Merge branch 'MDL-35055' of git://github.com/timhunt/moodle
[moodle.git] / lib / questionlib.php
CommitLineData
50fcb1d8 1<?php
50fcb1d8 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.
13//
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/>.
16
516cf3eb 17/**
6b11a0e8 18 * Code for handling and processing questions
19 *
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}
24 *
25 * TODO: separate those functions which form part of the API
26 * from the helper functions.
27 *
f29aeb5a
TH
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
6b11a0e8 32 */
720be6f2 33
8b92c1e3 34
9c197f44
TH
35defined('MOODLE_INTERNAL') || die();
36
f29aeb5a 37require_once($CFG->dirroot . '/question/engine/lib.php');
afe24f85 38require_once($CFG->dirroot . '/question/type/questiontypebase.php');
8b92c1e3 39
8b92c1e3 40
b55797b8 41
f29aeb5a 42/// CONSTANTS ///////////////////////////////////
e56a08dc 43
6b11a0e8 44/**
45 * Constant determines the number of answer boxes supplied in the editing
46 * form for multiple choice and similar question types.
47 */
f29aeb5a 48define("QUESTION_NUMANS", 10);
e56a08dc 49
271ffe3f 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.
54 */
55define("QUESTION_NUMANS_START", 3);
56
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'.
61 */
62define("QUESTION_NUMANS_ADD", 3);
63
af52ecee 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.
117bd748 67 *
af52ecee 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.
74 */
75function 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;
81 }
82 // Work out the other index.
83 $otherkey = $key + $direction;
84 if (!isset($neworder[$otherkey])) {
85 return $neworder;
86 }
87 // Do the swap.
88 $swap = $neworder[$otherkey];
89 $neworder[$otherkey] = $neworder[$key];
90 $neworder[$key] = $swap;
91 return $neworder;
92}
93
94/**
95 * Save a new question type order to the config_plugins table.
50fcb1d8 96 * @global object
af52ecee 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.
99 */
100function question_save_qtype_order($neworder, $config = null) {
101 global $DB;
102
103 if (is_null($config)) {
104 $config = get_config('question');
105 }
106
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');
111 }
112 }
113}
114
516cf3eb 115/// FUNCTIONS //////////////////////////////////////////////////////
116
90c3f310 117/**
f67172b6 118 * Returns an array of names of activity modules that use this question
90c3f310 119 *
f29aeb5a 120 * @deprecated since Moodle 2.1. Use {@link questions_in_use} instead.
aac80ff3 121 *
f67172b6 122 * @param object $questionid
123 * @return array of strings
90c3f310 124 */
f67172b6 125function question_list_instances($questionid) {
aac80ff3
TH
126 throw new coding_exception('question_list_instances has been deprectated. ' .
127 'Please use questions_in_use instead.');
f29aeb5a
TH
128}
129
130/**
131 * @param array $questionids of question ids.
132 * @return boolean whether any of these questions are being used by any part of Moodle.
133 */
134function questions_in_use($questionids) {
135 global $CFG;
136
137 if (question_engine::questions_in_use($questionids)) {
138 return true;
139 }
140
141 foreach (get_plugin_list('mod') as $module => $path) {
142 $lib = $path . '/lib.php';
143 if (is_readable($lib)) {
144 include_once($lib);
145
146 $fn = $module . '_questions_in_use';
7453df70 147 if (function_exists($fn)) {
f29aeb5a
TH
148 if ($fn($questionids)) {
149 return true;
150 }
151 } else {
152
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;
160 }
161 }
162 }
7453df70 163 }
90c3f310 164 }
165 }
f29aeb5a
TH
166
167 return false;
90c3f310 168}
516cf3eb 169
e2b347e9 170/**
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.
174 *
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.
178 */
179function question_context_has_any_questions($context) {
eb84a826 180 global $DB;
e2b347e9 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');
187 }
eb84a826 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));
e2b347e9 192}
193
271ffe3f 194/**
e9de4366 195 * Returns list of 'allowed' grades for grade selection
196 * formatted suitably for dropdown box function
af2f98ee
TH
197 *
198 * @deprecated since 2.1. Use {@link question_bank::fraction_options()} or
199 * {@link question_bank::fraction_options_full()} instead.
200 *
e9de4366 201 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
202 */
203function get_grade_options() {
0ff4bd08 204 $grades = new stdClass();
af2f98ee
TH
205 $grades->gradeoptions = question_bank::fraction_options();
206 $grades->gradeoptionsfull = question_bank::fraction_options_full();
e9de4366 207
208 return $grades;
209}
210
8511669c 211/**
aa5f0511
TH
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.
8511669c 215 * @param array $gradeoptionsfull list of valid options
216 * @param int $grade grade to be tested
217 * @param string $matchgrades 'error' or 'nearest'
aa5f0511 218 * @return mixed either 'fixed' value or false if error.
8511669c 219 */
aa5f0511
TH
220function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
221
aac80ff3 222 if ($matchgrades == 'error') {
aa5f0511 223 // (Almost) exact match, or an error.
aac80ff3 224 foreach ($gradeoptionsfull as $value => $option) {
aa5f0511 225 // Slightly fuzzy test, never check floats for equality.
aac80ff3 226 if (abs($grade - $value) < 0.00001) {
aa5f0511 227 return $value; // Be sure the return the proper value.
8511669c 228 }
229 }
aa5f0511 230 // Didn't find a match so that's an error.
8511669c 231 return false;
aa5f0511 232
aac80ff3 233 } else if ($matchgrades == 'nearest') {
aa5f0511
TH
234 // Work out nearest value
235 $best = false;
236 $bestmismatch = 2;
aac80ff3 237 foreach ($gradeoptionsfull as $value => $option) {
aa5f0511
TH
238 $newmismatch = abs($grade - $value);
239 if ($newmismatch < $bestmismatch) {
240 $best = $value;
241 $bestmismatch = $newmismatch;
8511669c 242 }
8511669c 243 }
aa5f0511
TH
244 return $best;
245
aac80ff3 246 } else {
aa5f0511
TH
247 // Unknow option passed.
248 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
249 ' passed to match_grade_options');
271ffe3f 250 }
8511669c 251}
252
f67172b6 253/**
f29aeb5a
TH
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.
f67172b6 258 */
259function question_category_isused($categoryid, $recursive = false) {
aac80ff3
TH
260 throw new coding_exception('question_category_isused has been deprectated. ' .
261 'Please use question_category_in_use instead.');
f29aeb5a
TH
262}
263
264/**
265 * Tests whether any question in a category is used by any part of Moodle.
266 *
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.
270 */
271function question_category_in_use($categoryid, $recursive = false) {
eb84a826 272 global $DB;
f67172b6 273
274 //Look at each question in the category
aac80ff3
TH
275 if ($questions = $DB->get_records_menu('question',
276 array('category' => $categoryid), '', 'id, 1')) {
f29aeb5a
TH
277 if (questions_in_use(array_keys($questions))) {
278 return true;
f67172b6 279 }
280 }
f29aeb5a
TH
281 if (!$recursive) {
282 return false;
283 }
f67172b6 284
285 //Look under child categories recursively
aac80ff3
TH
286 if ($children = $DB->get_records('question_categories',
287 array('parent' => $categoryid), '', 'id, 1')) {
f29aeb5a
TH
288 foreach ($children as $child) {
289 if (question_category_in_use($child->id, $recursive)) {
290 return true;
f67172b6 291 }
292 }
293 }
294
295 return false;
296}
297
516cf3eb 298/**
6b11a0e8 299 * Deletes question and all associated data from the database
300 *
90c3f310 301 * It will not delete a question if it is used by an activity module
6b11a0e8 302 * @param object $question The question being deleted
303 */
f29aeb5a 304function question_delete_question($questionid) {
f9b0500f 305 global $DB;
271ffe3f 306
9203b705
TH
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) {
3c573960 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;
317 }
318
90c3f310 319 // Do not delete a question if it is used by an activity module
f29aeb5a 320 if (questions_in_use(array($questionid))) {
90c3f310 321 return;
322 }
323
f29aeb5a 324 // Check permissions.
3bee1ead 325 question_require_capability_on($question, 'edit');
271ffe3f 326
f29aeb5a
TH
327 $dm = new question_engine_data_mapper();
328 $dm->delete_previews($questionid);
0429cd86 329
f29aeb5a
TH
330 // delete questiontype-specific data
331 question_bank::get_qtype($question->qtype, false)->delete_question(
332 $questionid, $question->contextid);
90c3f310 333
334 // Now recursively delete all child questions
aac80ff3
TH
335 if ($children = $DB->get_records('question',
336 array('parent' => $questionid), '', 'id, qtype')) {
516cf3eb 337 foreach ($children as $child) {
1d723a16 338 if ($child->id != $questionid) {
7ee214ff 339 question_delete_question($child->id);
1d723a16 340 }
516cf3eb 341 }
342 }
271ffe3f 343
90c3f310 344 // Finally delete the question record itself
f29aeb5a 345 $DB->delete_records('question', array('id' => $questionid));
516cf3eb 346}
347
f67172b6 348/**
3bee1ead 349 * All question categories and their questions are deleted for this course.
f67172b6 350 *
16ef46e7 351 * @param stdClass $course an object representing the activity
f67172b6 352 * @param boolean $feedback to specify if the process must output a summary of its work
353 * @return boolean
354 */
355function question_delete_course($course, $feedback=true) {
642816a6 356 global $DB, $OUTPUT;
eb84a826 357
f67172b6 358 //To store feedback to be showed at the end of the process
359 $feedbackdata = array();
360
361 //Cache some strings
f67172b6 362 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
b0c6dc1c 363 $coursecontext = context_course::instance($course->id);
aac80ff3
TH
364 $categoriescourse = $DB->get_records('question_categories',
365 array('contextid' => $coursecontext->id), 'parent', 'id, parent, name, contextid');
f67172b6 366
3bee1ead 367 if ($categoriescourse) {
f67172b6 368
369 //Sort categories following their tree (parent-child) relationships
3bee1ead 370 //this will make the feedback more readable
371 $categoriescourse = sort_categories_by_tree($categoriescourse);
372
373 foreach ($categoriescourse as $category) {
374
375 //Delete it completely (questions and category itself)
376 //deleting questions
aac80ff3
TH
377 if ($questions = $DB->get_records('question',
378 array('category' => $category->id), '', 'id,qtype')) {
3bee1ead 379 foreach ($questions as $question) {
7ee214ff 380 question_delete_question($question->id);
f67172b6 381 }
aac80ff3 382 $DB->delete_records("question", array("category" => $category->id));
3bee1ead 383 }
384 //delete the category
aac80ff3 385 $DB->delete_records('question_categories', array('id' => $category->id));
f67172b6 386
3bee1ead 387 //Fill feedback
388 $feedbackdata[] = array($category->name, $strcatdeleted);
389 }
390 //Inform about changes performed if feedback is enabled
391 if ($feedback) {
642816a6 392 $table = new html_table();
aac80ff3 393 $table->head = array(get_string('category', 'quiz'), get_string('action'));
3bee1ead 394 $table->data = $feedbackdata;
16be8974 395 echo html_writer::table($table);
3bee1ead 396 }
397 }
398 return true;
399}
f67172b6 400
e2b347e9 401/**
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
405 *
406 * @param object $category course category object
aac80ff3
TH
407 * @param object $newcategory empty means everything deleted, otherwise id of
408 * category where content moved
e2b347e9 409 * @param boolean $feedback to specify if the process must output a summary of its work
410 * @return boolean
411 */
412function question_delete_course_category($category, $newcategory, $feedback=true) {
aa9a6867 413 global $DB, $OUTPUT;
534792cd 414
b0c6dc1c 415 $context = context_coursecat::instance($category->id);
e2b347e9 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');
420
421 // Loop over question categories.
aac80ff3
TH
422 if ($categories = $DB->get_records('question_categories',
423 array('contextid'=>$context->id), 'parent', 'id, parent, name')) {
e2b347e9 424 foreach ($categories as $category) {
b9bd6da4 425
e2b347e9 426 // Deal with any questions in the category.
aac80ff3
TH
427 if ($questions = $DB->get_records('question',
428 array('category' => $category->id), '', 'id,qtype')) {
e2b347e9 429
430 // Try to delete each question.
431 foreach ($questions as $question) {
7ee214ff 432 question_delete_question($question->id);
e2b347e9 433 }
434
aac80ff3
TH
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');
e2b347e9 442 if (!empty($questionids)) {
aac80ff3
TH
443 if (!$rescueqcategory = question_save_from_deletion(
444 array_keys($questionids), get_parent_contextid($context),
445 print_context_name($context), $rescueqcategory)) {
e2b347e9 446 return false;
aac80ff3
TH
447 }
448 $feedbackdata[] = array($category->name,
449 get_string('questionsmovedto', 'question', $rescueqcategory->name));
e2b347e9 450 }
451 }
452
453 // Now delete the category.
eb84a826 454 if (!$DB->delete_records('question_categories', array('id'=>$category->id))) {
e2b347e9 455 return false;
456 }
457 $feedbackdata[] = array($category->name, $strcatdeleted);
458
459 } // End loop over categories.
460 }
461
462 // Output feedback if requested.
463 if ($feedback and $feedbackdata) {
642816a6 464 $table = new html_table();
aac80ff3 465 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
e2b347e9 466 $table->data = $feedbackdata;
16be8974 467 echo html_writer::table($table);
e2b347e9 468 }
469
470 } else {
471 // Move question categories ot the new context.
b0c6dc1c 472 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
e2b347e9 473 return false;
474 }
aac80ff3
TH
475 $DB->set_field('question_categories', 'contextid', $newcontext->id,
476 array('contextid'=>$context->id));
e2b347e9 477 if ($feedback) {
0ff4bd08 478 $a = new stdClass();
e2b347e9 479 $a->oldplace = print_context_name($context);
480 $a->newplace = print_context_name($newcontext);
aac80ff3
TH
481 echo $OUTPUT->notification(
482 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
e2b347e9 483 }
484 }
485
486 return true;
487}
488
489/**
490 * Enter description here...
491 *
9d0ac0ff 492 * @param array $questionids of question ids
e2b347e9 493 * @param object $newcontext the context to create the saved category in.
aac80ff3
TH
494 * @param string $oldplace a textual description of the think being deleted,
495 * e.g. from get_context_name
e2b347e9 496 * @param object $newcategory
b9bd6da4 497 * @return mixed false on
e2b347e9 498 */
aac80ff3
TH
499function question_save_from_deletion($questionids, $newcontextid, $oldplace,
500 $newcategory = null) {
eb84a826 501 global $DB;
502
e2b347e9 503 // Make a category in the parent context to move the questions to.
504 if (is_null($newcategory)) {
365a5941 505 $newcategory = new stdClass();
e2b347e9 506 $newcategory->parent = 0;
507 $newcategory->contextid = $newcontextid;
eb84a826 508 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
509 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
e2b347e9 510 $newcategory->sortorder = 999;
511 $newcategory->stamp = make_unique_id_code();
a8f3a651 512 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
e2b347e9 513 }
514
515 // Move any remaining questions to the 'saved' category.
516 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
517 return false;
518 }
519 return $newcategory;
520}
521
3bee1ead 522/**
523 * All question categories and their questions are deleted for this activity.
524 *
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
528 */
529function question_delete_activity($cm, $feedback=true) {
642816a6 530 global $DB, $OUTPUT;
eb84a826 531
3bee1ead 532 //To store feedback to be showed at the end of the process
533 $feedbackdata = array();
f67172b6 534
3bee1ead 535 //Cache some strings
536 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
b0c6dc1c 537 $modcontext = context_module::instance($cm->id);
aac80ff3
TH
538 if ($categoriesmods = $DB->get_records('question_categories',
539 array('contextid' => $modcontext->id), 'parent', 'id, parent, name, contextid')) {
3bee1ead 540 //Sort categories following their tree (parent-child) relationships
541 //this will make the feedback more readable
542 $categoriesmods = sort_categories_by_tree($categoriesmods);
f67172b6 543
3bee1ead 544 foreach ($categoriesmods as $category) {
f67172b6 545
3bee1ead 546 //Delete it completely (questions and category itself)
547 //deleting questions
aac80ff3
TH
548 if ($questions = $DB->get_records('question',
549 array('category' => $category->id), '', 'id,qtype')) {
3bee1ead 550 foreach ($questions as $question) {
7ee214ff 551 question_delete_question($question->id);
3bee1ead 552 }
eb84a826 553 $DB->delete_records("question", array("category"=>$category->id));
f67172b6 554 }
3bee1ead 555 //delete the category
eb84a826 556 $DB->delete_records('question_categories', array('id'=>$category->id));
3bee1ead 557
558 //Fill feedback
559 $feedbackdata[] = array($category->name, $strcatdeleted);
f67172b6 560 }
561 //Inform about changes performed if feedback is enabled
562 if ($feedback) {
642816a6 563 $table = new html_table();
aac80ff3 564 $table->head = array(get_string('category', 'quiz'), get_string('action'));
f67172b6 565 $table->data = $feedbackdata;
16be8974 566 echo html_writer::table($table);
f67172b6 567 }
568 }
569 return true;
570}
7fb1b88d 571
572/**
573 * This function should be considered private to the question bank, it is called from
aac80ff3
TH
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.
7fb1b88d 578 *
9d0ac0ff 579 * @param array $questionids of question ids.
fe6ce234 580 * @param integer $newcategoryid the id of the category to move to.
7fb1b88d 581 */
fe6ce234 582function question_move_questions_to_category($questionids, $newcategoryid) {
d649fb02 583 global $DB;
f685e830 584
5d548d3e
TH
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) {
d649fb02
TH
595 question_bank::get_qtype($question->qtype)->move_files(
596 $question->id, $question->contextid, $newcontextid);
5d548d3e 597 }
fe6ce234
DC
598 }
599
7fb1b88d 600 // Move the questions themselves.
aac80ff3
TH
601 $DB->set_field_select('question', 'category', $newcategoryid,
602 "id $questionidcondition", $params);
7fb1b88d 603
604 // Move any subquestions belonging to them.
aac80ff3
TH
605 $DB->set_field_select('question', 'category', $newcategoryid,
606 "parent $questionidcondition", $params);
7fb1b88d 607
608 // TODO Deal with datasets.
609
f685e830 610 return true;
7fb1b88d 611}
612
5d548d3e
TH
613/**
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.
620 */
621function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
d649fb02 622 global $DB;
5d548d3e
TH
623
624 $questionids = $DB->get_records_menu('question',
625 array('category' => $categoryid), '', 'id,qtype');
626 foreach ($questionids as $questionid => $qtype) {
aac80ff3
TH
627 question_bank::get_qtype($qtype)->move_files(
628 $questionid, $oldcontextid, $newcontextid);
5d548d3e
TH
629 }
630
631 $subcatids = $DB->get_records_menu('question_categories',
632 array('parent' => $categoryid), '', 'id,1');
633 foreach ($subcatids as $subcatid => $notused) {
aac80ff3
TH
634 $DB->set_field('question_categories', 'contextid', $newcontextid,
635 array('id' => $subcatid));
5d548d3e
TH
636 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
637 }
638}
639
f29aeb5a
TH
640/**
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.
c014b989
TH
646 * @param int $variant the variant of the question to preview. If null, one will
647 * be picked randomly.
56a4ae46
TH
648 * @param object $context context to run the preview in (affects things like
649 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
f29aeb5a
TH
650 * @return string the URL.
651 */
612106b3 652function question_preview_url($questionid, $preferredbehaviour = null,
56a4ae46 653 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
612106b3
TH
654
655 $params = array('id' => $questionid);
656
56a4ae46
TH
657 if (is_null($context)) {
658 global $PAGE;
659 $context = $PAGE->context;
660 }
661 if ($context->contextlevel == CONTEXT_MODULE) {
662 $params['cmid'] = $context->instanceid;
663 } else if ($context->contextlevel == CONTEXT_COURSE) {
664 $params['courseid'] = $context->instanceid;
665 }
666
612106b3
TH
667 if (!is_null($preferredbehaviour)) {
668 $params['behaviour'] = $preferredbehaviour;
669 }
670
671 if (!is_null($maxmark)) {
672 $params['maxmark'] = $maxmark;
673 }
674
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;
683 }
684
c014b989
TH
685 if ($variant) {
686 $params['variant'] = $variant;
687 }
612106b3 688
c014b989 689 return new moodle_url('/question/preview.php', $params);
f29aeb5a
TH
690}
691
612106b3
TH
692/**
693 * @return array that can be passed as $params to the {@link popup_action} constructor.
694 */
695function question_preview_popup_params() {
696 return array(
697 'height' => 600,
698 'width' => 800,
699 );
700}
701
5a2a5331 702/**
aac80ff3
TH
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
78e7a3dd 706 * read the code below to see how the SQL is assembled. Throws exceptions on error.
5a2a5331 707 *
50fcb1d8 708 * @global object
709 * @global object
78e7a3dd 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.
5a2a5331 715 *
78e7a3dd 716 * @return array partially complete question objects. You need to call get_question_options
717 * on them before they can be properly used.
5a2a5331 718 */
aac80ff3
TH
719function question_preload_questions($questionids, $extrafields = '', $join = '',
720 $extraparams = array()) {
f29aeb5a 721 global $DB;
4089d9ec 722 if (empty($questionids)) {
723 return array();
724 }
5a2a5331 725 if ($join) {
78e7a3dd 726 $join = ' JOIN '.$join;
5a2a5331 727 }
728 if ($extrafields) {
729 $extrafields = ', ' . $extrafields;
730 }
78e7a3dd 731 list($questionidcondition, $params) = $DB->get_in_or_equal(
732 $questionids, SQL_PARAMS_NAMED, 'qid0000');
56e82d99
TH
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;
5a2a5331 737
738 // Load the questions
78e7a3dd 739 if (!$questions = $DB->get_records_sql($sql, $extraparams + $params)) {
f29aeb5a 740 return array();
5a2a5331 741 }
742
78e7a3dd 743 foreach ($questions as $question) {
744 $question->_partiallyloaded = true;
745 }
746
b55797b8 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.
752
78e7a3dd 753 return $questions;
754}
755
756/**
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.
760 *
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.
766 *
767 * @return array question objects.
768 */
769function question_load_questions($questionids, $extrafields = '', $join = '') {
770 $questions = question_preload_questions($questionids, $extrafields, $join);
771
5a2a5331 772 // Load the question type specific information
773 if (!get_question_options($questions)) {
774 return 'Could not load the question options';
775 }
776
777 return $questions;
778}
779
516cf3eb 780/**
d7444d44 781 * Private function to factor common code out of get_question_options().
271ffe3f 782 *
d7444d44 783 * @param object $question the question to tidy.
c599a682 784 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
d7444d44 785 */
c76145d3 786function _tidy_question($question, $loadtags = false) {
d649fb02 787 global $CFG;
2daffca5 788 if (!question_bank::is_qtype_installed($question->qtype)) {
d649fb02
TH
789 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
790 'qtype_missingtype')) . $question->questiontext;
d7444d44 791 }
d649fb02 792 question_bank::get_qtype($question->qtype)->get_question_options($question);
a8a8ec51
TH
793 if (isset($question->_partiallyloaded)) {
794 unset($question->_partiallyloaded);
78e7a3dd 795 }
c599a682 796 if ($loadtags && !empty($CFG->usetags)) {
797 require_once($CFG->dirroot . '/tag/lib.php');
798 $question->tags = tag_get_tags_array('question', $question->id);
799 }
d7444d44 800}
516cf3eb 801
d7444d44 802/**
803 * Updates the question objects with question type specific
804 * information by calling {@link get_question_options()}
805 *
806 * Can be called either with an array of question objects or with a single
807 * question object.
271ffe3f 808 *
d7444d44 809 * @param mixed $questions Either an array of question objects to be updated
810 * or just a single question object
c599a682 811 * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
d7444d44 812 * @return bool Indicates success or failure.
813 */
c599a682 814function get_question_options(&$questions, $loadtags = false) {
516cf3eb 815 if (is_array($questions)) { // deal with an array of questions
d7444d44 816 foreach ($questions as $i => $notused) {
a8a8ec51 817 _tidy_question($questions[$i], $loadtags);
516cf3eb 818 }
516cf3eb 819 } else { // deal with single question
a8a8ec51 820 _tidy_question($questions, $loadtags);
516cf3eb 821 }
a8a8ec51 822 return true;
516cf3eb 823}
824
825/**
aac80ff3
TH
826 * Print the icon for the question type
827 *
828 * @param object $question The question object for which the icon is required.
829 * Only $question->qtype is used.
830 * @return string the HTML for the img tag.
831 */
f29aeb5a 832function print_question_icon($question) {
5cc021a0
TH
833 global $PAGE;
834 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
81d833ad 835}
836
837/**
f29aeb5a 838 * Creates a stamp that uniquely identifies this version of the question
81d833ad 839 *
f29aeb5a
TH
840 * In future we want this to use a hash of the question data to guarantee that
841 * identical versions have the same version stamp.
842 *
843 * @param object $question
844 * @return string A unique version stamp
81d833ad 845 */
f29aeb5a
TH
846function question_hash($question) {
847 return make_unique_id_code();
81d833ad 848}
849
f29aeb5a 850/// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
516cf3eb 851/**
f29aeb5a 852 * Saves question options
50fcb1d8 853 *
f29aeb5a
TH
854 * Simply calls the question type specific save_question_options() method.
855 */
856function save_question_options($question) {
d649fb02 857 question_bank::get_qtype($question->qtype)->save_question_options($question);
516cf3eb 858}
859
f29aeb5a
TH
860/// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
861
516cf3eb 862/**
f29aeb5a
TH
863 * returns the categories with their names ordered following parent-child relationships
864 * finally it tries to return pending categories (those being orphaned, whose parent is
865 * incorrect) to avoid missing any category from original array.
866 */
867function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
868 global $DB;
5e9170b4 869
f29aeb5a
TH
870 $children = array();
871 $keys = array_keys($categories);
516cf3eb 872
f29aeb5a
TH
873 foreach ($keys as $key) {
874 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
875 $children[$key] = $categories[$key];
876 $categories[$key]->processed = true;
aac80ff3
TH
877 $children = $children + sort_categories_by_tree(
878 $categories, $children[$key]->id, $level+1);
516cf3eb 879 }
880 }
aac80ff3
TH
881 //If level = 1, we have finished, try to look for non processed categories
882 // (bad parent) and sort them too
f29aeb5a
TH
883 if ($level == 1) {
884 foreach ($keys as $key) {
aac80ff3
TH
885 // If not processed and it's a good candidate to start (because its
886 // parent doesn't exist in the course)
887 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
888 array('contextid' => $categories[$key]->contextid,
889 'id' => $categories[$key]->parent))) {
f29aeb5a
TH
890 $children[$key] = $categories[$key];
891 $categories[$key]->processed = true;
aac80ff3
TH
892 $children = $children + sort_categories_by_tree(
893 $categories, $children[$key]->id, $level + 1);
f29aeb5a
TH
894 }
895 }
516cf3eb 896 }
f29aeb5a 897 return $children;
6cb4910c 898}
899
900/**
062a7522 901 * Private method, only for the use of add_indented_names().
271ffe3f 902 *
062a7522 903 * Recursively adds an indentedname field to each category, starting with the category
271ffe3f 904 * with id $id, and dealing with that category and all its children, and
062a7522 905 * return a new array, with those categories in the right order.
906 *
271ffe3f 907 * @param array $categories an array of categories which has had childids
062a7522 908 * fields added by flatten_category_tree(). Passed by reference for
909 * performance only. It is not modfied.
910 * @param int $id the category to start the indenting process from.
911 * @param int $depth the indent depth. Used in recursive calls.
912 * @return array a new array of categories, in the right order for the tree.
6cb4910c 913 */
3bee1ead 914function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
271ffe3f 915
062a7522 916 // Indent the name of this category.
917 $newcategories = array();
918 $newcategories[$id] = $categories[$id];
aac80ff3
TH
919 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
920 $categories[$id]->name;
271ffe3f 921
062a7522 922 // Recursively indent the children.
923 foreach ($categories[$id]->childids as $childid) {
aac80ff3
TH
924 if ($childid != $nochildrenof) {
925 $newcategories = $newcategories + flatten_category_tree(
926 $categories, $childid, $depth + 1, $nochildrenof);
3bee1ead 927 }
6cb4910c 928 }
271ffe3f 929
062a7522 930 // Remove the childids array that were temporarily added.
931 unset($newcategories[$id]->childids);
271ffe3f 932
062a7522 933 return $newcategories;
6cb4910c 934}
935
936/**
062a7522 937 * Format categories into an indented list reflecting the tree structure.
271ffe3f 938 *
062a7522 939 * @param array $categories An array of category objects, for example from the.
940 * @return array The formatted list of categories.
6cb4910c 941 */
3bee1ead 942function add_indented_names($categories, $nochildrenof = -1) {
6cb4910c 943
aac80ff3
TH
944 // Add an array to each category to hold the child category ids. This array
945 // will be removed again by flatten_category_tree(). It should not be used
946 // outside these two functions.
062a7522 947 foreach (array_keys($categories) as $id) {
948 $categories[$id]->childids = array();
6cb4910c 949 }
950
062a7522 951 // Build the tree structure, and record which categories are top-level.
271ffe3f 952 // We have to be careful, because the categories array may include published
062a7522 953 // categories from other courses, but not their parents.
954 $toplevelcategoryids = array();
955 foreach (array_keys($categories) as $id) {
aac80ff3
TH
956 if (!empty($categories[$id]->parent) &&
957 array_key_exists($categories[$id]->parent, $categories)) {
062a7522 958 $categories[$categories[$id]->parent]->childids[] = $id;
959 } else {
960 $toplevelcategoryids[] = $id;
6cb4910c 961 }
962 }
963
062a7522 964 // Flatten the tree to and add the indents.
965 $newcategories = array();
966 foreach ($toplevelcategoryids as $id) {
aac80ff3
TH
967 $newcategories = $newcategories + flatten_category_tree(
968 $categories, $id, 0, $nochildrenof);
6cb4910c 969 }
970
062a7522 971 return $newcategories;
6cb4910c 972}
2dd6d66b 973
516cf3eb 974/**
062a7522 975 * Output a select menu of question categories.
271ffe3f 976 *
062a7522 977 * Categories from this course and (optionally) published categories from other courses
271ffe3f 978 * are included. Optionally, only categories the current user may edit can be included.
062a7522 979 *
980 * @param integer $courseid the id of the course to get the categories for.
981 * @param integer $published if true, include publised categories from other courses.
982 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
aac80ff3
TH
983 * @param integer $selected optionally, the id of a category to be selected by
984 * default in the dropdown.
062a7522 985 */
aac80ff3
TH
986function question_category_select_menu($contexts, $top = false, $currentcat = 0,
987 $selected = "", $nochildrenof = -1) {
641454c6 988 global $OUTPUT;
aac80ff3
TH
989 $categoriesarray = question_category_options($contexts, $top, $currentcat,
990 false, $nochildrenof);
3ed998f3 991 if ($selected) {
6770330d 992 $choose = '';
3ed998f3 993 } else {
6770330d 994 $choose = 'choosedots';
516cf3eb 995 }
6770330d 996 $options = array();
aac80ff3
TH
997 foreach ($categoriesarray as $group => $opts) {
998 $options[] = array($group => $opts);
6770330d 999 }
ecc5cc31 1000 echo html_writer::label($selected, 'menucategory', false, array('class' => 'accesshide'));
6770330d 1001 echo html_writer::select($options, 'category', $selected, $choose);
516cf3eb 1002}
1003
cca6e300 1004/**
1005 * @param integer $contextid a context id.
1006 * @return object the default question category for that context, or false if none.
1007 */
1008function question_get_default_category($contextid) {
1009 global $DB;
aac80ff3
TH
1010 $category = $DB->get_records('question_categories',
1011 array('contextid' => $contextid), 'id', '*', 0, 1);
cca6e300 1012 if (!empty($category)) {
1013 return reset($category);
1014 } else {
1015 return false;
1016 }
1017}
1018
8f0f605d 1019/**
aac80ff3
TH
1020 * Gets the default category in the most specific context.
1021 * If no categories exist yet then default ones are created in all contexts.
1022 *
1023 * @param array $contexts The context objects for this context and all parent contexts.
1024 * @return object The default category - the category in the course context
1025 */
8f0f605d 1026function question_make_default_categories($contexts) {
eb84a826 1027 global $DB;
353b2d70 1028 static $preferredlevels = array(
1029 CONTEXT_COURSE => 4,
1030 CONTEXT_MODULE => 3,
1031 CONTEXT_COURSECAT => 2,
1032 CONTEXT_SYSTEM => 1,
1033 );
eb84a826 1034
8f0f605d 1035 $toreturn = null;
353b2d70 1036 $preferredness = 0;
8f0f605d 1037 // If it already exists, just return it.
1038 foreach ($contexts as $key => $context) {
aac80ff3
TH
1039 if (!$exists = $DB->record_exists("question_categories",
1040 array('contextid' => $context->id))) {
eb84a826 1041 // Otherwise, we need to make one
0ff4bd08 1042 $category = new stdClass();
eb84a826 1043 $contextname = print_context_name($context, false, true);
1044 $category->name = get_string('defaultfor', 'question', $contextname);
1045 $category->info = get_string('defaultinfofor', 'question', $contextname);
1046 $category->contextid = $context->id;
1047 $category->parent = 0;
aac80ff3
TH
1048 // By default, all categories get this number, and are sorted alphabetically.
1049 $category->sortorder = 999;
eb84a826 1050 $category->stamp = make_unique_id_code();
bf8e93d7 1051 $category->id = $DB->insert_record('question_categories', $category);
b9bd6da4 1052 } else {
cca6e300 1053 $category = question_get_default_category($context->id);
8f0f605d 1054 }
76cf77e4
TH
1055 $thispreferredness = $preferredlevels[$context->contextlevel];
1056 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1057 $thispreferredness += 10;
1058 }
1059 if ($thispreferredness > $preferredness) {
353b2d70 1060 $toreturn = $category;
76cf77e4 1061 $preferredness = $thispreferredness;
8f0f605d 1062 }
1063 }
1064
353b2d70 1065 if (!is_null($toreturn)) {
1066 $toreturn = clone($toreturn);
1067 }
8f0f605d 1068 return $toreturn;
1069}
1070
375ed78a 1071/**
3bee1ead 1072 * Get all the category objects, including a count of the number of questions in that category,
1073 * for all the categories in the lists $contexts.
375ed78a 1074 *
3bee1ead 1075 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1076 * @param string $sortorder used as the ORDER BY clause in the select statement.
1077 * @return array of category objects.
375ed78a 1078 */
3bee1ead 1079function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
eb84a826 1080 global $DB;
1081 return $DB->get_records_sql("
630a3dc3 1082 SELECT c.*, (SELECT count(1) FROM {question} q
eb84a826 1083 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1084 FROM {question_categories} c
1085 WHERE c.contextid IN ($contexts)
1086 ORDER BY $sortorder");
3bee1ead 1087}
3a3c454e 1088
3bee1ead 1089/**
1090 * Output an array of question categories.
1091 */
aac80ff3
TH
1092function question_category_options($contexts, $top = false, $currentcat = 0,
1093 $popupform = false, $nochildrenof = -1) {
3bee1ead 1094 global $CFG;
1095 $pcontexts = array();
aac80ff3 1096 foreach ($contexts as $context) {
3bee1ead 1097 $pcontexts[] = $context->id;
61d9b9fc 1098 }
3bee1ead 1099 $contextslist = join($pcontexts, ', ');
1100
1101 $categories = get_categories_for_contexts($contextslist);
375ed78a 1102
3bee1ead 1103 $categories = question_add_context_in_key($categories);
1104
aac80ff3 1105 if ($top) {
3bee1ead 1106 $categories = question_add_tops($categories, $pcontexts);
1107 }
1108 $categories = add_indented_names($categories, $nochildrenof);
3ed998f3 1109
aac80ff3 1110 // sort cats out into different contexts
375ed78a 1111 $categoriesarray = array();
aac80ff3
TH
1112 foreach ($pcontexts as $pcontext) {
1113 $contextstring = print_context_name(
1114 get_context_instance_by_id($pcontext), true, true);
3bee1ead 1115 foreach ($categories as $category) {
aac80ff3 1116 if ($category->contextid == $pcontext) {
3bee1ead 1117 $cid = $category->id;
aac80ff3
TH
1118 if ($currentcat != $cid || $currentcat == 0) {
1119 $countstring = !empty($category->questioncount) ?
1120 " ($category->questioncount)" : '';
3bee1ead 1121 $categoriesarray[$contextstring][$cid] = $category->indentedname.$countstring;
1122 }
1123 }
375ed78a 1124 }
1125 }
aac80ff3 1126 if ($popupform) {
3bee1ead 1127 $popupcats = array();
aac80ff3 1128 foreach ($categoriesarray as $contextstring => $optgroup) {
94fa6be4 1129 $group = array();
aac80ff3 1130 foreach ($optgroup as $key => $value) {
78bfb562
PS
1131 $key = str_replace($CFG->wwwroot, '', $key);
1132 $group[$key] = $value;
94fa6be4 1133 }
aac80ff3 1134 $popupcats[] = array($contextstring => $group);
3bee1ead 1135 }
1136 return $popupcats;
1137 } else {
1138 return $categoriesarray;
1139 }
375ed78a 1140}
1141
aac80ff3 1142function question_add_context_in_key($categories) {
3bee1ead 1143 $newcatarray = array();
1144 foreach ($categories as $id => $category) {
1145 $category->parent = "$category->parent,$category->contextid";
1146 $category->id = "$category->id,$category->contextid";
1147 $newcatarray["$id,$category->contextid"] = $category;
516cf3eb 1148 }
3bee1ead 1149 return $newcatarray;
1150}
f29aeb5a 1151
aac80ff3 1152function question_add_tops($categories, $pcontexts) {
3bee1ead 1153 $topcats = array();
aac80ff3 1154 foreach ($pcontexts as $context) {
365a5941 1155 $newcat = new stdClass();
3bee1ead 1156 $newcat->id = "0,$context";
1157 $newcat->name = get_string('top');
1158 $newcat->parent = -1;
1159 $newcat->contextid = $context;
1160 $topcats["0,$context"] = $newcat;
1161 }
1162 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1163 return array_merge($topcats, $categories);
516cf3eb 1164}
1165
516cf3eb 1166/**
2daffca5 1167 * @return array of question category ids of the category and all subcategories.
b20ea669 1168 */
dc1f00de 1169function question_categorylist($categoryid) {
eb84a826 1170 global $DB;
1171
aac80ff3
TH
1172 $subcategories = $DB->get_records('question_categories',
1173 array('parent' => $categoryid), 'sortorder ASC', 'id, 1');
2daffca5
TH
1174
1175 $categorylist = array($categoryid);
1176 foreach ($subcategories as $subcategory) {
1177 $categorylist = array_merge($categorylist, question_categorylist($subcategory->id));
516cf3eb 1178 }
2daffca5 1179
516cf3eb 1180 return $categorylist;
1181}
1182
947217d7 1183//===========================
1184// Import/Export Functions
1185//===========================
1186
ff4b6492 1187/**
1188 * Get list of available import or export formats
1189 * @param string $type 'import' if import list, otherwise export list assumed
271ffe3f 1190 * @return array sorted list of import/export formats available
50fcb1d8 1191 */
f29aeb5a 1192function get_import_export_formats($type) {
ff4b6492 1193 global $CFG;
44a7f384 1194 require_once($CFG->dirroot . '/question/format.php');
f7c1dfaf 1195
44a7f384 1196 $formatclasses = get_plugin_list_with_class('qformat', '', 'format.php');
ff4b6492 1197
f7c1dfaf 1198 $fileformatname = array();
44a7f384 1199 foreach ($formatclasses as $component => $formatclass) {
f29aeb5a 1200
44a7f384 1201 $format = new $formatclass();
f29aeb5a 1202 if ($type == 'import') {
44a7f384 1203 $provided = $format->provide_import();
f29aeb5a 1204 } else {
44a7f384 1205 $provided = $format->provide_export();
ff4b6492 1206 }
f29aeb5a 1207
ff4b6492 1208 if ($provided) {
44a7f384 1209 list($notused, $fileformat) = explode('_', $component, 2);
64679179 1210 $fileformatnames[$fileformat] = get_string('pluginname', $component);
ff4b6492 1211 }
1212 }
ff4b6492 1213
d609d962 1214 collatorlib::asort($fileformatnames);
ff4b6492 1215 return $fileformatnames;
1216}
feb60a07 1217
1218
1219/**
aac80ff3
TH
1220 * Create a reasonable default file name for exporting questions from a particular
1221 * category.
1222 * @param object $course the course the questions are in.
1223 * @param object $category the question category.
1224 * @return string the filename.
1225 */
b80d424c
TH
1226function question_default_export_filename($course, $category) {
1227 // We build a string that is an appropriate name (questions) from the lang pack,
0ff4bd08 1228 // then the corse shortname, then the question category name, then a timestamp.
b80d424c
TH
1229
1230 $base = clean_filename(get_string('exportfilename', 'question'));
1231
1232 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1233 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1234
1235 $shortname = clean_filename($course->shortname);
1236 if ($shortname == '' || $shortname == '_' ) {
1237 $shortname = $course->id;
1238 }
1239
1240 $categoryname = clean_filename(format_string($category->name));
1241
1242 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
feb60a07 1243
1244 return $export_name;
1245}
50fcb1d8 1246
1247/**
f29aeb5a
TH
1248 * Converts contextlevels to strings and back to help with reading/writing contexts
1249 * to/from import/export files.
1250 *
50fcb1d8 1251 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1253 */
3bee1ead 1254class context_to_string_translator{
1255 /**
1256 * @var array used to translate between contextids and strings for this context.
1257 */
f29aeb5a 1258 protected $contexttostringarray = array();
3bee1ead 1259
f29aeb5a 1260 public function __construct($contexts) {
3bee1ead 1261 $this->generate_context_to_string_array($contexts);
1262 }
1263
f29aeb5a 1264 public function context_to_string($contextid) {
3bee1ead 1265 return $this->contexttostringarray[$contextid];
1266 }
1267
f29aeb5a 1268 public function string_to_context($contextname) {
3bee1ead 1269 $contextid = array_search($contextname, $this->contexttostringarray);
1270 return $contextid;
1271 }
1272
f29aeb5a 1273 protected function generate_context_to_string_array($contexts) {
aac80ff3 1274 if (!$this->contexttostringarray) {
3bee1ead 1275 $catno = 1;
aac80ff3
TH
1276 foreach ($contexts as $context) {
1277 switch ($context->contextlevel) {
3bee1ead 1278 case CONTEXT_MODULE :
1279 $contextstring = 'module';
1280 break;
1281 case CONTEXT_COURSE :
1282 $contextstring = 'course';
1283 break;
1284 case CONTEXT_COURSECAT :
1285 $contextstring = "cat$catno";
1286 $catno++;
1287 break;
1288 case CONTEXT_SYSTEM :
1289 $contextstring = 'system';
1290 break;
1291 }
1292 $this->contexttostringarray[$context->id] = $contextstring;
1293 }
1294 }
1295 }
1296
1297}
feb60a07 1298
3bee1ead 1299/**
1300 * Check capability on category
50fcb1d8 1301 *
3bee1ead 1302 * @param mixed $question object or id
1303 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1304 * @param integer $cachecat useful to cache all question records in a category
1305 * @return boolean this user has the capability $cap for this question $question?
1306 */
aac80ff3 1307function question_has_capability_on($question, $cap, $cachecat = -1) {
eb84a826 1308 global $USER, $DB;
1309
3bee1ead 1310 // these are capabilities on existing questions capabilties are
1311 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1312 $question_questioncaps = array('edit', 'view', 'use', 'move');
3bee1ead 1313 static $questions = array();
1314 static $categories = array();
1315 static $cachedcat = array();
9203b705 1316 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
fe0fbfae 1317 $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
3bee1ead 1318 $cachedcat[] = $cachecat;
1319 }
aac80ff3
TH
1320 if (!is_object($question)) {
1321 if (!isset($questions[$question])) {
1322 if (!$questions[$question] = $DB->get_record('question',
1323 array('id' => $question), 'id,category,createdby')) {
0f6475b3 1324 print_error('questiondoesnotexist', 'question');
3bee1ead 1325 }
1326 }
1327 $question = $questions[$question];
1328 }
2a73f863
TH
1329 if (empty($question->category)) {
1330 // This can happen when we have created a fake 'missingtype' question to
1331 // take the place of a deleted question.
1332 return false;
1333 }
aac80ff3
TH
1334 if (!isset($categories[$question->category])) {
1335 if (!$categories[$question->category] = $DB->get_record('question_categories',
1336 array('id'=>$question->category))) {
3bee1ead 1337 print_error('invalidcategory', 'quiz');
1338 }
1339 }
1340 $category = $categories[$question->category];
9203b705 1341 $context = get_context_instance_by_id($category->contextid);
3bee1ead 1342
aac80ff3
TH
1343 if (array_search($cap, $question_questioncaps)!== false) {
1344 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1345 if ($question->createdby == $USER->id) {
1346 return has_capability('moodle/question:' . $cap . 'mine', $context);
3bee1ead 1347 } else {
1348 return false;
1349 }
1350 } else {
1351 return true;
1352 }
1353 } else {
aac80ff3 1354 return has_capability('moodle/question:' . $cap, $context);
3bee1ead 1355 }
1356
1357}
1358
1359/**
1360 * Require capability on question.
1361 */
aac80ff3
TH
1362function question_require_capability_on($question, $cap) {
1363 if (!question_has_capability_on($question, $cap)) {
3bee1ead 1364 print_error('nopermissions', '', '', $cap);
1365 }
1366 return true;
1367}
1368
4f5ffac0 1369/**
43ec99aa 1370 * Get the real state - the correct question id and answer - for a random
1371 * question.
4f5ffac0 1372 * @param object $state with property answer.
1373 * @return mixed return integer real question id or false if there was an
1374 * error..
1375 */
5d548d3e 1376function question_get_real_state($state) {
aa9a6867 1377 global $OUTPUT;
43ec99aa 1378 $realstate = clone($state);
4f5ffac0 1379 $matches = array();
aac80ff3 1380 if (!preg_match('|^random([0-9]+)-(.*)|', $state->answer, $matches)) {
aa9a6867 1381 echo $OUTPUT->notification(get_string('errorrandom', 'quiz_statistics'));
4f5ffac0 1382 return false;
1383 } else {
43ec99aa 1384 $realstate->question = $matches[1];
1385 $realstate->answer = $matches[2];
1386 return $realstate;
4f5ffac0 1387 }
1388}
43ec99aa 1389
62e76c67 1390/**
f29aeb5a
TH
1391 * @param object $context a context
1392 * @return string A URL for editing questions in this context.
f62040ed 1393 */
f29aeb5a
TH
1394function question_edit_url($context) {
1395 global $CFG, $SITE;
1396 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1397 return false;
f62040ed 1398 }
f29aeb5a
TH
1399 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1400 $defaultcategory = question_get_default_category($context->id);
1401 if ($defaultcategory) {
1402 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
f62040ed 1403 }
f29aeb5a
TH
1404 switch ($context->contextlevel) {
1405 case CONTEXT_SYSTEM:
1406 return $baseurl . 'courseid=' . $SITE->id;
1407 case CONTEXT_COURSECAT:
1408 // This is nasty, becuase we can only edit questions in a course
1409 // context at the moment, so for now we just return false.
1410 return false;
1411 case CONTEXT_COURSE:
1412 return $baseurl . 'courseid=' . $context->instanceid;
1413 case CONTEXT_MODULE:
1414 return $baseurl . 'cmid=' . $context->instanceid;
62e76c67 1415 }
f29aeb5a 1416
62e76c67 1417}
56ed242b
SH
1418
1419/**
792881f0 1420 * Adds question bank setting links to the given navigation node if caps are met.
56ed242b
SH
1421 *
1422 * @param navigation_node $navigationnode The navigation node to add the question branch to
0ff4bd08 1423 * @param object $context
56ed242b
SH
1424 * @return navigation_node Returns the question branch that was added
1425 */
1426function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1427 global $PAGE;
1428
1429 if ($context->contextlevel == CONTEXT_COURSE) {
1430 $params = array('courseid'=>$context->instanceid);
1431 } else if ($context->contextlevel == CONTEXT_MODULE) {
1432 $params = array('cmid'=>$context->instanceid);
1433 } else {
1434 return;
1435 }
1436
8356e6cf
TH
1437 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1438 $params['cat'] = $cat;
1439 }
1440
aac80ff3
TH
1441 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1442 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
56ed242b
SH
1443
1444 $contexts = new question_edit_contexts($context);
1445 if ($contexts->have_one_edit_tab_cap('questions')) {
aac80ff3
TH
1446 $questionnode->add(get_string('questions', 'quiz'), new moodle_url(
1447 '/question/edit.php', $params), navigation_node::TYPE_SETTING);
56ed242b
SH
1448 }
1449 if ($contexts->have_one_edit_tab_cap('categories')) {
aac80ff3
TH
1450 $questionnode->add(get_string('categories', 'quiz'), new moodle_url(
1451 '/question/category.php', $params), navigation_node::TYPE_SETTING);
56ed242b
SH
1452 }
1453 if ($contexts->have_one_edit_tab_cap('import')) {
aac80ff3
TH
1454 $questionnode->add(get_string('import', 'quiz'), new moodle_url(
1455 '/question/import.php', $params), navigation_node::TYPE_SETTING);
56ed242b
SH
1456 }
1457 if ($contexts->have_one_edit_tab_cap('export')) {
aac80ff3
TH
1458 $questionnode->add(get_string('export', 'quiz'), new moodle_url(
1459 '/question/export.php', $params), navigation_node::TYPE_SETTING);
56ed242b
SH
1460 }
1461
1462 return $questionnode;
1463}
1464
f29aeb5a
TH
1465/**
1466 * @return array all the capabilities that relate to accessing particular questions.
1467 */
1468function question_get_question_capabilities() {
1469 return array(
1470 'moodle/question:add',
1471 'moodle/question:editmine',
1472 'moodle/question:editall',
1473 'moodle/question:viewmine',
1474 'moodle/question:viewall',
1475 'moodle/question:usemine',
1476 'moodle/question:useall',
1477 'moodle/question:movemine',
1478 'moodle/question:moveall',
1479 );
1480}
1481
1482/**
1483 * @return array all the question bank capabilities.
1484 */
1485function question_get_all_capabilities() {
1486 $caps = question_get_question_capabilities();
1487 $caps[] = 'moodle/question:managecategory';
1488 $caps[] = 'moodle/question:flag';
1489 return $caps;
1490}
1491
6f4c71f5
TH
1492
1493/**
1494 * Tracks all the contexts related to the one where we are currently editing
1495 * questions, and provides helper methods to check permissions.
1496 *
1497 * @copyright 2007 Jamie Pratt me@jamiep.org
1498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1499 */
56ed242b
SH
1500class question_edit_contexts {
1501
aac80ff3 1502 public static $caps = array(
56ed242b
SH
1503 'editq' => array('moodle/question:add',
1504 'moodle/question:editmine',
1505 'moodle/question:editall',
1506 'moodle/question:viewmine',
1507 'moodle/question:viewall',
1508 'moodle/question:usemine',
1509 'moodle/question:useall',
1510 'moodle/question:movemine',
1511 'moodle/question:moveall'),
1512 'questions'=>array('moodle/question:add',
1513 'moodle/question:editmine',
1514 'moodle/question:editall',
1515 'moodle/question:viewmine',
1516 'moodle/question:viewall',
1517 'moodle/question:movemine',
1518 'moodle/question:moveall'),
1519 'categories'=>array('moodle/question:managecategory'),
1520 'import'=>array('moodle/question:add'),
1521 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1522
1523 protected $allcontexts;
1524
1525 /**
6f4c71f5
TH
1526 * Constructor
1527 * @param context the current context.
56ed242b 1528 */
6f4c71f5
TH
1529 public function __construct(context $thiscontext) {
1530 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
56ed242b 1531 }
6f4c71f5 1532
56ed242b
SH
1533 /**
1534 * @return array all parent contexts
1535 */
f29aeb5a 1536 public function all() {
56ed242b
SH
1537 return $this->allcontexts;
1538 }
6f4c71f5 1539
56ed242b
SH
1540 /**
1541 * @return object lowest context which must be either the module or course context
1542 */
f29aeb5a 1543 public function lowest() {
56ed242b
SH
1544 return $this->allcontexts[0];
1545 }
6f4c71f5 1546
56ed242b
SH
1547 /**
1548 * @param string $cap capability
1549 * @return array parent contexts having capability, zero based index
1550 */
f29aeb5a 1551 public function having_cap($cap) {
56ed242b 1552 $contextswithcap = array();
aac80ff3
TH
1553 foreach ($this->allcontexts as $context) {
1554 if (has_capability($cap, $context)) {
56ed242b
SH
1555 $contextswithcap[] = $context;
1556 }
1557 }
1558 return $contextswithcap;
1559 }
6f4c71f5 1560
56ed242b
SH
1561 /**
1562 * @param array $caps capabilities
1563 * @return array parent contexts having at least one of $caps, zero based index
1564 */
f29aeb5a 1565 public function having_one_cap($caps) {
56ed242b 1566 $contextswithacap = array();
aac80ff3
TH
1567 foreach ($this->allcontexts as $context) {
1568 foreach ($caps as $cap) {
1569 if (has_capability($cap, $context)) {
56ed242b
SH
1570 $contextswithacap[] = $context;
1571 break; //done with caps loop
1572 }
1573 }
1574 }
1575 return $contextswithacap;
1576 }
6f4c71f5 1577
56ed242b
SH
1578 /**
1579 * @param string $tabname edit tab name
1580 * @return array parent contexts having at least one of $caps, zero based index
1581 */
f29aeb5a 1582 public function having_one_edit_tab_cap($tabname) {
aac80ff3 1583 return $this->having_one_cap(self::$caps[$tabname]);
56ed242b 1584 }
6f4c71f5 1585
76cf77e4
TH
1586 /**
1587 * @return those contexts where a user can add a question and then use it.
1588 */
1589 public function having_add_and_use() {
1590 $contextswithcap = array();
1591 foreach ($this->allcontexts as $context) {
1592 if (!has_capability('moodle/question:add', $context)) {
1593 continue;
1594 }
1595 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1596 continue;
1597 }
1598 $contextswithcap[] = $context;
1599 }
1600 return $contextswithcap;
1601 }
1602
56ed242b
SH
1603 /**
1604 * Has at least one parent context got the cap $cap?
1605 *
1606 * @param string $cap capability
1607 * @return boolean
1608 */
f29aeb5a 1609 public function have_cap($cap) {
56ed242b
SH
1610 return (count($this->having_cap($cap)));
1611 }
1612
1613 /**
1614 * Has at least one parent context got one of the caps $caps?
1615 *
1616 * @param array $caps capability
1617 * @return boolean
1618 */
f29aeb5a 1619 public function have_one_cap($caps) {
56ed242b
SH
1620 foreach ($caps as $cap) {
1621 if ($this->have_cap($cap)) {
1622 return true;
1623 }
1624 }
1625 return false;
1626 }
f29aeb5a 1627
56ed242b
SH
1628 /**
1629 * Has at least one parent context got one of the caps for actions on $tabname
1630 *
1631 * @param string $tabname edit tab name
1632 * @return boolean
1633 */
aac80ff3
TH
1634 public function have_one_edit_tab_cap($tabname) {
1635 return $this->have_one_cap(self::$caps[$tabname]);
56ed242b 1636 }
f29aeb5a 1637
56ed242b
SH
1638 /**
1639 * Throw error if at least one parent context hasn't got the cap $cap
1640 *
1641 * @param string $cap capability
1642 */
aac80ff3
TH
1643 public function require_cap($cap) {
1644 if (!$this->have_cap($cap)) {
56ed242b
SH
1645 print_error('nopermissions', '', '', $cap);
1646 }
1647 }
f29aeb5a 1648
56ed242b
SH
1649 /**
1650 * Throw error if at least one parent context hasn't got one of the caps $caps
1651 *
1652 * @param array $cap capabilities
1653 */
aac80ff3 1654 public function require_one_cap($caps) {
56ed242b
SH
1655 if (!$this->have_one_cap($caps)) {
1656 $capsstring = join($caps, ', ');
1657 print_error('nopermissions', '', '', $capsstring);
1658 }
1659 }
1660
1661 /**
1662 * Throw error if at least one parent context hasn't got one of the caps $caps
1663 *
1664 * @param string $tabname edit tab name
1665 */
aac80ff3 1666 public function require_one_edit_tab_cap($tabname) {
56ed242b
SH
1667 if (!$this->have_one_edit_tab_cap($tabname)) {
1668 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1669 }
1670 }
fe6ce234
DC
1671}
1672
6f4c71f5 1673
fe6ce234 1674/**
fdb5bc03 1675 * Helps call file_rewrite_pluginfile_urls with the right parameters.
fe6ce234 1676 *
d2b7803e
DC
1677 * @package core_question
1678 * @category files
fe6ce234
DC
1679 * @param string $text text being processed
1680 * @param string $file the php script used to serve files
d2b7803e 1681 * @param int $contextid context ID
fe6ce234
DC
1682 * @param string $component component
1683 * @param string $filearea filearea
1684 * @param array $ids other IDs will be used to check file permission
d2b7803e
DC
1685 * @param int $itemid item ID
1686 * @param array $options options
fe6ce234
DC
1687 * @return string
1688 */
aac80ff3
TH
1689function question_rewrite_question_urls($text, $file, $contextid, $component,
1690 $filearea, array $ids, $itemid, array $options=null) {
fe6ce234 1691
fdb5bc03
TH
1692 $idsstr = '';
1693 if (!empty($ids)) {
1694 $idsstr .= implode('/', $ids);
fe6ce234 1695 }
fdb5bc03
TH
1696 if ($itemid !== null) {
1697 $idsstr .= '/' . $itemid;
fe6ce234 1698 }
fdb5bc03
TH
1699 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1700 $filearea, $idsstr, $options);
1701}
fe6ce234 1702
fdb5bc03
TH
1703/**
1704 * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
1705 * text outside and attempt (for example, in the question bank listing or in the
1706 * quiz statistics report).
1707 *
1708 * @param string $questiontext the question text.
1709 * @param int $contextid the context the text is being displayed in.
1710 * @param string $component component
1711 * @param array $ids other IDs will be used to check file permission
1712 * @param array $options
1713 * @return string $questiontext with URLs rewritten.
1714 */
1715function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
1716 $component, $questionid, $options=null) {
fe6ce234 1717
fdb5bc03
TH
1718 return file_rewrite_pluginfile_urls($questiontext, 'pluginfile.php', $contextid,
1719 'question', 'questiontext_preview', "$component/$questionid", $options);
1720}
fe6ce234 1721
fdb5bc03
TH
1722/**
1723 * Send a file from the question text of a question.
1724 * @param int $questionid the question id
1725 * @param array $args the remaining file arguments (file path).
1726 * @param bool $forcedownload whether the user must be forced to download the file.
7a00d438 1727 * @param array $options additional options affecting the file serving
fdb5bc03 1728 */
7a00d438 1729function question_send_questiontext_file($questionid, $args, $forcedownload, $options) {
fdb5bc03 1730 global $DB;
fe6ce234 1731
fdb5bc03
TH
1732 $question = $DB->get_record_sql('
1733 SELECT q.id, qc.contextid
1734 FROM {question} q
1735 JOIN {question_categories} qc ON qc.id = q.category
1736 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
1737
1738 $fs = get_file_storage();
1739 $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
1740 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1741 send_file_not_found();
fe6ce234
DC
1742 }
1743
7a00d438 1744 send_stored_file($file, 0, 0, $forcedownload, $options);
fe6ce234
DC
1745}
1746
1747/**
1748 * Called by pluginfile.php to serve files related to the 'question' core
1749 * component and for files belonging to qtypes.
1750 *
1751 * For files that relate to questions in a question_attempt, then we delegate to
1752 * a function in the component that owns the attempt (for example in the quiz,
1753 * or in core question preview) to get necessary inforation.
1754 *
1755 * (Note that, at the moment, all question file areas relate to questions in
1756 * attempts, so the If at the start of the last paragraph is always true.)
1757 *
1758 * Does not return, either calls send_file_not_found(); or serves the file.
1759 *
d2b7803e
DC
1760 * @package core_question
1761 * @category files
1762 * @param stdClass $course course settings object
1763 * @param stdClass $context context object
fe6ce234
DC
1764 * @param string $component the name of the component we are serving files for.
1765 * @param string $filearea the name of the file area.
1766 * @param array $args the remaining bits of the file path.
1767 * @param bool $forcedownload whether the user must be forced to download the file.
7a00d438 1768 * @param array $options additional options affecting the file serving
fe6ce234 1769 */
7a00d438 1770function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
fe6ce234
DC
1771 global $DB, $CFG;
1772
fdb5bc03
TH
1773 if ($filearea === 'questiontext_preview') {
1774 $component = array_shift($args);
1775 $questionid = array_shift($args);
1776
1777 component_callback($component, 'questiontext_preview_pluginfile', array(
7a00d438 1778 $context, $questionid, $args, $forcedownload, $options));
fdb5bc03
TH
1779
1780 send_file_not_found();
1781 }
1782
cde2709a
DC
1783 list($context, $course, $cm) = get_context_info_array($context->id);
1784 require_login($course, false, $cm);
1785
1786 if ($filearea === 'export') {
1787 require_once($CFG->dirroot . '/question/editlib.php');
1788 $contexts = new question_edit_contexts($context);
1789 // check export capability
1790 $contexts->require_one_edit_tab_cap('export');
1791 $category_id = (int)array_shift($args);
1792 $format = array_shift($args);
1793 $cattofile = array_shift($args);
1794 $contexttofile = array_shift($args);
1795 $filename = array_shift($args);
1796
1797 // load parent class for import/export
1798 require_once($CFG->dirroot . '/question/format.php');
1799 require_once($CFG->dirroot . '/question/editlib.php');
1800 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1801
1802 $classname = 'qformat_' . $format;
1803 if (!class_exists($classname)) {
1804 send_file_not_found();
1805 }
1806
1807 $qformat = new $classname();
1808
1809 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
1810 send_file_not_found();
1811 }
1812
1813 $qformat->setCategory($category);
1814 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1815 $qformat->setCourse($course);
1816
1817 if ($cattofile == 'withcategories') {
1818 $qformat->setCattofile(true);
1819 } else {
1820 $qformat->setCattofile(false);
1821 }
1822
1823 if ($contexttofile == 'withcontexts') {
1824 $qformat->setContexttofile(true);
1825 } else {
1826 $qformat->setContexttofile(false);
1827 }
1828
1829 if (!$qformat->exportpreprocess()) {
1830 send_file_not_found();
1831 print_error('exporterror', 'question', $thispageurl->out());
1832 }
1833
1834 // export data to moodle file pool
1835 if (!$content = $qformat->exportprocess(true)) {
1836 send_file_not_found();
1837 }
1838
46732124 1839 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
cde2709a
DC
1840 }
1841
7a719748
TH
1842 $qubaid = (int)array_shift($args);
1843 $slot = (int)array_shift($args);
fe6ce234 1844
7a719748
TH
1845 $module = $DB->get_field('question_usages', 'component',
1846 array('id' => $qubaid));
fe6ce234 1847
7a719748 1848 if ($module === 'core_question_preview') {
fe6ce234
DC
1849 require_once($CFG->dirroot . '/question/previewlib.php');
1850 return question_preview_question_pluginfile($course, $context,
7a00d438 1851 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
fe6ce234
DC
1852
1853 } else {
fe6ce234
DC
1854 $dir = get_component_directory($module);
1855 if (!file_exists("$dir/lib.php")) {
1856 send_file_not_found();
1857 }
1858 include_once("$dir/lib.php");
1859
1860 $filefunction = $module . '_question_pluginfile';
0dd0f963
AB
1861 if (function_exists($filefunction)) {
1862 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1863 $args, $forcedownload, $options);
fe6ce234
DC
1864 }
1865
813f6964
DP
1866 // Okay, we're here so lets check for function without 'mod_'.
1867 if (strpos($module, 'mod_') === 0) {
38d488ce 1868 $filefunctionold = substr($module, 4) . '_question_pluginfile';
0dd0f963
AB
1869 if (function_exists($filefunctionold)) {
1870 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1871 $args, $forcedownload, $options);
1872 }
1873 }
fe6ce234
DC
1874
1875 send_file_not_found();
1876 }
1877}
1878
0019a9b7
TH
1879/**
1880 * Serve questiontext files in the question text when they are displayed in this report.
d2b7803e
DC
1881 *
1882 * @package core_files
1883 * @category files
1884 * @param stdClass $context the context
0019a9b7
TH
1885 * @param int $questionid the question id
1886 * @param array $args remaining file args
1887 * @param bool $forcedownload
7a00d438 1888 * @param array $options additional options affecting the file serving
0019a9b7 1889 */
7a00d438 1890function core_question_questiontext_preview_pluginfile($context, $questionid, $args, $forcedownload, array $options=array()) {
0019a9b7
TH
1891 global $DB;
1892
1893 // Verify that contextid matches the question.
1894 $question = $DB->get_record_sql('
1895 SELECT q.*, qc.contextid
1896 FROM {question} q
1897 JOIN {question_categories} qc ON qc.id = q.category
1898 WHERE q.id = :id AND qc.contextid = :contextid',
1899 array('id' => $questionid, 'contextid' => $context->id), MUST_EXIST);
1900
1901 // Check the capability.
1902 list($context, $course, $cm) = get_context_info_array($context->id);
1903 require_login($course, false, $cm);
1904
1905 question_require_capability_on($question, 'use');
1906
7a00d438 1907 question_send_questiontext_file($questionid, $args, $forcedownload, $options);
0019a9b7
TH
1908}
1909
cde2709a
DC
1910/**
1911 * Create url for question export
1912 *
1913 * @param int $contextid, current context
1914 * @param int $categoryid, categoryid
1915 * @param string $format
1916 * @param string $withcategories
1917 * @param string $ithcontexts
1918 * @param moodle_url export file url
1919 */
aac80ff3
TH
1920function question_make_export_url($contextid, $categoryid, $format, $withcategories,
1921 $withcontexts, $filename) {
cde2709a
DC
1922 global $CFG;
1923 $urlbase = "$CFG->httpswwwroot/pluginfile.php";
aac80ff3
TH
1924 return moodle_url::make_file_url($urlbase,
1925 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
1926 "/{$withcontexts}/{$filename}", true);
cde2709a 1927}
b1627a92
DC
1928
1929/**
1930 * Return a list of page types
1931 * @param string $pagetype current page type
1932 * @param stdClass $parentcontext Block's parent context
1933 * @param stdClass $currentcontext Current context of block
1934 */
b38e2e28 1935function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
1936 global $CFG;
1937 $types = array(
1938 'question-*'=>get_string('page-question-x', 'question'),
1939 'question-edit'=>get_string('page-question-edit', 'question'),
1940 'question-category'=>get_string('page-question-category', 'question'),
1941 'question-export'=>get_string('page-question-export', 'question'),
1942 'question-import'=>get_string('page-question-import', 'question')
1943 );
1944 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1945 require_once($CFG->dirroot . '/course/lib.php');
b38e2e28 1946 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
b1627a92
DC
1947 } else {
1948 return $types;
1949 }
1950}