MDL-35537 - Right align registration text on login page, when in RTL mode
[moodle.git] / lib / questionlib.php
blob8375ba6d3758491d63e55fc929650ea283f5d6dd
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Code for handling and processing questions
20 * This is code that is module independent, i.e., can be used by any module that
21 * uses questions, like quiz, lesson, ..
22 * This script also loads the questiontype classes
23 * Code for handling the editing of questions is in {@link question/editlib.php}
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
28 * @package moodlecore
29 * @subpackage questionbank
30 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 defined('MOODLE_INTERNAL') || die();
37 require_once($CFG->dirroot . '/question/engine/lib.php');
38 require_once($CFG->dirroot . '/question/type/questiontypebase.php');
42 /// CONSTANTS ///////////////////////////////////
44 /**
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
48 define("QUESTION_NUMANS", 10);
50 /**
51 * Constant determines the number of answer boxes supplied in the editing
52 * form for multiple choice and similar question types to start with, with
53 * the option of adding QUESTION_NUMANS_ADD more answers.
55 define("QUESTION_NUMANS_START", 3);
57 /**
58 * Constant determines the number of answer boxes to add in the editing
59 * form for multiple choice and similar question types when the user presses
60 * 'add form fields button'.
62 define("QUESTION_NUMANS_ADD", 3);
64 /**
65 * Move one question type in a list of question types. If you try to move one element
66 * off of the end, nothing will change.
68 * @param array $sortedqtypes An array $qtype => anything.
69 * @param string $tomove one of the keys from $sortedqtypes
70 * @param integer $direction +1 or -1
71 * @return array an array $index => $qtype, with $index from 0 to n in order, and
72 * the $qtypes in the same order as $sortedqtypes, except that $tomove will
73 * have been moved one place.
75 function question_reorder_qtypes($sortedqtypes, $tomove, $direction) {
76 $neworder = array_keys($sortedqtypes);
77 // Find the element to move.
78 $key = array_search($tomove, $neworder);
79 if ($key === false) {
80 return $neworder;
82 // Work out the other index.
83 $otherkey = $key + $direction;
84 if (!isset($neworder[$otherkey])) {
85 return $neworder;
87 // Do the swap.
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
91 return $neworder;
94 /**
95 * Save a new question type order to the config_plugins table.
96 * @global object
97 * @param $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
98 * @param $config get_config('question'), if you happen to have it around, to save one DB query.
100 function question_save_qtype_order($neworder, $config = null) {
101 global $DB;
103 if (is_null($config)) {
104 $config = get_config('question');
107 foreach ($neworder as $index => $qtype) {
108 $sortvar = $qtype . '_sortorder';
109 if (!isset($config->$sortvar) || $config->$sortvar != $index + 1) {
110 set_config($sortvar, $index + 1, 'question');
115 /// FUNCTIONS //////////////////////////////////////////////////////
118 * 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) {
135 global $CFG;
137 if (question_engine::questions_in_use($questionids)) {
138 return true;
141 foreach (get_plugin_list('mod') as $module => $path) {
142 $lib = $path . '/lib.php';
143 if (is_readable($lib)) {
144 include_once($lib);
146 $fn = $module . '_questions_in_use';
147 if (function_exists($fn)) {
148 if ($fn($questionids)) {
149 return true;
151 } else {
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)) {
159 return true;
167 return false;
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
173 * hidden.
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) {
180 global $DB;
181 if (is_object($context)) {
182 $contextid = $context->id;
183 } else if (is_numeric($context)) {
184 $contextid = $context;
185 } else {
186 print_error('invalidcontextinhasanyquestions', 'question');
188 return $DB->record_exists_sql("SELECT *
189 FROM {question} q
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();
208 return $grades;
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.
231 return false;
233 } else if ($matchgrades == 'nearest') {
234 // Work out nearest value
235 $best = false;
236 $bestmismatch = 2;
237 foreach ($gradeoptionsfull as $value => $option) {
238 $newmismatch = abs($grade - $value);
239 if ($newmismatch < $bestmismatch) {
240 $best = $value;
241 $bestmismatch = $newmismatch;
244 return $best;
246 } else {
247 // Unknow option passed.
248 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
249 ' passed to match_grade_options');
254 * @deprecated Since Moodle 2.1. Use {@link question_category_in_use} instead.
255 * @param integer $categoryid a question category id.
256 * @param boolean $recursive whether to check child categories too.
257 * @return boolean whether any question in this category is in use.
259 function question_category_isused($categoryid, $recursive = false) {
260 throw new coding_exception('question_category_isused has been deprectated. ' .
261 'Please use question_category_in_use instead.');
265 * Tests whether any question in a category is used by any part of Moodle.
267 * @param integer $categoryid a question category id.
268 * @param boolean $recursive whether to check child categories too.
269 * @return boolean whether any question in this category is in use.
271 function question_category_in_use($categoryid, $recursive = false) {
272 global $DB;
274 //Look at each question in the category
275 if ($questions = $DB->get_records_menu('question',
276 array('category' => $categoryid), '', 'id, 1')) {
277 if (questions_in_use(array_keys($questions))) {
278 return true;
281 if (!$recursive) {
282 return false;
285 //Look under child categories recursively
286 if ($children = $DB->get_records('question_categories',
287 array('parent' => $categoryid), '', 'id, 1')) {
288 foreach ($children as $child) {
289 if (question_category_in_use($child->id, $recursive)) {
290 return true;
295 return false;
299 * Deletes question and all associated data from the database
301 * It will not delete a question if it is used by an activity module
302 * @param object $question The question being deleted
304 function question_delete_question($questionid) {
305 global $DB;
307 $question = $DB->get_record_sql('
308 SELECT q.*, qc.contextid
309 FROM {question} q
310 JOIN {question_categories} qc ON qc.id = q.category
311 WHERE q.id = ?', array($questionid));
312 if (!$question) {
313 // In some situations, for example if this was a child of a
314 // Cloze question that was previously deleted, the question may already
315 // have gone. In this case, just do nothing.
316 return;
319 // Do not delete a question if it is used by an activity module
320 if (questions_in_use(array($questionid))) {
321 return;
324 // Check permissions.
325 question_require_capability_on($question, 'edit');
327 $dm = new question_engine_data_mapper();
328 $dm->delete_previews($questionid);
330 // delete questiontype-specific data
331 question_bank::get_qtype($question->qtype, false)->delete_question(
332 $questionid, $question->contextid);
334 // Now recursively delete all child questions
335 if ($children = $DB->get_records('question',
336 array('parent' => $questionid), '', 'id, qtype')) {
337 foreach ($children as $child) {
338 if ($child->id != $questionid) {
339 question_delete_question($child->id);
344 // Finally delete the question record itself
345 $DB->delete_records('question', array('id' => $questionid));
349 * All question categories and their questions are deleted for this course.
351 * @param stdClass $course an object representing the activity
352 * @param boolean $feedback to specify if the process must output a summary of its work
353 * @return boolean
355 function question_delete_course($course, $feedback=true) {
356 global $DB, $OUTPUT;
358 //To store feedback to be showed at the end of the process
359 $feedbackdata = array();
361 //Cache some strings
362 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
363 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
364 $categoriescourse = $DB->get_records('question_categories',
365 array('contextid' => $coursecontext->id), 'parent', 'id, parent, name, contextid');
367 if ($categoriescourse) {
369 //Sort categories following their tree (parent-child) relationships
370 //this will make the feedback more readable
371 $categoriescourse = sort_categories_by_tree($categoriescourse);
373 foreach ($categoriescourse as $category) {
375 //Delete it completely (questions and category itself)
376 //deleting questions
377 if ($questions = $DB->get_records('question',
378 array('category' => $category->id), '', 'id,qtype')) {
379 foreach ($questions as $question) {
380 question_delete_question($question->id);
382 $DB->delete_records("question", array("category" => $category->id));
384 //delete the category
385 $DB->delete_records('question_categories', array('id' => $category->id));
387 //Fill feedback
388 $feedbackdata[] = array($category->name, $strcatdeleted);
390 //Inform about changes performed if feedback is enabled
391 if ($feedback) {
392 $table = new html_table();
393 $table->head = array(get_string('category', 'quiz'), get_string('action'));
394 $table->data = $feedbackdata;
395 echo html_writer::table($table);
398 return true;
402 * Category is about to be deleted,
403 * 1/ All question categories and their questions are deleted for this course category.
404 * 2/ All questions are moved to new category
406 * @param object $category course category object
407 * @param object $newcategory empty means everything deleted, otherwise id of
408 * category where content moved
409 * @param boolean $feedback to specify if the process must output a summary of its work
410 * @return boolean
412 function question_delete_course_category($category, $newcategory, $feedback=true) {
413 global $DB, $OUTPUT;
415 $context = get_context_instance(CONTEXT_COURSECAT, $category->id);
416 if (empty($newcategory)) {
417 $feedbackdata = array(); // To store feedback to be showed at the end of the process
418 $rescueqcategory = null; // See the code around the call to question_save_from_deletion.
419 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
421 // Loop over question categories.
422 if ($categories = $DB->get_records('question_categories',
423 array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
424 foreach ($categories as $category) {
426 // Deal with any questions in the category.
427 if ($questions = $DB->get_records('question',
428 array('category' => $category->id), '', 'id,qtype')) {
430 // Try to delete each question.
431 foreach ($questions as $question) {
432 question_delete_question($question->id);
435 // Check to see if there were any questions that were kept because
436 // they are still in use somehow, even though quizzes in courses
437 // in this category will already have been deteted. This could
438 // happen, for example, if questions are added to a course,
439 // and then that course is moved to another category (MDL-14802).
440 $questionids = $DB->get_records_menu('question',
441 array('category'=>$category->id), '', 'id, 1');
442 if (!empty($questionids)) {
443 if (!$rescueqcategory = question_save_from_deletion(
444 array_keys($questionids), get_parent_contextid($context),
445 print_context_name($context), $rescueqcategory)) {
446 return false;
448 $feedbackdata[] = array($category->name,
449 get_string('questionsmovedto', 'question', $rescueqcategory->name));
453 // Now delete the category.
454 if (!$DB->delete_records('question_categories', array('id'=>$category->id))) {
455 return false;
457 $feedbackdata[] = array($category->name, $strcatdeleted);
459 } // End loop over categories.
462 // Output feedback if requested.
463 if ($feedback and $feedbackdata) {
464 $table = new html_table();
465 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
466 $table->data = $feedbackdata;
467 echo html_writer::table($table);
470 } else {
471 // Move question categories ot the new context.
472 if (!$newcontext = get_context_instance(CONTEXT_COURSECAT, $newcategory->id)) {
473 return false;
475 $DB->set_field('question_categories', 'contextid', $newcontext->id,
476 array('contextid'=>$context->id));
477 if ($feedback) {
478 $a = new stdClass();
479 $a->oldplace = print_context_name($context);
480 $a->newplace = print_context_name($newcontext);
481 echo $OUTPUT->notification(
482 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
486 return true;
490 * Enter description here...
492 * @param array $questionids of question ids
493 * @param object $newcontext the context to create the saved category in.
494 * @param string $oldplace a textual description of the think being deleted,
495 * e.g. from get_context_name
496 * @param object $newcategory
497 * @return mixed false on
499 function question_save_from_deletion($questionids, $newcontextid, $oldplace,
500 $newcategory = null) {
501 global $DB;
503 // Make a category in the parent context to move the questions to.
504 if (is_null($newcategory)) {
505 $newcategory = new stdClass();
506 $newcategory->parent = 0;
507 $newcategory->contextid = $newcontextid;
508 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
509 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
510 $newcategory->sortorder = 999;
511 $newcategory->stamp = make_unique_id_code();
512 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
515 // Move any remaining questions to the 'saved' category.
516 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
517 return false;
519 return $newcategory;
523 * All question categories and their questions are deleted for this activity.
525 * @param object $cm the course module object representing the activity
526 * @param boolean $feedback to specify if the process must output a summary of its work
527 * @return boolean
529 function question_delete_activity($cm, $feedback=true) {
530 global $DB, $OUTPUT;
532 //To store feedback to be showed at the end of the process
533 $feedbackdata = array();
535 //Cache some strings
536 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
537 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
538 if ($categoriesmods = $DB->get_records('question_categories',
539 array('contextid' => $modcontext->id), 'parent', 'id, parent, name, contextid')) {
540 //Sort categories following their tree (parent-child) relationships
541 //this will make the feedback more readable
542 $categoriesmods = sort_categories_by_tree($categoriesmods);
544 foreach ($categoriesmods as $category) {
546 //Delete it completely (questions and category itself)
547 //deleting questions
548 if ($questions = $DB->get_records('question',
549 array('category' => $category->id), '', 'id,qtype')) {
550 foreach ($questions as $question) {
551 question_delete_question($question->id);
553 $DB->delete_records("question", array("category"=>$category->id));
555 //delete the category
556 $DB->delete_records('question_categories', array('id'=>$category->id));
558 //Fill feedback
559 $feedbackdata[] = array($category->name, $strcatdeleted);
561 //Inform about changes performed if feedback is enabled
562 if ($feedback) {
563 $table = new html_table();
564 $table->head = array(get_string('category', 'quiz'), get_string('action'));
565 $table->data = $feedbackdata;
566 echo html_writer::table($table);
569 return true;
573 * This function should be considered private to the question bank, it is called from
574 * question/editlib.php question/contextmoveq.php and a few similar places to to the
575 * work of acutally moving questions and associated data. However, callers of this
576 * function also have to do other work, which is why you should not call this method
577 * directly from outside the questionbank.
579 * @param array $questionids of question ids.
580 * @param integer $newcategoryid the id of the category to move to.
582 function question_move_questions_to_category($questionids, $newcategoryid) {
583 global $DB;
585 $newcontextid = $DB->get_field('question_categories', 'contextid',
586 array('id' => $newcategoryid));
587 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
588 $questions = $DB->get_records_sql("
589 SELECT q.id, q.qtype, qc.contextid
590 FROM {question} q
591 JOIN {question_categories} qc ON q.category = qc.id
592 WHERE q.id $questionidcondition", $params);
593 foreach ($questions as $question) {
594 if ($newcontextid != $question->contextid) {
595 question_bank::get_qtype($question->qtype)->move_files(
596 $question->id, $question->contextid, $newcontextid);
600 // Move the questions themselves.
601 $DB->set_field_select('question', 'category', $newcategoryid,
602 "id $questionidcondition", $params);
604 // Move any subquestions belonging to them.
605 $DB->set_field_select('question', 'category', $newcategoryid,
606 "parent $questionidcondition", $params);
608 // TODO Deal with datasets.
610 return true;
614 * This function helps move a question cateogry to a new context by moving all
615 * the files belonging to all the questions to the new context.
616 * Also moves subcategories.
617 * @param integer $categoryid the id of the category being moved.
618 * @param integer $oldcontextid the old context id.
619 * @param integer $newcontextid the new context id.
621 function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
622 global $DB;
624 $questionids = $DB->get_records_menu('question',
625 array('category' => $categoryid), '', 'id,qtype');
626 foreach ($questionids as $questionid => $qtype) {
627 question_bank::get_qtype($qtype)->move_files(
628 $questionid, $oldcontextid, $newcontextid);
631 $subcatids = $DB->get_records_menu('question_categories',
632 array('parent' => $categoryid), '', 'id,1');
633 foreach ($subcatids as $subcatid => $notused) {
634 $DB->set_field('question_categories', 'contextid', $newcontextid,
635 array('id' => $subcatid));
636 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
641 * Generate the URL for starting a new preview of a given question with the given options.
642 * @param integer $questionid the question to preview.
643 * @param string $preferredbehaviour the behaviour to use for the preview.
644 * @param float $maxmark the maximum to mark the question out of.
645 * @param question_display_options $displayoptions the display options to use.
646 * @param int $variant the variant of the question to preview. If null, one will
647 * be picked randomly.
648 * @param object $context context to run the preview in (affects things like
649 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
650 * @return string the URL.
652 function question_preview_url($questionid, $preferredbehaviour = null,
653 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
655 $params = array('id' => $questionid);
657 if (is_null($context)) {
658 global $PAGE;
659 $context = $PAGE->context;
661 if ($context->contextlevel == CONTEXT_MODULE) {
662 $params['cmid'] = $context->instanceid;
663 } else if ($context->contextlevel == CONTEXT_COURSE) {
664 $params['courseid'] = $context->instanceid;
667 if (!is_null($preferredbehaviour)) {
668 $params['behaviour'] = $preferredbehaviour;
671 if (!is_null($maxmark)) {
672 $params['maxmark'] = $maxmark;
675 if (!is_null($displayoptions)) {
676 $params['correctness'] = $displayoptions->correctness;
677 $params['marks'] = $displayoptions->marks;
678 $params['markdp'] = $displayoptions->markdp;
679 $params['feedback'] = (bool) $displayoptions->feedback;
680 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
681 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
682 $params['history'] = (bool) $displayoptions->history;
685 if ($variant) {
686 $params['variant'] = $variant;
689 return new moodle_url('/question/preview.php', $params);
693 * @return array that can be passed as $params to the {@link popup_action} constructor.
695 function question_preview_popup_params() {
696 return array(
697 'height' => 600,
698 'width' => 800,
703 * Given a list of ids, load the basic information about a set of questions from
704 * the questions table. The $join and $extrafields arguments can be used together
705 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
706 * read the code below to see how the SQL is assembled. Throws exceptions on error.
708 * @global object
709 * @global object
710 * @param array $questionids array of question ids.
711 * @param string $extrafields extra SQL code to be added to the query.
712 * @param string $join extra SQL code to be added to the query.
713 * @param array $extraparams values for any placeholders in $join.
714 * You are strongly recommended to use named placeholder.
716 * @return array partially complete question objects. You need to call get_question_options
717 * on them before they can be properly used.
719 function question_preload_questions($questionids, $extrafields = '', $join = '',
720 $extraparams = array()) {
721 global $DB;
722 if (empty($questionids)) {
723 return array();
725 if ($join) {
726 $join = ' JOIN '.$join;
728 if ($extrafields) {
729 $extrafields = ', ' . $extrafields;
731 list($questionidcondition, $params) = $DB->get_in_or_equal(
732 $questionids, SQL_PARAMS_NAMED, 'qid0000');
733 $sql = 'SELECT q.*, qc.contextid' . $extrafields . ' FROM {question} q
734 JOIN {question_categories} qc ON q.category = qc.id' .
735 $join .
736 ' WHERE q.id ' . $questionidcondition;
738 // Load the questions
739 if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) {
740 return array();
743 foreach ($questions as $question) {
744 $question->_partiallyloaded = true;
747 // Note, a possible optimisation here would be to not load the TEXT fields
748 // (that is, questiontext and generalfeedback) here, and instead load them in
749 // question_load_questions. That would add one DB query, but reduce the amount
750 // of data transferred most of the time. I am not going to do this optimisation
751 // until it is shown to be worthwhile.
753 return $questions;
757 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
758 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
759 * read the code below to see how the SQL is assembled. Throws exceptions on error.
761 * @param array $questionids array of question ids.
762 * @param string $extrafields extra SQL code to be added to the query.
763 * @param string $join extra SQL code to be added to the query.
764 * @param array $extraparams values for any placeholders in $join.
765 * You are strongly recommended to use named placeholder.
767 * @return array question objects.
769 function question_load_questions($questionids, $extrafields = '', $join = '') {
770 $questions = question_preload_questions($questionids, $extrafields, $join);
772 // Load the question type specific information
773 if (!get_question_options($questions)) {
774 return 'Could not load the question options';
777 return $questions;
781 * Private function to factor common code out of get_question_options().
783 * @param object $question the question to tidy.
784 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
786 function _tidy_question($question, $loadtags = false) {
787 global $CFG;
789 // Load question-type specific fields.
790 if (!question_bank::is_qtype_installed($question->qtype)) {
791 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
792 'qtype_missingtype')) . $question->questiontext;
794 question_bank::get_qtype($question->qtype)->get_question_options($question);
796 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
797 $question->defaultmark += 0;
798 $question->penalty += 0;
800 if (isset($question->_partiallyloaded)) {
801 unset($question->_partiallyloaded);
804 if ($loadtags && !empty($CFG->usetags)) {
805 require_once($CFG->dirroot . '/tag/lib.php');
806 $question->tags = tag_get_tags_array('question', $question->id);
811 * Updates the question objects with question type specific
812 * information by calling {@link get_question_options()}
814 * Can be called either with an array of question objects or with a single
815 * question object.
817 * @param mixed $questions Either an array of question objects to be updated
818 * or just a single question object
819 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
820 * @return bool Indicates success or failure.
822 function get_question_options(&$questions, $loadtags = false) {
823 if (is_array($questions)) { // deal with an array of questions
824 foreach ($questions as $i => $notused) {
825 _tidy_question($questions[$i], $loadtags);
827 } else { // deal with single question
828 _tidy_question($questions, $loadtags);
830 return true;
834 * Print the icon for the question type
836 * @param object $question The question object for which the icon is required.
837 * Only $question->qtype is used.
838 * @return string the HTML for the img tag.
840 function print_question_icon($question) {
841 global $PAGE;
842 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
846 * Creates a stamp that uniquely identifies this version of the question
848 * In future we want this to use a hash of the question data to guarantee that
849 * identical versions have the same version stamp.
851 * @param object $question
852 * @return string A unique version stamp
854 function question_hash($question) {
855 return make_unique_id_code();
858 /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
860 * Saves question options
862 * Simply calls the question type specific save_question_options() method.
864 function save_question_options($question) {
865 question_bank::get_qtype($question->qtype)->save_question_options($question);
868 /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
871 * returns the categories with their names ordered following parent-child relationships
872 * finally it tries to return pending categories (those being orphaned, whose parent is
873 * incorrect) to avoid missing any category from original array.
875 function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
876 global $DB;
878 $children = array();
879 $keys = array_keys($categories);
881 foreach ($keys as $key) {
882 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
883 $children[$key] = $categories[$key];
884 $categories[$key]->processed = true;
885 $children = $children + sort_categories_by_tree(
886 $categories, $children[$key]->id, $level+1);
889 //If level = 1, we have finished, try to look for non processed categories
890 // (bad parent) and sort them too
891 if ($level == 1) {
892 foreach ($keys as $key) {
893 // If not processed and it's a good candidate to start (because its
894 // parent doesn't exist in the course)
895 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
896 array('contextid' => $categories[$key]->contextid,
897 'id' => $categories[$key]->parent))) {
898 $children[$key] = $categories[$key];
899 $categories[$key]->processed = true;
900 $children = $children + sort_categories_by_tree(
901 $categories, $children[$key]->id, $level + 1);
905 return $children;
909 * Private method, only for the use of add_indented_names().
911 * Recursively adds an indentedname field to each category, starting with the category
912 * with id $id, and dealing with that category and all its children, and
913 * return a new array, with those categories in the right order.
915 * @param array $categories an array of categories which has had childids
916 * fields added by flatten_category_tree(). Passed by reference for
917 * performance only. It is not modfied.
918 * @param int $id the category to start the indenting process from.
919 * @param int $depth the indent depth. Used in recursive calls.
920 * @return array a new array of categories, in the right order for the tree.
922 function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
924 // Indent the name of this category.
925 $newcategories = array();
926 $newcategories[$id] = $categories[$id];
927 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
928 $categories[$id]->name;
930 // Recursively indent the children.
931 foreach ($categories[$id]->childids as $childid) {
932 if ($childid != $nochildrenof) {
933 $newcategories = $newcategories + flatten_category_tree(
934 $categories, $childid, $depth + 1, $nochildrenof);
938 // Remove the childids array that were temporarily added.
939 unset($newcategories[$id]->childids);
941 return $newcategories;
945 * Format categories into an indented list reflecting the tree structure.
947 * @param array $categories An array of category objects, for example from the.
948 * @return array The formatted list of categories.
950 function add_indented_names($categories, $nochildrenof = -1) {
952 // Add an array to each category to hold the child category ids. This array
953 // will be removed again by flatten_category_tree(). It should not be used
954 // outside these two functions.
955 foreach (array_keys($categories) as $id) {
956 $categories[$id]->childids = array();
959 // Build the tree structure, and record which categories are top-level.
960 // We have to be careful, because the categories array may include published
961 // categories from other courses, but not their parents.
962 $toplevelcategoryids = array();
963 foreach (array_keys($categories) as $id) {
964 if (!empty($categories[$id]->parent) &&
965 array_key_exists($categories[$id]->parent, $categories)) {
966 $categories[$categories[$id]->parent]->childids[] = $id;
967 } else {
968 $toplevelcategoryids[] = $id;
972 // Flatten the tree to and add the indents.
973 $newcategories = array();
974 foreach ($toplevelcategoryids as $id) {
975 $newcategories = $newcategories + flatten_category_tree(
976 $categories, $id, 0, $nochildrenof);
979 return $newcategories;
983 * Output a select menu of question categories.
985 * Categories from this course and (optionally) published categories from other courses
986 * are included. Optionally, only categories the current user may edit can be included.
988 * @param integer $courseid the id of the course to get the categories for.
989 * @param integer $published if true, include publised categories from other courses.
990 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
991 * @param integer $selected optionally, the id of a category to be selected by
992 * default in the dropdown.
994 function question_category_select_menu($contexts, $top = false, $currentcat = 0,
995 $selected = "", $nochildrenof = -1) {
996 global $OUTPUT;
997 $categoriesarray = question_category_options($contexts, $top, $currentcat,
998 false, $nochildrenof);
999 if ($selected) {
1000 $choose = '';
1001 } else {
1002 $choose = 'choosedots';
1004 $options = array();
1005 foreach ($categoriesarray as $group => $opts) {
1006 $options[] = array($group => $opts);
1008 echo html_writer::label($selected, 'menucategory', false, array('class' => 'accesshide'));
1009 echo html_writer::select($options, 'category', $selected, $choose);
1013 * @param integer $contextid a context id.
1014 * @return object the default question category for that context, or false if none.
1016 function question_get_default_category($contextid) {
1017 global $DB;
1018 $category = $DB->get_records('question_categories',
1019 array('contextid' => $contextid), 'id', '*', 0, 1);
1020 if (!empty($category)) {
1021 return reset($category);
1022 } else {
1023 return false;
1028 * Gets the default category in the most specific context.
1029 * If no categories exist yet then default ones are created in all contexts.
1031 * @param array $contexts The context objects for this context and all parent contexts.
1032 * @return object The default category - the category in the course context
1034 function question_make_default_categories($contexts) {
1035 global $DB;
1036 static $preferredlevels = array(
1037 CONTEXT_COURSE => 4,
1038 CONTEXT_MODULE => 3,
1039 CONTEXT_COURSECAT => 2,
1040 CONTEXT_SYSTEM => 1,
1043 $toreturn = null;
1044 $preferredness = 0;
1045 // If it already exists, just return it.
1046 foreach ($contexts as $key => $context) {
1047 if (!$exists = $DB->record_exists("question_categories",
1048 array('contextid' => $context->id))) {
1049 // Otherwise, we need to make one
1050 $category = new stdClass();
1051 $contextname = print_context_name($context, false, true);
1052 $category->name = get_string('defaultfor', 'question', $contextname);
1053 $category->info = get_string('defaultinfofor', 'question', $contextname);
1054 $category->contextid = $context->id;
1055 $category->parent = 0;
1056 // By default, all categories get this number, and are sorted alphabetically.
1057 $category->sortorder = 999;
1058 $category->stamp = make_unique_id_code();
1059 $category->id = $DB->insert_record('question_categories', $category);
1060 } else {
1061 $category = question_get_default_category($context->id);
1063 $thispreferredness = $preferredlevels[$context->contextlevel];
1064 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1065 $thispreferredness += 10;
1067 if ($thispreferredness > $preferredness) {
1068 $toreturn = $category;
1069 $preferredness = $thispreferredness;
1073 if (!is_null($toreturn)) {
1074 $toreturn = clone($toreturn);
1076 return $toreturn;
1080 * Get all the category objects, including a count of the number of questions in that category,
1081 * for all the categories in the lists $contexts.
1083 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1084 * @param string $sortorder used as the ORDER BY clause in the select statement.
1085 * @return array of category objects.
1087 function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
1088 global $DB;
1089 return $DB->get_records_sql("
1090 SELECT c.*, (SELECT count(1) FROM {question} q
1091 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1092 FROM {question_categories} c
1093 WHERE c.contextid IN ($contexts)
1094 ORDER BY $sortorder");
1098 * Output an array of question categories.
1100 function question_category_options($contexts, $top = false, $currentcat = 0,
1101 $popupform = false, $nochildrenof = -1) {
1102 global $CFG;
1103 $pcontexts = array();
1104 foreach ($contexts as $context) {
1105 $pcontexts[] = $context->id;
1107 $contextslist = join($pcontexts, ', ');
1109 $categories = get_categories_for_contexts($contextslist);
1111 $categories = question_add_context_in_key($categories);
1113 if ($top) {
1114 $categories = question_add_tops($categories, $pcontexts);
1116 $categories = add_indented_names($categories, $nochildrenof);
1118 // sort cats out into different contexts
1119 $categoriesarray = array();
1120 foreach ($pcontexts as $contextid) {
1121 $context = context::instance_by_id($contextid);
1122 $contextstring = $context->get_context_name(true, true);
1123 foreach ($categories as $category) {
1124 if ($category->contextid == $contextid) {
1125 $cid = $category->id;
1126 if ($currentcat != $cid || $currentcat == 0) {
1127 $countstring = !empty($category->questioncount) ?
1128 " ($category->questioncount)" : '';
1129 $categoriesarray[$contextstring][$cid] =
1130 format_string($category->indentedname, true,
1131 array('context' => $context)) . $countstring;
1136 if ($popupform) {
1137 $popupcats = array();
1138 foreach ($categoriesarray as $contextstring => $optgroup) {
1139 $group = array();
1140 foreach ($optgroup as $key => $value) {
1141 $key = str_replace($CFG->wwwroot, '', $key);
1142 $group[$key] = $value;
1144 $popupcats[] = array($contextstring => $group);
1146 return $popupcats;
1147 } else {
1148 return $categoriesarray;
1152 function question_add_context_in_key($categories) {
1153 $newcatarray = array();
1154 foreach ($categories as $id => $category) {
1155 $category->parent = "$category->parent,$category->contextid";
1156 $category->id = "$category->id,$category->contextid";
1157 $newcatarray["$id,$category->contextid"] = $category;
1159 return $newcatarray;
1162 function question_add_tops($categories, $pcontexts) {
1163 $topcats = array();
1164 foreach ($pcontexts as $context) {
1165 $newcat = new stdClass();
1166 $newcat->id = "0,$context";
1167 $newcat->name = get_string('top');
1168 $newcat->parent = -1;
1169 $newcat->contextid = $context;
1170 $topcats["0,$context"] = $newcat;
1172 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1173 return array_merge($topcats, $categories);
1177 * @return array of question category ids of the category and all subcategories.
1179 function question_categorylist($categoryid) {
1180 global $DB;
1182 $subcategories = $DB->get_records('question_categories',
1183 array('parent' => $categoryid), 'sortorder ASC', 'id, 1');
1185 $categorylist = array($categoryid);
1186 foreach ($subcategories as $subcategory) {
1187 $categorylist = array_merge($categorylist, question_categorylist($subcategory->id));
1190 return $categorylist;
1193 //===========================
1194 // Import/Export Functions
1195 //===========================
1198 * Get list of available import or export formats
1199 * @param string $type 'import' if import list, otherwise export list assumed
1200 * @return array sorted list of import/export formats available
1202 function get_import_export_formats($type) {
1203 global $CFG;
1204 require_once($CFG->dirroot . '/question/format.php');
1206 $formatclasses = get_plugin_list_with_class('qformat', '', 'format.php');
1208 $fileformatname = array();
1209 foreach ($formatclasses as $component => $formatclass) {
1211 $format = new $formatclass();
1212 if ($type == 'import') {
1213 $provided = $format->provide_import();
1214 } else {
1215 $provided = $format->provide_export();
1218 if ($provided) {
1219 list($notused, $fileformat) = explode('_', $component, 2);
1220 $fileformatnames[$fileformat] = get_string('pluginname', $component);
1224 collatorlib::asort($fileformatnames);
1225 return $fileformatnames;
1230 * Create a reasonable default file name for exporting questions from a particular
1231 * category.
1232 * @param object $course the course the questions are in.
1233 * @param object $category the question category.
1234 * @return string the filename.
1236 function question_default_export_filename($course, $category) {
1237 // We build a string that is an appropriate name (questions) from the lang pack,
1238 // then the corse shortname, then the question category name, then a timestamp.
1240 $base = clean_filename(get_string('exportfilename', 'question'));
1242 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1243 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1245 $shortname = clean_filename($course->shortname);
1246 if ($shortname == '' || $shortname == '_' ) {
1247 $shortname = $course->id;
1250 $categoryname = clean_filename(format_string($category->name));
1252 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1254 return $export_name;
1258 * Converts contextlevels to strings and back to help with reading/writing contexts
1259 * to/from import/export files.
1261 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1262 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1264 class context_to_string_translator{
1266 * @var array used to translate between contextids and strings for this context.
1268 protected $contexttostringarray = array();
1270 public function __construct($contexts) {
1271 $this->generate_context_to_string_array($contexts);
1274 public function context_to_string($contextid) {
1275 return $this->contexttostringarray[$contextid];
1278 public function string_to_context($contextname) {
1279 $contextid = array_search($contextname, $this->contexttostringarray);
1280 return $contextid;
1283 protected function generate_context_to_string_array($contexts) {
1284 if (!$this->contexttostringarray) {
1285 $catno = 1;
1286 foreach ($contexts as $context) {
1287 switch ($context->contextlevel) {
1288 case CONTEXT_MODULE :
1289 $contextstring = 'module';
1290 break;
1291 case CONTEXT_COURSE :
1292 $contextstring = 'course';
1293 break;
1294 case CONTEXT_COURSECAT :
1295 $contextstring = "cat$catno";
1296 $catno++;
1297 break;
1298 case CONTEXT_SYSTEM :
1299 $contextstring = 'system';
1300 break;
1302 $this->contexttostringarray[$context->id] = $contextstring;
1310 * Check capability on category
1312 * @param mixed $question object or id
1313 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1314 * @param integer $cachecat useful to cache all question records in a category
1315 * @return boolean this user has the capability $cap for this question $question?
1317 function question_has_capability_on($question, $cap, $cachecat = -1) {
1318 global $USER, $DB;
1320 // these are capabilities on existing questions capabilties are
1321 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1322 $question_questioncaps = array('edit', 'view', 'use', 'move');
1323 static $questions = array();
1324 static $categories = array();
1325 static $cachedcat = array();
1326 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
1327 $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
1328 $cachedcat[] = $cachecat;
1330 if (!is_object($question)) {
1331 if (!isset($questions[$question])) {
1332 if (!$questions[$question] = $DB->get_record('question',
1333 array('id' => $question), 'id,category,createdby')) {
1334 print_error('questiondoesnotexist', 'question');
1337 $question = $questions[$question];
1339 if (empty($question->category)) {
1340 // This can happen when we have created a fake 'missingtype' question to
1341 // take the place of a deleted question.
1342 return false;
1344 if (!isset($categories[$question->category])) {
1345 if (!$categories[$question->category] = $DB->get_record('question_categories',
1346 array('id'=>$question->category))) {
1347 print_error('invalidcategory', 'quiz');
1350 $category = $categories[$question->category];
1351 $context = get_context_instance_by_id($category->contextid);
1353 if (array_search($cap, $question_questioncaps)!== false) {
1354 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1355 if ($question->createdby == $USER->id) {
1356 return has_capability('moodle/question:' . $cap . 'mine', $context);
1357 } else {
1358 return false;
1360 } else {
1361 return true;
1363 } else {
1364 return has_capability('moodle/question:' . $cap, $context);
1370 * Require capability on question.
1372 function question_require_capability_on($question, $cap) {
1373 if (!question_has_capability_on($question, $cap)) {
1374 print_error('nopermissions', '', '', $cap);
1376 return true;
1380 * Get the real state - the correct question id and answer - for a random
1381 * question.
1382 * @param object $state with property answer.
1383 * @return mixed return integer real question id or false if there was an
1384 * error..
1386 function question_get_real_state($state) {
1387 global $OUTPUT;
1388 $realstate = clone($state);
1389 $matches = array();
1390 if (!preg_match('|^random([0-9]+)-(.*)|', $state->answer, $matches)) {
1391 echo $OUTPUT->notification(get_string('errorrandom', 'quiz_statistics'));
1392 return false;
1393 } else {
1394 $realstate->question = $matches[1];
1395 $realstate->answer = $matches[2];
1396 return $realstate;
1401 * @param object $context a context
1402 * @return string A URL for editing questions in this context.
1404 function question_edit_url($context) {
1405 global $CFG, $SITE;
1406 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1407 return false;
1409 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1410 $defaultcategory = question_get_default_category($context->id);
1411 if ($defaultcategory) {
1412 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1414 switch ($context->contextlevel) {
1415 case CONTEXT_SYSTEM:
1416 return $baseurl . 'courseid=' . $SITE->id;
1417 case CONTEXT_COURSECAT:
1418 // This is nasty, becuase we can only edit questions in a course
1419 // context at the moment, so for now we just return false.
1420 return false;
1421 case CONTEXT_COURSE:
1422 return $baseurl . 'courseid=' . $context->instanceid;
1423 case CONTEXT_MODULE:
1424 return $baseurl . 'cmid=' . $context->instanceid;
1430 * Adds question bank setting links to the given navigation node if caps are met.
1432 * @param navigation_node $navigationnode The navigation node to add the question branch to
1433 * @param object $context
1434 * @return navigation_node Returns the question branch that was added
1436 function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1437 global $PAGE;
1439 if ($context->contextlevel == CONTEXT_COURSE) {
1440 $params = array('courseid'=>$context->instanceid);
1441 } else if ($context->contextlevel == CONTEXT_MODULE) {
1442 $params = array('cmid'=>$context->instanceid);
1443 } else {
1444 return;
1447 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1448 $params['cat'] = $cat;
1451 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1452 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
1454 $contexts = new question_edit_contexts($context);
1455 if ($contexts->have_one_edit_tab_cap('questions')) {
1456 $questionnode->add(get_string('questions', 'quiz'), new moodle_url(
1457 '/question/edit.php', $params), navigation_node::TYPE_SETTING);
1459 if ($contexts->have_one_edit_tab_cap('categories')) {
1460 $questionnode->add(get_string('categories', 'quiz'), new moodle_url(
1461 '/question/category.php', $params), navigation_node::TYPE_SETTING);
1463 if ($contexts->have_one_edit_tab_cap('import')) {
1464 $questionnode->add(get_string('import', 'quiz'), new moodle_url(
1465 '/question/import.php', $params), navigation_node::TYPE_SETTING);
1467 if ($contexts->have_one_edit_tab_cap('export')) {
1468 $questionnode->add(get_string('export', 'quiz'), new moodle_url(
1469 '/question/export.php', $params), navigation_node::TYPE_SETTING);
1472 return $questionnode;
1476 * @return array all the capabilities that relate to accessing particular questions.
1478 function question_get_question_capabilities() {
1479 return array(
1480 'moodle/question:add',
1481 'moodle/question:editmine',
1482 'moodle/question:editall',
1483 'moodle/question:viewmine',
1484 'moodle/question:viewall',
1485 'moodle/question:usemine',
1486 'moodle/question:useall',
1487 'moodle/question:movemine',
1488 'moodle/question:moveall',
1493 * @return array all the question bank capabilities.
1495 function question_get_all_capabilities() {
1496 $caps = question_get_question_capabilities();
1497 $caps[] = 'moodle/question:managecategory';
1498 $caps[] = 'moodle/question:flag';
1499 return $caps;
1504 * Tracks all the contexts related to the one where we are currently editing
1505 * questions, and provides helper methods to check permissions.
1507 * @copyright 2007 Jamie Pratt me@jamiep.org
1508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1510 class question_edit_contexts {
1512 public static $caps = array(
1513 'editq' => array('moodle/question:add',
1514 'moodle/question:editmine',
1515 'moodle/question:editall',
1516 'moodle/question:viewmine',
1517 'moodle/question:viewall',
1518 'moodle/question:usemine',
1519 'moodle/question:useall',
1520 'moodle/question:movemine',
1521 'moodle/question:moveall'),
1522 'questions'=>array('moodle/question:add',
1523 'moodle/question:editmine',
1524 'moodle/question:editall',
1525 'moodle/question:viewmine',
1526 'moodle/question:viewall',
1527 'moodle/question:movemine',
1528 'moodle/question:moveall'),
1529 'categories'=>array('moodle/question:managecategory'),
1530 'import'=>array('moodle/question:add'),
1531 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1533 protected $allcontexts;
1536 * Constructor
1537 * @param context the current context.
1539 public function __construct(context $thiscontext) {
1540 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
1544 * @return array all parent contexts
1546 public function all() {
1547 return $this->allcontexts;
1551 * @return object lowest context which must be either the module or course context
1553 public function lowest() {
1554 return $this->allcontexts[0];
1558 * @param string $cap capability
1559 * @return array parent contexts having capability, zero based index
1561 public function having_cap($cap) {
1562 $contextswithcap = array();
1563 foreach ($this->allcontexts as $context) {
1564 if (has_capability($cap, $context)) {
1565 $contextswithcap[] = $context;
1568 return $contextswithcap;
1572 * @param array $caps capabilities
1573 * @return array parent contexts having at least one of $caps, zero based index
1575 public function having_one_cap($caps) {
1576 $contextswithacap = array();
1577 foreach ($this->allcontexts as $context) {
1578 foreach ($caps as $cap) {
1579 if (has_capability($cap, $context)) {
1580 $contextswithacap[] = $context;
1581 break; //done with caps loop
1585 return $contextswithacap;
1589 * @param string $tabname edit tab name
1590 * @return array parent contexts having at least one of $caps, zero based index
1592 public function having_one_edit_tab_cap($tabname) {
1593 return $this->having_one_cap(self::$caps[$tabname]);
1597 * @return those contexts where a user can add a question and then use it.
1599 public function having_add_and_use() {
1600 $contextswithcap = array();
1601 foreach ($this->allcontexts as $context) {
1602 if (!has_capability('moodle/question:add', $context)) {
1603 continue;
1605 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1606 continue;
1608 $contextswithcap[] = $context;
1610 return $contextswithcap;
1614 * Has at least one parent context got the cap $cap?
1616 * @param string $cap capability
1617 * @return boolean
1619 public function have_cap($cap) {
1620 return (count($this->having_cap($cap)));
1624 * Has at least one parent context got one of the caps $caps?
1626 * @param array $caps capability
1627 * @return boolean
1629 public function have_one_cap($caps) {
1630 foreach ($caps as $cap) {
1631 if ($this->have_cap($cap)) {
1632 return true;
1635 return false;
1639 * Has at least one parent context got one of the caps for actions on $tabname
1641 * @param string $tabname edit tab name
1642 * @return boolean
1644 public function have_one_edit_tab_cap($tabname) {
1645 return $this->have_one_cap(self::$caps[$tabname]);
1649 * Throw error if at least one parent context hasn't got the cap $cap
1651 * @param string $cap capability
1653 public function require_cap($cap) {
1654 if (!$this->have_cap($cap)) {
1655 print_error('nopermissions', '', '', $cap);
1660 * Throw error if at least one parent context hasn't got one of the caps $caps
1662 * @param array $cap capabilities
1664 public function require_one_cap($caps) {
1665 if (!$this->have_one_cap($caps)) {
1666 $capsstring = join($caps, ', ');
1667 print_error('nopermissions', '', '', $capsstring);
1672 * Throw error if at least one parent context hasn't got one of the caps $caps
1674 * @param string $tabname edit tab name
1676 public function require_one_edit_tab_cap($tabname) {
1677 if (!$this->have_one_edit_tab_cap($tabname)) {
1678 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1685 * Helps call file_rewrite_pluginfile_urls with the right parameters.
1687 * @param string $text text being processed
1688 * @param string $file the php script used to serve files
1689 * @param int $contextid
1690 * @param string $component component
1691 * @param string $filearea filearea
1692 * @param array $ids other IDs will be used to check file permission
1693 * @param int $itemid
1694 * @param array $options
1695 * @return string
1697 function question_rewrite_question_urls($text, $file, $contextid, $component,
1698 $filearea, array $ids, $itemid, array $options=null) {
1700 $idsstr = '';
1701 if (!empty($ids)) {
1702 $idsstr .= implode('/', $ids);
1704 if ($itemid !== null) {
1705 $idsstr .= '/' . $itemid;
1707 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1708 $filearea, $idsstr, $options);
1712 * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
1713 * text outside and attempt (for example, in the question bank listing or in the
1714 * quiz statistics report).
1716 * @param string $questiontext the question text.
1717 * @param int $contextid the context the text is being displayed in.
1718 * @param string $component component
1719 * @param array $ids other IDs will be used to check file permission
1720 * @param array $options
1721 * @return string $questiontext with URLs rewritten.
1723 function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
1724 $component, $questionid, $options=null) {
1726 return file_rewrite_pluginfile_urls($questiontext, 'pluginfile.php', $contextid,
1727 'question', 'questiontext_preview', "$component/$questionid", $options);
1731 * Send a file from the question text of a question.
1732 * @param int $questionid the question id
1733 * @param array $args the remaining file arguments (file path).
1734 * @param bool $forcedownload whether the user must be forced to download the file.
1736 function question_send_questiontext_file($questionid, $args, $forcedownload) {
1737 global $DB;
1739 $question = $DB->get_record_sql('
1740 SELECT q.id, qc.contextid
1741 FROM {question} q
1742 JOIN {question_categories} qc ON qc.id = q.category
1743 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
1745 $fs = get_file_storage();
1746 $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
1747 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1748 send_file_not_found();
1751 send_stored_file($file, 0, 0, $forcedownload);
1755 * Called by pluginfile.php to serve files related to the 'question' core
1756 * component and for files belonging to qtypes.
1758 * For files that relate to questions in a question_attempt, then we delegate to
1759 * a function in the component that owns the attempt (for example in the quiz,
1760 * or in core question preview) to get necessary inforation.
1762 * (Note that, at the moment, all question file areas relate to questions in
1763 * attempts, so the If at the start of the last paragraph is always true.)
1765 * Does not return, either calls send_file_not_found(); or serves the file.
1767 * @param object $course course settings object
1768 * @param object $context context object
1769 * @param string $component the name of the component we are serving files for.
1770 * @param string $filearea the name of the file area.
1771 * @param array $args the remaining bits of the file path.
1772 * @param bool $forcedownload whether the user must be forced to download the file.
1774 function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload) {
1775 global $DB, $CFG;
1777 if ($filearea === 'questiontext_preview') {
1778 $component = array_shift($args);
1779 $questionid = array_shift($args);
1781 component_callback($component, 'questiontext_preview_pluginfile', array(
1782 $context, $questionid, $args, $forcedownload));
1784 send_file_not_found();
1787 list($context, $course, $cm) = get_context_info_array($context->id);
1788 require_login($course, false, $cm);
1790 if ($filearea === 'export') {
1791 require_once($CFG->dirroot . '/question/editlib.php');
1792 $contexts = new question_edit_contexts($context);
1793 // check export capability
1794 $contexts->require_one_edit_tab_cap('export');
1795 $category_id = (int)array_shift($args);
1796 $format = array_shift($args);
1797 $cattofile = array_shift($args);
1798 $contexttofile = array_shift($args);
1799 $filename = array_shift($args);
1801 // load parent class for import/export
1802 require_once($CFG->dirroot . '/question/format.php');
1803 require_once($CFG->dirroot . '/question/editlib.php');
1804 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1806 $classname = 'qformat_' . $format;
1807 if (!class_exists($classname)) {
1808 send_file_not_found();
1811 $qformat = new $classname();
1813 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1814 send_file_not_found();
1817 $qformat->setCategory($category);
1818 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1819 $qformat->setCourse($course);
1821 if ($cattofile == 'withcategories') {
1822 $qformat->setCattofile(true);
1823 } else {
1824 $qformat->setCattofile(false);
1827 if ($contexttofile == 'withcontexts') {
1828 $qformat->setContexttofile(true);
1829 } else {
1830 $qformat->setContexttofile(false);
1833 if (!$qformat->exportpreprocess()) {
1834 send_file_not_found();
1835 print_error('exporterror', 'question', $thispageurl->out());
1838 // export data to moodle file pool
1839 if (!$content = $qformat->exportprocess(true)) {
1840 send_file_not_found();
1843 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1846 $qubaid = (int)array_shift($args);
1847 $slot = (int)array_shift($args);
1849 $module = $DB->get_field('question_usages', 'component',
1850 array('id' => $qubaid));
1852 if ($module === 'core_question_preview') {
1853 require_once($CFG->dirroot . '/question/previewlib.php');
1854 return question_preview_question_pluginfile($course, $context,
1855 $component, $filearea, $qubaid, $slot, $args, $forcedownload);
1857 } else {
1858 $dir = get_component_directory($module);
1859 if (!file_exists("$dir/lib.php")) {
1860 send_file_not_found();
1862 include_once("$dir/lib.php");
1864 $filefunction = $module . '_question_pluginfile';
1865 if (!function_exists($filefunction)) {
1866 send_file_not_found();
1869 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1870 $args, $forcedownload);
1872 send_file_not_found();
1877 * Serve questiontext files in the question text when they are displayed in this report.
1878 * @param context $context the context
1879 * @param int $questionid the question id
1880 * @param array $args remaining file args
1881 * @param bool $forcedownload
1883 function core_question_questiontext_preview_pluginfile($context, $questionid, $args, $forcedownload) {
1884 global $DB;
1886 // Verify that contextid matches the question.
1887 $question = $DB->get_record_sql('
1888 SELECT q.*, qc.contextid
1889 FROM {question} q
1890 JOIN {question_categories} qc ON qc.id = q.category
1891 WHERE q.id = :id AND qc.contextid = :contextid',
1892 array('id' => $questionid, 'contextid' => $context->id), MUST_EXIST);
1894 // Check the capability.
1895 list($context, $course, $cm) = get_context_info_array($context->id);
1896 require_login($course, false, $cm);
1898 question_require_capability_on($question, 'use');
1900 question_send_questiontext_file($questionid, $args, $forcedownload);
1904 * Create url for question export
1906 * @param int $contextid, current context
1907 * @param int $categoryid, categoryid
1908 * @param string $format
1909 * @param string $withcategories
1910 * @param string $ithcontexts
1911 * @param moodle_url export file url
1913 function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1914 $withcontexts, $filename) {
1915 global $CFG;
1916 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
1917 return moodle_url::make_file_url($urlbase,
1918 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1919 "/{$withcontexts}/{$filename}", true);
1923 * Return a list of page types
1924 * @param string $pagetype current page type
1925 * @param stdClass $parentcontext Block's parent context
1926 * @param stdClass $currentcontext Current context of block
1928 function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
1929 global $CFG;
1930 $types = array(
1931 'question-*'=>get_string('page-question-x', 'question'),
1932 'question-edit'=>get_string('page-question-edit', 'question'),
1933 'question-category'=>get_string('page-question-category', 'question'),
1934 'question-export'=>get_string('page-question-export', 'question'),
1935 'question-import'=>get_string('page-question-import', 'question')
1937 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1938 require_once($CFG->dirroot . '/course/lib.php');
1939 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1940 } else {
1941 return $types;