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