MDL-61410 question: move tag sorting logic to a new function
[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
f29aeb5a
TH
117/**
118 * @param array $questionids of question ids.
119 * @return boolean whether any of these questions are being used by any part of Moodle.
120 */
121function questions_in_use($questionids) {
122 global $CFG;
123
124 if (question_engine::questions_in_use($questionids)) {
125 return true;
126 }
127
bd3b3bba 128 foreach (core_component::get_plugin_list('mod') as $module => $path) {
f29aeb5a
TH
129 $lib = $path . '/lib.php';
130 if (is_readable($lib)) {
131 include_once($lib);
132
133 $fn = $module . '_questions_in_use';
7453df70 134 if (function_exists($fn)) {
f29aeb5a
TH
135 if ($fn($questionids)) {
136 return true;
137 }
138 } else {
139
140 // Fallback for legacy modules.
141 $fn = $module . '_question_list_instances';
142 if (function_exists($fn)) {
143 foreach ($questionids as $questionid) {
144 $instances = $fn($questionid);
145 if (!empty($instances)) {
146 return true;
147 }
148 }
149 }
7453df70 150 }
90c3f310 151 }
152 }
f29aeb5a
TH
153
154 return false;
90c3f310 155}
516cf3eb 156
e2b347e9 157/**
158 * Determine whether there arey any questions belonging to this context, that is whether any of its
159 * question categories contain any questions. This will return true even if all the questions are
160 * hidden.
161 *
162 * @param mixed $context either a context object, or a context id.
163 * @return boolean whether any of the question categories beloning to this context have
164 * any questions in them.
165 */
166function question_context_has_any_questions($context) {
eb84a826 167 global $DB;
e2b347e9 168 if (is_object($context)) {
169 $contextid = $context->id;
170 } else if (is_numeric($context)) {
171 $contextid = $context;
172 } else {
173 print_error('invalidcontextinhasanyquestions', 'question');
174 }
eb84a826 175 return $DB->record_exists_sql("SELECT *
176 FROM {question} q
177 JOIN {question_categories} qc ON qc.id = q.category
178 WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
e2b347e9 179}
180
8511669c 181/**
aa5f0511
TH
182 * Check whether a given grade is one of a list of allowed options. If not,
183 * depending on $matchgrades, either return the nearest match, or return false
184 * to signal an error.
8511669c 185 * @param array $gradeoptionsfull list of valid options
186 * @param int $grade grade to be tested
187 * @param string $matchgrades 'error' or 'nearest'
aa5f0511 188 * @return mixed either 'fixed' value or false if error.
8511669c 189 */
aa5f0511
TH
190function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
191
aac80ff3 192 if ($matchgrades == 'error') {
aa5f0511 193 // (Almost) exact match, or an error.
aac80ff3 194 foreach ($gradeoptionsfull as $value => $option) {
aa5f0511 195 // Slightly fuzzy test, never check floats for equality.
aac80ff3 196 if (abs($grade - $value) < 0.00001) {
aa5f0511 197 return $value; // Be sure the return the proper value.
8511669c 198 }
199 }
aa5f0511 200 // Didn't find a match so that's an error.
8511669c 201 return false;
aa5f0511 202
aac80ff3 203 } else if ($matchgrades == 'nearest') {
aa5f0511
TH
204 // Work out nearest value
205 $best = false;
206 $bestmismatch = 2;
aac80ff3 207 foreach ($gradeoptionsfull as $value => $option) {
aa5f0511
TH
208 $newmismatch = abs($grade - $value);
209 if ($newmismatch < $bestmismatch) {
210 $best = $value;
211 $bestmismatch = $newmismatch;
8511669c 212 }
8511669c 213 }
aa5f0511
TH
214 return $best;
215
aac80ff3 216 } else {
aa5f0511
TH
217 // Unknow option passed.
218 throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
219 ' passed to match_grade_options');
271ffe3f 220 }
8511669c 221}
222
31031e98
FM
223/**
224 * Remove stale questions from a category.
225 *
226 * While questions should not be left behind when they are not used any more,
227 * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
228 * this happens, the users are unable to delete the question category unless
229 * they move those stale questions to another one category, but to them the
230 * category is empty as it does not contain anything. The purpose of this function
231 * is to detect the questions that may have gone stale and remove them.
232 *
233 * You will typically use this prior to checking if the category contains questions.
234 *
235 * The stale questions (unused and hidden to the user) handled are:
236 * - hidden questions
237 * - random questions
238 *
239 * @param int $categoryid The category ID.
240 */
241function question_remove_stale_questions_from_category($categoryid) {
242 global $DB;
243
244 $select = 'category = :categoryid AND (qtype = :qtype OR hidden = :hidden)';
245 $params = ['categoryid' => $categoryid, 'qtype' => 'random', 'hidden' => 1];
246 $questions = $DB->get_recordset_select("question", $select, $params, '', 'id');
247 foreach ($questions as $question) {
248 // The function question_delete_question does not delete questions in use.
249 question_delete_question($question->id);
250 }
251 $questions->close();
252}
253
7f7144fd
TB
254/**
255 * Category is about to be deleted,
256 * 1/ All questions are deleted for this question category.
257 * 2/ Any questions that can't be deleted are moved to a new category
258 * NOTE: this function is called from lib/db/upgrade.php
259 *
260 * @param object|coursecat $category course category object
261 */
262function question_category_delete_safe($category) {
263 global $DB;
264 $criteria = array('category' => $category->id);
265 $context = context::instance_by_id($category->contextid, IGNORE_MISSING);
266 $rescue = null; // See the code around the call to question_save_from_deletion.
267
268 // Deal with any questions in the category.
269 if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
270
271 // Try to delete each question.
272 foreach ($questions as $question) {
273 question_delete_question($question->id);
274 }
275
276 // Check to see if there were any questions that were kept because
277 // they are still in use somehow, even though quizzes in courses
278 // in this category will already have been deleted. This could
279 // happen, for example, if questions are added to a course,
280 // and then that course is moved to another category (MDL-14802).
281 $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
282 if (!empty($questionids)) {
283 $parentcontextid = SYSCONTEXTID;
284 $name = get_string('unknown', 'question');
285 if ($context !== false) {
286 $name = $context->get_context_name();
287 $parentcontext = $context->get_parent_context();
288 if ($parentcontext) {
289 $parentcontextid = $parentcontext->id;
290 }
291 }
292 question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
293 }
294 }
295
296 // Now delete the category.
297 $DB->delete_records('question_categories', array('id' => $category->id));
298}
299
f29aeb5a
TH
300/**
301 * Tests whether any question in a category is used by any part of Moodle.
302 *
303 * @param integer $categoryid a question category id.
304 * @param boolean $recursive whether to check child categories too.
305 * @return boolean whether any question in this category is in use.
306 */
307function question_category_in_use($categoryid, $recursive = false) {
eb84a826 308 global $DB;
f67172b6 309
310 //Look at each question in the category
aac80ff3
TH
311 if ($questions = $DB->get_records_menu('question',
312 array('category' => $categoryid), '', 'id, 1')) {
f29aeb5a
TH
313 if (questions_in_use(array_keys($questions))) {
314 return true;
f67172b6 315 }
316 }
f29aeb5a
TH
317 if (!$recursive) {
318 return false;
319 }
f67172b6 320
321 //Look under child categories recursively
aac80ff3
TH
322 if ($children = $DB->get_records('question_categories',
323 array('parent' => $categoryid), '', 'id, 1')) {
f29aeb5a
TH
324 foreach ($children as $child) {
325 if (question_category_in_use($child->id, $recursive)) {
326 return true;
f67172b6 327 }
328 }
329 }
330
331 return false;
332}
333
516cf3eb 334/**
6b11a0e8 335 * Deletes question and all associated data from the database
336 *
90c3f310 337 * It will not delete a question if it is used by an activity module
6b11a0e8 338 * @param object $question The question being deleted
339 */
f29aeb5a 340function question_delete_question($questionid) {
f9b0500f 341 global $DB;
271ffe3f 342
9203b705
TH
343 $question = $DB->get_record_sql('
344 SELECT q.*, qc.contextid
345 FROM {question} q
346 JOIN {question_categories} qc ON qc.id = q.category
347 WHERE q.id = ?', array($questionid));
348 if (!$question) {
3c573960 349 // In some situations, for example if this was a child of a
350 // Cloze question that was previously deleted, the question may already
351 // have gone. In this case, just do nothing.
352 return;
353 }
354
90c3f310 355 // Do not delete a question if it is used by an activity module
f29aeb5a 356 if (questions_in_use(array($questionid))) {
90c3f310 357 return;
358 }
359
f29aeb5a
TH
360 $dm = new question_engine_data_mapper();
361 $dm->delete_previews($questionid);
0429cd86 362
f29aeb5a
TH
363 // delete questiontype-specific data
364 question_bank::get_qtype($question->qtype, false)->delete_question(
365 $questionid, $question->contextid);
90c3f310 366
cc033d48 367 // Delete all tag instances.
b355a1c9 368 core_tag_tag::remove_all_item_tags('core_question', 'question', $question->id);
cc033d48 369
90c3f310 370 // Now recursively delete all child questions
aac80ff3
TH
371 if ($children = $DB->get_records('question',
372 array('parent' => $questionid), '', 'id, qtype')) {
516cf3eb 373 foreach ($children as $child) {
1d723a16 374 if ($child->id != $questionid) {
7ee214ff 375 question_delete_question($child->id);
1d723a16 376 }
516cf3eb 377 }
378 }
271ffe3f 379
90c3f310 380 // Finally delete the question record itself
f29aeb5a 381 $DB->delete_records('question', array('id' => $questionid));
a560d636 382 question_bank::notify_question_edited($questionid);
516cf3eb 383}
384
f67172b6 385/**
7f7144fd 386 * All question categories and their questions are deleted for this context id.
f67172b6 387 *
7f7144fd
TB
388 * @param object $contextid The contextid to delete question categories from
389 * @return array Feedback from deletes (if any)
f67172b6 390 */
7f7144fd
TB
391function question_delete_context($contextid) {
392 global $DB;
eb84a826 393
f67172b6 394 //To store feedback to be showed at the end of the process
395 $feedbackdata = array();
396
397 //Cache some strings
e0c22222 398 $strcatdeleted = get_string('unusedcategorydeleted', 'question');
7f7144fd
TB
399 $fields = 'id, parent, name, contextid';
400 if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
f67172b6 401 //Sort categories following their tree (parent-child) relationships
3bee1ead 402 //this will make the feedback more readable
7f7144fd 403 $categories = sort_categories_by_tree($categories);
3bee1ead 404
7f7144fd
TB
405 foreach ($categories as $category) {
406 question_category_delete_safe($category);
f67172b6 407
3bee1ead 408 //Fill feedback
409 $feedbackdata[] = array($category->name, $strcatdeleted);
410 }
7f7144fd
TB
411 }
412 return $feedbackdata;
413}
414
415/**
416 * All question categories and their questions are deleted for this course.
417 *
418 * @param stdClass $course an object representing the activity
419 * @param boolean $feedback to specify if the process must output a summary of its work
420 * @return boolean
421 */
422function question_delete_course($course, $feedback=true) {
423 $coursecontext = context_course::instance($course->id);
424 $feedbackdata = question_delete_context($coursecontext->id, $feedback);
425
426 // Inform about changes performed if feedback is enabled.
427 if ($feedback && $feedbackdata) {
428 $table = new html_table();
429 $table->head = array(get_string('category', 'question'), get_string('action'));
430 $table->data = $feedbackdata;
431 echo html_writer::table($table);
3bee1ead 432 }
433 return true;
434}
f67172b6 435
e2b347e9 436/**
437 * Category is about to be deleted,
438 * 1/ All question categories and their questions are deleted for this course category.
439 * 2/ All questions are moved to new category
440 *
b33389d2
MG
441 * @param object|coursecat $category course category object
442 * @param object|coursecat $newcategory empty means everything deleted, otherwise id of
aac80ff3 443 * category where content moved
e2b347e9 444 * @param boolean $feedback to specify if the process must output a summary of its work
445 * @return boolean
446 */
447function question_delete_course_category($category, $newcategory, $feedback=true) {
aa9a6867 448 global $DB, $OUTPUT;
534792cd 449
b0c6dc1c 450 $context = context_coursecat::instance($category->id);
e2b347e9 451 if (empty($newcategory)) {
7f7144fd 452 $feedbackdata = question_delete_context($context->id, $feedback);
e2b347e9 453
454 // Output feedback if requested.
7f7144fd 455 if ($feedback && $feedbackdata) {
642816a6 456 $table = new html_table();
aac80ff3 457 $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
e2b347e9 458 $table->data = $feedbackdata;
16be8974 459 echo html_writer::table($table);
e2b347e9 460 }
461
462 } else {
cc033d48 463 // Move question categories to the new context.
b0c6dc1c 464 if (!$newcontext = context_coursecat::instance($newcategory->id)) {
e2b347e9 465 return false;
466 }
cc033d48
MN
467
468 // Update the contextid for any tag instances for questions in the old context.
b355a1c9 469 core_tag_tag::move_context('core_question', 'question', $context, $newcontext);
cc033d48
MN
470
471 $DB->set_field('question_categories', 'contextid', $newcontext->id, array('contextid' => $context->id));
472
e2b347e9 473 if ($feedback) {
0ff4bd08 474 $a = new stdClass();
329846f1
AG
475 $a->oldplace = $context->get_context_name();
476 $a->newplace = $newcontext->get_context_name();
aac80ff3
TH
477 echo $OUTPUT->notification(
478 get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
e2b347e9 479 }
480 }
481
482 return true;
483}
484
485/**
486 * Enter description here...
487 *
9d0ac0ff 488 * @param array $questionids of question ids
7f7144fd 489 * @param object $newcontextid the context to create the saved category in.
aac80ff3
TH
490 * @param string $oldplace a textual description of the think being deleted,
491 * e.g. from get_context_name
e2b347e9 492 * @param object $newcategory
b9bd6da4 493 * @return mixed false on
e2b347e9 494 */
aac80ff3
TH
495function question_save_from_deletion($questionids, $newcontextid, $oldplace,
496 $newcategory = null) {
eb84a826 497 global $DB;
498
e2b347e9 499 // Make a category in the parent context to move the questions to.
500 if (is_null($newcategory)) {
365a5941 501 $newcategory = new stdClass();
e2b347e9 502 $newcategory->parent = 0;
503 $newcategory->contextid = $newcontextid;
eb84a826 504 $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
505 $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
e2b347e9 506 $newcategory->sortorder = 999;
507 $newcategory->stamp = make_unique_id_code();
a8f3a651 508 $newcategory->id = $DB->insert_record('question_categories', $newcategory);
e2b347e9 509 }
510
511 // Move any remaining questions to the 'saved' category.
512 if (!question_move_questions_to_category($questionids, $newcategory->id)) {
513 return false;
514 }
515 return $newcategory;
516}
517
3bee1ead 518/**
519 * All question categories and their questions are deleted for this activity.
520 *
521 * @param object $cm the course module object representing the activity
522 * @param boolean $feedback to specify if the process must output a summary of its work
523 * @return boolean
524 */
525function question_delete_activity($cm, $feedback=true) {
7f7144fd 526 global $DB;
f67172b6 527
b0c6dc1c 528 $modcontext = context_module::instance($cm->id);
7f7144fd
TB
529 $feedbackdata = question_delete_context($modcontext->id, $feedback);
530 // Inform about changes performed if feedback is enabled.
531 if ($feedback && $feedbackdata) {
532 $table = new html_table();
533 $table->head = array(get_string('category', 'question'), get_string('action'));
534 $table->data = $feedbackdata;
535 echo html_writer::table($table);
f67172b6 536 }
537 return true;
538}
7fb1b88d 539
68beb758
RW
540/**
541 * This function will handle moving all tag instances to a new context for a
542 * given list of questions.
543 *
544 * Questions can be tagged in up to two contexts:
545 * 1.) The context the question exists in.
546 * 2.) The course context (if the question context is a higher context.
547 * E.g. course category context or system context.
548 *
549 * This means a question that exists in a higher context (e.g. course cat or
550 * system context) may have multiple groups of tags in any number of child
551 * course contexts.
552 *
553 * Questions in the course category context can be move "down" a context level
554 * into one of their child course contexts or activity contexts which affects the
555 * availability of that question in other courses / activities.
556 *
557 * In this case it makes the questions no longer available in the other course or
558 * activity contexts so we need to make sure that the tag instances in those other
559 * contexts are removed.
560 *
561 * @param stdClass[] $questions The list of question being moved (must include
562 * the id and contextid)
563 * @param context $newcontext The Moodle context the questions are being moved to
564 */
565function question_move_question_tags_to_new_context(array $questions, context $newcontext) {
566 // If the questions are moving to a new course/activity context then we need to
567 // find any existing tag instances from any unavailable course contexts and
568 // delete them because they will no longer be applicable (we don't support
569 // tagging questions across courses).
570 $instancestodelete = [];
571 $instancesfornewcontext = [];
572 $newcontextparentids = $newcontext->get_parent_context_ids();
573 $questionids = array_map(function($question) {
574 return $question->id;
575 }, $questions);
576 $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
577
578 foreach ($questions as $question) {
579 $tagobjects = $questionstagobjects[$question->id];
580
581 foreach ($tagobjects as $tagobject) {
582 $tagid = $tagobject->taginstanceid;
583 $tagcontextid = $tagobject->taginstancecontextid;
584 $istaginnewcontext = $tagcontextid == $newcontext->id;
585 $istaginquestioncontext = $tagcontextid == $question->contextid;
586
587 if ($istaginnewcontext) {
588 // This tag instance is already in the correct context so we can
589 // ignore it.
590 continue;
591 }
592
593 if ($istaginquestioncontext) {
594 // This tag instance is in the question context so it needs to be
595 // updated.
596 $instancesfornewcontext[] = $tagid;
597 continue;
598 }
599
600 // These tag instances are in neither the new context nor the
601 // question context so we need to determine what to do based on
602 // the context they are in and the new question context.
603 $tagcontext = context::instance_by_id($tagcontextid);
604 $tagcoursecontext = $tagcontext->get_course_context(false);
605 // The tag is in a course context if get_course_context() returns
606 // itself.
607 $istaginstancecontextcourse = !empty($tagcoursecontext)
608 && $tagcontext->id == $tagcoursecontext->id;
609
610 if ($istaginstancecontextcourse) {
611 // If the tag instance is in a course context we need to add some
612 // special handling.
613 $tagcontextparentids = $tagcontext->get_parent_context_ids();
614 $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
615 $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
616
617 if ($isnewcontextaparent) {
618 // If the tag instance is a course context tag and the new
619 // context is still a parent context to the tag context then
620 // we can leave this tag where it is.
621 continue;
622 } else if ($isnewcontextachild) {
623 // If the new context is a child context (e.g. activity) of this
624 // tag instance then we should move all of this tag instance
625 // down into the activity context along with the question.
626 $instancesfornewcontext[] = $tagid;
627 } else {
628 // If the tag is in a course context that is no longer a parent
629 // or child of the new context then this tag instance should be
630 // removed.
631 $instancestodelete[] = $tagid;
632 }
633 } else {
634 // This is a catch all for any tag instances not in the question
635 // context or a course context. These tag instances should be
636 // updated to the new context id. This will clean up old invalid
637 // data.
638 $instancesfornewcontext[] = $tagid;
639 }
640 }
641 }
642
643 if (!empty($instancestodelete)) {
644 // Delete any course context tags that may no longer be valid.
645 core_tag_tag::delete_instances_by_id($instancestodelete);
646 }
647
648 if (!empty($instancesfornewcontext)) {
649 // Update the tag instances to the new context id.
650 core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
651 }
652}
653
7fb1b88d 654/**
655 * This function should be considered private to the question bank, it is called from
aac80ff3
TH
656 * question/editlib.php question/contextmoveq.php and a few similar places to to the
657 * work of acutally moving questions and associated data. However, callers of this
658 * function also have to do other work, which is why you should not call this method
659 * directly from outside the questionbank.
7fb1b88d 660 *
9d0ac0ff 661 * @param array $questionids of question ids.
fe6ce234 662 * @param integer $newcategoryid the id of the category to move to.
7fb1b88d 663 */
fe6ce234 664function question_move_questions_to_category($questionids, $newcategoryid) {
d649fb02 665 global $DB;
f685e830 666
5d548d3e
TH
667 $newcontextid = $DB->get_field('question_categories', 'contextid',
668 array('id' => $newcategoryid));
669 list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
670 $questions = $DB->get_records_sql("
671 SELECT q.id, q.qtype, qc.contextid
672 FROM {question} q
673 JOIN {question_categories} qc ON q.category = qc.id
a3f92b2e 674 WHERE q.id $questionidcondition", $params);
5d548d3e
TH
675 foreach ($questions as $question) {
676 if ($newcontextid != $question->contextid) {
d649fb02
TH
677 question_bank::get_qtype($question->qtype)->move_files(
678 $question->id, $question->contextid, $newcontextid);
5d548d3e 679 }
fe6ce234
DC
680 }
681
7fb1b88d 682 // Move the questions themselves.
aac80ff3
TH
683 $DB->set_field_select('question', 'category', $newcategoryid,
684 "id $questionidcondition", $params);
7fb1b88d 685
686 // Move any subquestions belonging to them.
aac80ff3
TH
687 $DB->set_field_select('question', 'category', $newcategoryid,
688 "parent $questionidcondition", $params);
7fb1b88d 689
68beb758
RW
690 $newcontext = context::instance_by_id($newcontextid);
691 question_move_question_tags_to_new_context($questions, $newcontext);
cc033d48 692
7fb1b88d 693 // TODO Deal with datasets.
694
a560d636
TH
695 // Purge these questions from the cache.
696 foreach ($questions as $question) {
697 question_bank::notify_question_edited($question->id);
698 }
699
f685e830 700 return true;
7fb1b88d 701}
702
5d548d3e
TH
703/**
704 * This function helps move a question cateogry to a new context by moving all
705 * the files belonging to all the questions to the new context.
706 * Also moves subcategories.
707 * @param integer $categoryid the id of the category being moved.
708 * @param integer $oldcontextid the old context id.
709 * @param integer $newcontextid the new context id.
710 */
711function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
d649fb02 712 global $DB;
5d548d3e 713
68beb758 714 $questions = [];
5d548d3e
TH
715 $questionids = $DB->get_records_menu('question',
716 array('category' => $categoryid), '', 'id,qtype');
717 foreach ($questionids as $questionid => $qtype) {
aac80ff3
TH
718 question_bank::get_qtype($qtype)->move_files(
719 $questionid, $oldcontextid, $newcontextid);
a560d636
TH
720 // Purge this question from the cache.
721 question_bank::notify_question_edited($questionid);
68beb758
RW
722
723 $questions[] = (object) [
724 'id' => $questionid,
725 'contextid' => $oldcontextid
726 ];
5d548d3e
TH
727 }
728
68beb758
RW
729 $newcontext = context::instance_by_id($newcontextid);
730 question_move_question_tags_to_new_context($questions, $newcontext);
cc033d48 731
5d548d3e
TH
732 $subcatids = $DB->get_records_menu('question_categories',
733 array('parent' => $categoryid), '', 'id,1');
734 foreach ($subcatids as $subcatid => $notused) {
aac80ff3
TH
735 $DB->set_field('question_categories', 'contextid', $newcontextid,
736 array('id' => $subcatid));
5d548d3e
TH
737 question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
738 }
739}
740
f29aeb5a
TH
741/**
742 * Generate the URL for starting a new preview of a given question with the given options.
743 * @param integer $questionid the question to preview.
744 * @param string $preferredbehaviour the behaviour to use for the preview.
745 * @param float $maxmark the maximum to mark the question out of.
746 * @param question_display_options $displayoptions the display options to use.
c014b989
TH
747 * @param int $variant the variant of the question to preview. If null, one will
748 * be picked randomly.
56a4ae46
TH
749 * @param object $context context to run the preview in (affects things like
750 * filter settings, theme, lang, etc.) Defaults to $PAGE->context.
8011be18 751 * @return moodle_url the URL.
f29aeb5a 752 */
612106b3 753function question_preview_url($questionid, $preferredbehaviour = null,
56a4ae46 754 $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
612106b3
TH
755
756 $params = array('id' => $questionid);
757
56a4ae46
TH
758 if (is_null($context)) {
759 global $PAGE;
760 $context = $PAGE->context;
761 }
762 if ($context->contextlevel == CONTEXT_MODULE) {
763 $params['cmid'] = $context->instanceid;
764 } else if ($context->contextlevel == CONTEXT_COURSE) {
765 $params['courseid'] = $context->instanceid;
766 }
767
612106b3
TH
768 if (!is_null($preferredbehaviour)) {
769 $params['behaviour'] = $preferredbehaviour;
770 }
771
772 if (!is_null($maxmark)) {
773 $params['maxmark'] = $maxmark;
774 }
775
776 if (!is_null($displayoptions)) {
777 $params['correctness'] = $displayoptions->correctness;
778 $params['marks'] = $displayoptions->marks;
779 $params['markdp'] = $displayoptions->markdp;
780 $params['feedback'] = (bool) $displayoptions->feedback;
781 $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
782 $params['rightanswer'] = (bool) $displayoptions->rightanswer;
783 $params['history'] = (bool) $displayoptions->history;
784 }
785
c014b989
TH
786 if ($variant) {
787 $params['variant'] = $variant;
788 }
612106b3 789
c014b989 790 return new moodle_url('/question/preview.php', $params);
f29aeb5a
TH
791}
792
612106b3
TH
793/**
794 * @return array that can be passed as $params to the {@link popup_action} constructor.
795 */
796function question_preview_popup_params() {
797 return array(
798 'height' => 600,
799 'width' => 800,
800 );
801}
802
5a2a5331 803/**
aac80ff3
TH
804 * Given a list of ids, load the basic information about a set of questions from
805 * the questions table. The $join and $extrafields arguments can be used together
806 * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
78e7a3dd 807 * read the code below to see how the SQL is assembled. Throws exceptions on error.
5a2a5331 808 *
ccba5b88
TH
809 * @param array $questionids array of question ids to load. If null, then all
810 * questions matched by $join will be loaded.
78e7a3dd 811 * @param string $extrafields extra SQL code to be added to the query.
812 * @param string $join extra SQL code to be added to the query.
813 * @param array $extraparams values for any placeholders in $join.
ccba5b88
TH
814 * You must use named placeholders.
815 * @param string $orderby what to order the results by. Optional, default is unspecified order.
5a2a5331 816 *
78e7a3dd 817 * @return array partially complete question objects. You need to call get_question_options
818 * on them before they can be properly used.
5a2a5331 819 */
ccba5b88
TH
820function question_preload_questions($questionids = null, $extrafields = '', $join = '',
821 $extraparams = array(), $orderby = '') {
f29aeb5a 822 global $DB;
ccba5b88
TH
823
824 if ($questionids === null) {
825 $where = '';
826 $params = array();
827 } else {
828 if (empty($questionids)) {
829 return array();
830 }
831
832 list($questionidcondition, $params) = $DB->get_in_or_equal(
833 $questionids, SQL_PARAMS_NAMED, 'qid0000');
834 $where = 'WHERE q.id ' . $questionidcondition;
4089d9ec 835 }
ccba5b88 836
5a2a5331 837 if ($join) {
ccba5b88 838 $join = 'JOIN ' . $join;
5a2a5331 839 }
ccba5b88 840
5a2a5331 841 if ($extrafields) {
842 $extrafields = ', ' . $extrafields;
843 }
5a2a5331 844
ccba5b88
TH
845 if ($orderby) {
846 $orderby = 'ORDER BY ' . $orderby;
5a2a5331 847 }
848
ccba5b88
TH
849 $sql = "SELECT q.*, qc.contextid{$extrafields}
850 FROM {question} q
851 JOIN {question_categories} qc ON q.category = qc.id
852 {$join}
853 {$where}
854 {$orderby}";
855
856 // Load the questions.
857 $questions = $DB->get_records_sql($sql, $extraparams + $params);
78e7a3dd 858 foreach ($questions as $question) {
859 $question->_partiallyloaded = true;
860 }
861
862 return $questions;
863}
864
865/**
866 * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
867 * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
868 * read the code below to see how the SQL is assembled. Throws exceptions on error.
869 *
870 * @param array $questionids array of question ids.
871 * @param string $extrafields extra SQL code to be added to the query.
872 * @param string $join extra SQL code to be added to the query.
873 * @param array $extraparams values for any placeholders in $join.
874 * You are strongly recommended to use named placeholder.
875 *
876 * @return array question objects.
877 */
878function question_load_questions($questionids, $extrafields = '', $join = '') {
879 $questions = question_preload_questions($questionids, $extrafields, $join);
880
5a2a5331 881 // Load the question type specific information
882 if (!get_question_options($questions)) {
883 return 'Could not load the question options';
884 }
885
886 return $questions;
887}
888
516cf3eb 889/**
d7444d44 890 * Private function to factor common code out of get_question_options().
271ffe3f 891 *
d7444d44 892 * @param object $question the question to tidy.
081eb156
RW
893 * @param stdClass $category The question_categories record for the given $question.
894 * @param stdClass[]|null $tagobjects The tags for the given $question.
895 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
d7444d44 896 */
081eb156 897function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null) {
d649fb02 898 global $CFG;
d2acbd1a
TH
899
900 // Load question-type specific fields.
2daffca5 901 if (!question_bank::is_qtype_installed($question->qtype)) {
d649fb02
TH
902 $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
903 'qtype_missingtype')) . $question->questiontext;
d7444d44 904 }
d649fb02 905 question_bank::get_qtype($question->qtype)->get_question_options($question);
d2acbd1a
TH
906
907 // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
908 $question->defaultmark += 0;
909 $question->penalty += 0;
910
a8a8ec51
TH
911 if (isset($question->_partiallyloaded)) {
912 unset($question->_partiallyloaded);
78e7a3dd 913 }
d2acbd1a 914
081eb156
RW
915 $question->categoryobject = $category;
916
917 if (!is_null($tagobjects)) {
918 $categorycontext = context::instance_by_id($category->contextid);
6307622b
SL
919 $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
920 $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
921 $question->coursetags = $sortedtagobjects->coursetags;
922 $question->tagobjects = $sortedtagobjects->tagobjects;
923 $question->tags = $sortedtagobjects->tags;
c599a682 924 }
d7444d44 925}
516cf3eb 926
d7444d44 927/**
928 * Updates the question objects with question type specific
929 * information by calling {@link get_question_options()}
930 *
931 * Can be called either with an array of question objects or with a single
932 * question object.
271ffe3f 933 *
d7444d44 934 * @param mixed $questions Either an array of question objects to be updated
935 * or just a single question object
081eb156
RW
936 * @param bool $loadtags load the question tags from the tags table. Optional, default false.
937 * @param stdClass[] $filtercourses The courses to filter the course tags by.
d7444d44 938 * @return bool Indicates success or failure.
939 */
081eb156
RW
940function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
941 global $DB;
942
943 $questionlist = is_array($questions) ? $questions : [$questions];
944 $categoryids = [];
945 $questionids = [];
946
947 if (empty($questionlist)) {
948 return true;
949 }
950
951 foreach ($questionlist as $question) {
952 $questionids[] = $question->id;
953
954 if (!in_array($question->category, $categoryids)) {
955 $categoryids[] = $question->category;
516cf3eb 956 }
516cf3eb 957 }
081eb156
RW
958
959 $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
960
961 if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
962 $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
963 } else {
964 $tagobjectsbyquestion = null;
965 }
966
967 foreach ($questionlist as $question) {
968 if (is_null($tagobjectsbyquestion)) {
969 $tagobjects = null;
970 } else {
971 $tagobjects = $tagobjectsbyquestion[$question->id];
972 }
973
974 _tidy_question($question, $categories[$question->category], $tagobjects, $filtercourses);
975 }
976
a8a8ec51 977 return true;
516cf3eb 978}
979
6307622b
SL
980/**
981 * Sort question tags by course or normal tags.
982 *
983 * This function also search tag instances that may have a context id that don't match either a course or
984 * question context and fix the data setting the correct context id.
985 *
986 * @param stdClass[] $tagobjects The tags for the given $question.
987 * @param stdClass $categorycontext The question categories context.
988 * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
989 * @return stdClass $sortedtagobjects Sorted tag objects.
990 */
991function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null) {
992
993 // Questions can have two sets of tag instances. One set at the
994 // course context level and another at the context the question
995 // belongs to (e.g. course category, system etc).
996 $sortedtagobjects = new stdClass();
997 $sortedtagobjects->coursetagobjects = [];
998 $sortedtagobjects->coursetags = [];
999 $sortedtagobjects->tagobjects = [];
1000 $sortedtagobjects->tags = [];
1001 $taginstanceidstonormalise = [];
1002 $filtercoursecontextids = [];
1003 $hasfiltercourses = !empty($filtercourses);
1004
1005 if ($hasfiltercourses) {
1006 // If we're being asked to filter the course tags by a set of courses
1007 // then get the context ids to filter below.
1008 $filtercoursecontextids = array_map(function($course) {
1009 $coursecontext = context_course::instance($course->id);
1010 return $coursecontext->id;
1011 }, $filtercourses);
1012 }
1013
1014 foreach ($tagobjects as $tagobject) {
1015 $tagcontextid = $tagobject->taginstancecontextid;
1016 $tagcontext = context::instance_by_id($tagcontextid);
1017 $tagcoursecontext = $tagcontext->get_course_context(false);
1018 // This is a course tag if the tag context is a course context which
1019 // doesn't match the question's context. Any tag in the question context
1020 // is not considered a course tag, it belongs to the question.
1021 $iscoursetag = $tagcoursecontext
1022 && $tagcontext->id == $tagcoursecontext->id
1023 && $tagcontext->id != $categorycontext->id;
1024
1025 if ($iscoursetag) {
1026 // Any tag instance in a course context level is considered a course tag.
1027 if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1028 // Add the tag to the list of course tags if we aren't being
1029 // asked to filter or if this tag is in the list of courses
1030 // we're being asked to filter by.
1031 $sortedtagobjects->coursetagobjects[] = $tagobject;
1032 $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1033 }
1034 } else {
1035 // All non course context level tag instances or tags in the question
1036 // context belong to the context that the question was created in.
1037 $sortedtagobjects->tagobjects[] = $tagobject;
1038 $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1039
1040 // Due to legacy tag implementations that don't force the recording
1041 // of a context id, some tag instances may have context ids that don't
1042 // match either a course context or the question context. In this case
1043 // we should take the opportunity to fix up the data and set the correct
1044 // context id.
1045 if ($tagcontext->id != $categorycontext->id) {
1046 $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1047 // Update the object properties to reflect the DB update that will
1048 // happen below.
1049 $tagobject->taginstancecontextid = $categorycontext->id;
1050 }
1051 }
1052 }
1053
1054 if (!empty($taginstanceidstonormalise)) {
1055 // If we found any tag instances with incorrect context id data then we can
1056 // correct those values now by setting them to the question context id.
1057 core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1058 }
1059
1060 return $sortedtagobjects;
1061}
1062
516cf3eb 1063/**
aac80ff3
TH
1064 * Print the icon for the question type
1065 *
1066 * @param object $question The question object for which the icon is required.
1067 * Only $question->qtype is used.
1068 * @return string the HTML for the img tag.
1069 */
f29aeb5a 1070function print_question_icon($question) {
5cc021a0
TH
1071 global $PAGE;
1072 return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
81d833ad 1073}
1074
1075/**
f29aeb5a 1076 * Creates a stamp that uniquely identifies this version of the question
81d833ad 1077 *
f29aeb5a
TH
1078 * In future we want this to use a hash of the question data to guarantee that
1079 * identical versions have the same version stamp.
1080 *
1081 * @param object $question
1082 * @return string A unique version stamp
81d833ad 1083 */
f29aeb5a
TH
1084function question_hash($question) {
1085 return make_unique_id_code();
81d833ad 1086}
1087
f29aeb5a
TH
1088/// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1089
516cf3eb 1090/**
f29aeb5a
TH
1091 * returns the categories with their names ordered following parent-child relationships
1092 * finally it tries to return pending categories (those being orphaned, whose parent is
1093 * incorrect) to avoid missing any category from original array.
1094 */
1095function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1096 global $DB;
5e9170b4 1097
f29aeb5a
TH
1098 $children = array();
1099 $keys = array_keys($categories);
516cf3eb 1100
f29aeb5a
TH
1101 foreach ($keys as $key) {
1102 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1103 $children[$key] = $categories[$key];
1104 $categories[$key]->processed = true;
aac80ff3
TH
1105 $children = $children + sort_categories_by_tree(
1106 $categories, $children[$key]->id, $level+1);
516cf3eb 1107 }
1108 }
aac80ff3
TH
1109 //If level = 1, we have finished, try to look for non processed categories
1110 // (bad parent) and sort them too
f29aeb5a
TH
1111 if ($level == 1) {
1112 foreach ($keys as $key) {
aac80ff3
TH
1113 // If not processed and it's a good candidate to start (because its
1114 // parent doesn't exist in the course)
1115 if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1116 array('contextid' => $categories[$key]->contextid,
1117 'id' => $categories[$key]->parent))) {
f29aeb5a
TH
1118 $children[$key] = $categories[$key];
1119 $categories[$key]->processed = true;
aac80ff3
TH
1120 $children = $children + sort_categories_by_tree(
1121 $categories, $children[$key]->id, $level + 1);
f29aeb5a
TH
1122 }
1123 }
516cf3eb 1124 }
f29aeb5a 1125 return $children;
6cb4910c 1126}
1127
1128/**
062a7522 1129 * Private method, only for the use of add_indented_names().
271ffe3f 1130 *
062a7522 1131 * Recursively adds an indentedname field to each category, starting with the category
271ffe3f 1132 * with id $id, and dealing with that category and all its children, and
062a7522 1133 * return a new array, with those categories in the right order.
1134 *
271ffe3f 1135 * @param array $categories an array of categories which has had childids
062a7522 1136 * fields added by flatten_category_tree(). Passed by reference for
1137 * performance only. It is not modfied.
1138 * @param int $id the category to start the indenting process from.
1139 * @param int $depth the indent depth. Used in recursive calls.
1140 * @return array a new array of categories, in the right order for the tree.
6cb4910c 1141 */
3bee1ead 1142function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
271ffe3f 1143
062a7522 1144 // Indent the name of this category.
1145 $newcategories = array();
1146 $newcategories[$id] = $categories[$id];
aac80ff3
TH
1147 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
1148 $categories[$id]->name;
271ffe3f 1149
062a7522 1150 // Recursively indent the children.
1151 foreach ($categories[$id]->childids as $childid) {
aac80ff3
TH
1152 if ($childid != $nochildrenof) {
1153 $newcategories = $newcategories + flatten_category_tree(
1154 $categories, $childid, $depth + 1, $nochildrenof);
3bee1ead 1155 }
6cb4910c 1156 }
271ffe3f 1157
062a7522 1158 // Remove the childids array that were temporarily added.
1159 unset($newcategories[$id]->childids);
271ffe3f 1160
062a7522 1161 return $newcategories;
6cb4910c 1162}
1163
1164/**
062a7522 1165 * Format categories into an indented list reflecting the tree structure.
271ffe3f 1166 *
062a7522 1167 * @param array $categories An array of category objects, for example from the.
1168 * @return array The formatted list of categories.
6cb4910c 1169 */
3bee1ead 1170function add_indented_names($categories, $nochildrenof = -1) {
6cb4910c 1171
aac80ff3
TH
1172 // Add an array to each category to hold the child category ids. This array
1173 // will be removed again by flatten_category_tree(). It should not be used
1174 // outside these two functions.
062a7522 1175 foreach (array_keys($categories) as $id) {
1176 $categories[$id]->childids = array();
6cb4910c 1177 }
1178
062a7522 1179 // Build the tree structure, and record which categories are top-level.
271ffe3f 1180 // We have to be careful, because the categories array may include published
062a7522 1181 // categories from other courses, but not their parents.
1182 $toplevelcategoryids = array();
1183 foreach (array_keys($categories) as $id) {
aac80ff3
TH
1184 if (!empty($categories[$id]->parent) &&
1185 array_key_exists($categories[$id]->parent, $categories)) {
062a7522 1186 $categories[$categories[$id]->parent]->childids[] = $id;
1187 } else {
1188 $toplevelcategoryids[] = $id;
6cb4910c 1189 }
1190 }
1191
062a7522 1192 // Flatten the tree to and add the indents.
1193 $newcategories = array();
1194 foreach ($toplevelcategoryids as $id) {
aac80ff3
TH
1195 $newcategories = $newcategories + flatten_category_tree(
1196 $categories, $id, 0, $nochildrenof);
6cb4910c 1197 }
1198
062a7522 1199 return $newcategories;
6cb4910c 1200}
2dd6d66b 1201
516cf3eb 1202/**
062a7522 1203 * Output a select menu of question categories.
271ffe3f 1204 *
062a7522 1205 * Categories from this course and (optionally) published categories from other courses
271ffe3f 1206 * are included. Optionally, only categories the current user may edit can be included.
062a7522 1207 *
1208 * @param integer $courseid the id of the course to get the categories for.
1209 * @param integer $published if true, include publised categories from other courses.
1210 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
aac80ff3
TH
1211 * @param integer $selected optionally, the id of a category to be selected by
1212 * default in the dropdown.
062a7522 1213 */
aac80ff3
TH
1214function question_category_select_menu($contexts, $top = false, $currentcat = 0,
1215 $selected = "", $nochildrenof = -1) {
aac80ff3
TH
1216 $categoriesarray = question_category_options($contexts, $top, $currentcat,
1217 false, $nochildrenof);
3ed998f3 1218 if ($selected) {
6770330d 1219 $choose = '';
3ed998f3 1220 } else {
6770330d 1221 $choose = 'choosedots';
516cf3eb 1222 }
6770330d 1223 $options = array();
aac80ff3
TH
1224 foreach ($categoriesarray as $group => $opts) {
1225 $options[] = array($group => $opts);
6770330d 1226 }
9422f6ee 1227 echo html_writer::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
12d6dfc1
DW
1228 $attrs = array('id' => 'id_movetocategory', 'class' => 'custom-select');
1229 echo html_writer::select($options, 'category', $selected, $choose, $attrs);
516cf3eb 1230}
1231
cca6e300 1232/**
1233 * @param integer $contextid a context id.
1234 * @return object the default question category for that context, or false if none.
1235 */
1236function question_get_default_category($contextid) {
1237 global $DB;
bb063971
SR
1238 $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1239 array($contextid), 'id', '*', 0, 1);
cca6e300 1240 if (!empty($category)) {
1241 return reset($category);
1242 } else {
1243 return false;
1244 }
1245}
1246
bb063971
SR
1247/**
1248 * Gets the top category in the given context.
1249 * This function can optionally create the top category if it doesn't exist.
1250 *
1251 * @param int $contextid A context id.
1252 * @param bool $create Whether create a top category if it doesn't exist.
1253 * @return bool|stdClass The top question category for that context, or false if none.
1254 */
1255function question_get_top_category($contextid, $create = false) {
1256 global $DB;
1257 $category = $DB->get_record('question_categories',
1258 array('contextid' => $contextid, 'parent' => 0));
1259
1260 if (!$category && $create) {
1261 // We need to make one.
1262 $category = new stdClass();
1263 $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1264 $category->info = '';
1265 $category->contextid = $contextid;
1266 $category->parent = 0;
1267 $category->sortorder = 0;
1268 $category->stamp = make_unique_id_code();
1269 $category->id = $DB->insert_record('question_categories', $category);
1270 }
1271
1272 return $category;
1273}
1274
3b8f3198
SR
1275/**
1276 * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1277 *
1278 * @param array $contextids List of context ids
1279 * @return array
1280 */
1281function question_get_top_categories_for_contexts($contextids) {
1282 global $DB;
1283
1284 $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1285 list($insql, $params) = $DB->get_in_or_equal($contextids);
1286 $sql = "SELECT $concatsql FROM {question_categories} WHERE contextid $insql AND parent = 0";
1287 $topcategories = $DB->get_fieldset_sql($sql, $params);
1288
1289 return $topcategories;
1290}
1291
8f0f605d 1292/**
aac80ff3
TH
1293 * Gets the default category in the most specific context.
1294 * If no categories exist yet then default ones are created in all contexts.
1295 *
1296 * @param array $contexts The context objects for this context and all parent contexts.
1297 * @return object The default category - the category in the course context
1298 */
8f0f605d 1299function question_make_default_categories($contexts) {
eb84a826 1300 global $DB;
353b2d70 1301 static $preferredlevels = array(
1302 CONTEXT_COURSE => 4,
1303 CONTEXT_MODULE => 3,
1304 CONTEXT_COURSECAT => 2,
1305 CONTEXT_SYSTEM => 1,
1306 );
eb84a826 1307
8f0f605d 1308 $toreturn = null;
353b2d70 1309 $preferredness = 0;
8f0f605d 1310 // If it already exists, just return it.
1311 foreach ($contexts as $key => $context) {
bb063971 1312 $topcategory = question_get_top_category($context->id, true);
aac80ff3 1313 if (!$exists = $DB->record_exists("question_categories",
bb063971 1314 array('contextid' => $context->id, 'parent' => $topcategory->id))) {
eb84a826 1315 // Otherwise, we need to make one
0ff4bd08 1316 $category = new stdClass();
329846f1 1317 $contextname = $context->get_context_name(false, true);
eb84a826 1318 $category->name = get_string('defaultfor', 'question', $contextname);
1319 $category->info = get_string('defaultinfofor', 'question', $contextname);
1320 $category->contextid = $context->id;
bb063971 1321 $category->parent = $topcategory->id;
aac80ff3
TH
1322 // By default, all categories get this number, and are sorted alphabetically.
1323 $category->sortorder = 999;
eb84a826 1324 $category->stamp = make_unique_id_code();
bf8e93d7 1325 $category->id = $DB->insert_record('question_categories', $category);
b9bd6da4 1326 } else {
cca6e300 1327 $category = question_get_default_category($context->id);
8f0f605d 1328 }
76cf77e4
TH
1329 $thispreferredness = $preferredlevels[$context->contextlevel];
1330 if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1331 $thispreferredness += 10;
1332 }
1333 if ($thispreferredness > $preferredness) {
353b2d70 1334 $toreturn = $category;
76cf77e4 1335 $preferredness = $thispreferredness;
8f0f605d 1336 }
1337 }
1338
353b2d70 1339 if (!is_null($toreturn)) {
1340 $toreturn = clone($toreturn);
1341 }
8f0f605d 1342 return $toreturn;
1343}
1344
375ed78a 1345/**
3bee1ead 1346 * Get all the category objects, including a count of the number of questions in that category,
1347 * for all the categories in the lists $contexts.
375ed78a 1348 *
3bee1ead 1349 * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
1350 * @param string $sortorder used as the ORDER BY clause in the select statement.
bb063971 1351 * @param bool $top Whether to return the top categories or not.
3bee1ead 1352 * @return array of category objects.
375ed78a 1353 */
bb063971 1354function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
eb84a826 1355 global $DB;
bb063971 1356 $topwhere = $top ? '' : 'AND c.parent <> 0';
eb84a826 1357 return $DB->get_records_sql("
630a3dc3 1358 SELECT c.*, (SELECT count(1) FROM {question} q
eb84a826 1359 WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
1360 FROM {question_categories} c
bb063971 1361 WHERE c.contextid IN ($contexts) $topwhere
eb84a826 1362 ORDER BY $sortorder");
3bee1ead 1363}
3a3c454e 1364
3bee1ead 1365/**
1366 * Output an array of question categories.
bb063971
SR
1367 *
1368 * @param array $contexts The list of contexts.
1369 * @param bool $top Whether to return the top categories or not.
1370 * @param int $currentcat
1371 * @param bool $popupform
1372 * @param int $nochildrenof
1373 * @return array
3bee1ead 1374 */
aac80ff3
TH
1375function question_category_options($contexts, $top = false, $currentcat = 0,
1376 $popupform = false, $nochildrenof = -1) {
3bee1ead 1377 global $CFG;
1378 $pcontexts = array();
aac80ff3 1379 foreach ($contexts as $context) {
3bee1ead 1380 $pcontexts[] = $context->id;
61d9b9fc 1381 }
3bee1ead 1382 $contextslist = join($pcontexts, ', ');
1383
bb063971 1384 $categories = get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
3bee1ead 1385
aac80ff3 1386 if ($top) {
bb063971 1387 $categories = question_fix_top_names($categories);
3bee1ead 1388 }
bb063971
SR
1389
1390 $categories = question_add_context_in_key($categories);
3bee1ead 1391 $categories = add_indented_names($categories, $nochildrenof);
3ed998f3 1392
aac80ff3 1393 // sort cats out into different contexts
375ed78a 1394 $categoriesarray = array();
fc51c2bc
TH
1395 foreach ($pcontexts as $contextid) {
1396 $context = context::instance_by_id($contextid);
1397 $contextstring = $context->get_context_name(true, true);
3bee1ead 1398 foreach ($categories as $category) {
fc51c2bc 1399 if ($category->contextid == $contextid) {
3bee1ead 1400 $cid = $category->id;
aac80ff3
TH
1401 if ($currentcat != $cid || $currentcat == 0) {
1402 $countstring = !empty($category->questioncount) ?
1403 " ($category->questioncount)" : '';
fc51c2bc
TH
1404 $categoriesarray[$contextstring][$cid] =
1405 format_string($category->indentedname, true,
1406 array('context' => $context)) . $countstring;
3bee1ead 1407 }
1408 }
375ed78a 1409 }
1410 }
aac80ff3 1411 if ($popupform) {
3bee1ead 1412 $popupcats = array();
aac80ff3 1413 foreach ($categoriesarray as $contextstring => $optgroup) {
94fa6be4 1414 $group = array();
aac80ff3 1415 foreach ($optgroup as $key => $value) {
78bfb562
PS
1416 $key = str_replace($CFG->wwwroot, '', $key);
1417 $group[$key] = $value;
94fa6be4 1418 }
aac80ff3 1419 $popupcats[] = array($contextstring => $group);
3bee1ead 1420 }
1421 return $popupcats;
1422 } else {
1423 return $categoriesarray;
1424 }
375ed78a 1425}
1426
aac80ff3 1427function question_add_context_in_key($categories) {
3bee1ead 1428 $newcatarray = array();
1429 foreach ($categories as $id => $category) {
1430 $category->parent = "$category->parent,$category->contextid";
1431 $category->id = "$category->id,$category->contextid";
1432 $newcatarray["$id,$category->contextid"] = $category;
516cf3eb 1433 }
3bee1ead 1434 return $newcatarray;
1435}
f29aeb5a 1436
bb063971
SR
1437/**
1438 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
1439 *
1440 * @param array $categories An array of question categories.
1441 * @return array The same question category list given to the function, with the top category names being translated.
1442 */
1443function question_fix_top_names($categories) {
1444
1445 foreach ($categories as $id => $category) {
1446 if ($category->parent == 0) {
1447 $categories[$id]->name = get_string('top');
1448 }
3bee1ead 1449 }
bb063971
SR
1450
1451 return $categories;
516cf3eb 1452}
1453
516cf3eb 1454/**
2daffca5 1455 * @return array of question category ids of the category and all subcategories.
b20ea669 1456 */
dc1f00de 1457function question_categorylist($categoryid) {
eb84a826 1458 global $DB;
1459
e80c64ab 1460 // final list of category IDs
0f76ac4f
TM
1461 $categorylist = array();
1462
e80c64ab
TM
1463 // a list of category IDs to check for any sub-categories
1464 $subcategories = array($categoryid);
0f76ac4f 1465
e80c64ab 1466 while ($subcategories) {
0f76ac4f 1467 foreach ($subcategories as $subcategory) {
e80c64ab
TM
1468 // if anything from the temporary list was added already, then we have a loop
1469 if (isset($categorylist[$subcategory])) {
1470 throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1471 }
1472 $categorylist[$subcategory] = $subcategory;
0f76ac4f
TM
1473 }
1474
e80c64ab
TM
1475 list ($in, $params) = $DB->get_in_or_equal($subcategories);
1476
1477 $subcategories = $DB->get_records_select_menu('question_categories',
1478 "parent $in", $params, NULL, 'id,id AS id2');
516cf3eb 1479 }
2daffca5 1480
516cf3eb 1481 return $categorylist;
1482}
1483
947217d7 1484//===========================
1485// Import/Export Functions
1486//===========================
1487
ff4b6492 1488/**
1489 * Get list of available import or export formats
1490 * @param string $type 'import' if import list, otherwise export list assumed
271ffe3f 1491 * @return array sorted list of import/export formats available
50fcb1d8 1492 */
f29aeb5a 1493function get_import_export_formats($type) {
ff4b6492 1494 global $CFG;
44a7f384 1495 require_once($CFG->dirroot . '/question/format.php');
f7c1dfaf 1496
059e08ed 1497 $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
ff4b6492 1498
f7c1dfaf 1499 $fileformatname = array();
44a7f384 1500 foreach ($formatclasses as $component => $formatclass) {
f29aeb5a 1501
44a7f384 1502 $format = new $formatclass();
f29aeb5a 1503 if ($type == 'import') {
44a7f384 1504 $provided = $format->provide_import();
f29aeb5a 1505 } else {
44a7f384 1506 $provided = $format->provide_export();
ff4b6492 1507 }
f29aeb5a 1508
ff4b6492 1509 if ($provided) {
44a7f384 1510 list($notused, $fileformat) = explode('_', $component, 2);
64679179 1511 $fileformatnames[$fileformat] = get_string('pluginname', $component);
ff4b6492 1512 }
1513 }
ff4b6492 1514
2f1e464a 1515 core_collator::asort($fileformatnames);
ff4b6492 1516 return $fileformatnames;
1517}
feb60a07 1518
1519
1520/**
aac80ff3
TH
1521 * Create a reasonable default file name for exporting questions from a particular
1522 * category.
1523 * @param object $course the course the questions are in.
1524 * @param object $category the question category.
1525 * @return string the filename.
1526 */
b80d424c
TH
1527function question_default_export_filename($course, $category) {
1528 // We build a string that is an appropriate name (questions) from the lang pack,
0ff4bd08 1529 // then the corse shortname, then the question category name, then a timestamp.
b80d424c
TH
1530
1531 $base = clean_filename(get_string('exportfilename', 'question'));
1532
1533 $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1534 $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1535
1536 $shortname = clean_filename($course->shortname);
1537 if ($shortname == '' || $shortname == '_' ) {
1538 $shortname = $course->id;
1539 }
1540
1541 $categoryname = clean_filename(format_string($category->name));
1542
1543 return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
feb60a07 1544
1545 return $export_name;
1546}
50fcb1d8 1547
1548/**
f29aeb5a
TH
1549 * Converts contextlevels to strings and back to help with reading/writing contexts
1550 * to/from import/export files.
1551 *
50fcb1d8 1552 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1554 */
3bee1ead 1555class context_to_string_translator{
1556 /**
1557 * @var array used to translate between contextids and strings for this context.
1558 */
f29aeb5a 1559 protected $contexttostringarray = array();
3bee1ead 1560
f29aeb5a 1561 public function __construct($contexts) {
3bee1ead 1562 $this->generate_context_to_string_array($contexts);
1563 }
1564
f29aeb5a 1565 public function context_to_string($contextid) {
3bee1ead 1566 return $this->contexttostringarray[$contextid];
1567 }
1568
f29aeb5a 1569 public function string_to_context($contextname) {
3bee1ead 1570 $contextid = array_search($contextname, $this->contexttostringarray);
1571 return $contextid;
1572 }
1573
f29aeb5a 1574 protected function generate_context_to_string_array($contexts) {
aac80ff3 1575 if (!$this->contexttostringarray) {
3bee1ead 1576 $catno = 1;
aac80ff3
TH
1577 foreach ($contexts as $context) {
1578 switch ($context->contextlevel) {
3bee1ead 1579 case CONTEXT_MODULE :
1580 $contextstring = 'module';
1581 break;
1582 case CONTEXT_COURSE :
1583 $contextstring = 'course';
1584 break;
1585 case CONTEXT_COURSECAT :
1586 $contextstring = "cat$catno";
1587 $catno++;
1588 break;
1589 case CONTEXT_SYSTEM :
1590 $contextstring = 'system';
1591 break;
1592 }
1593 $this->contexttostringarray[$context->id] = $contextstring;
1594 }
1595 }
1596 }
1597
1598}
feb60a07 1599
3bee1ead 1600/**
1601 * Check capability on category
50fcb1d8 1602 *
3bee1ead 1603 * @param mixed $question object or id
1604 * @param string $cap 'add', 'edit', 'view', 'use', 'move'
1605 * @param integer $cachecat useful to cache all question records in a category
1606 * @return boolean this user has the capability $cap for this question $question?
1607 */
aac80ff3 1608function question_has_capability_on($question, $cap, $cachecat = -1) {
eb84a826 1609 global $USER, $DB;
1610
3bee1ead 1611 // these are capabilities on existing questions capabilties are
1612 //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
1451c07e 1613 $question_questioncaps = array('edit', 'view', 'use', 'move', 'tag');
3bee1ead 1614 static $questions = array();
1615 static $categories = array();
1616 static $cachedcat = array();
9203b705 1617 if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
fe0fbfae 1618 $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
3bee1ead 1619 $cachedcat[] = $cachecat;
1620 }
aac80ff3
TH
1621 if (!is_object($question)) {
1622 if (!isset($questions[$question])) {
1623 if (!$questions[$question] = $DB->get_record('question',
1624 array('id' => $question), 'id,category,createdby')) {
0f6475b3 1625 print_error('questiondoesnotexist', 'question');
3bee1ead 1626 }
1627 }
1628 $question = $questions[$question];
1629 }
2a73f863
TH
1630 if (empty($question->category)) {
1631 // This can happen when we have created a fake 'missingtype' question to
1632 // take the place of a deleted question.
1633 return false;
1634 }
aac80ff3
TH
1635 if (!isset($categories[$question->category])) {
1636 if (!$categories[$question->category] = $DB->get_record('question_categories',
1637 array('id'=>$question->category))) {
7f7144fd 1638 print_error('invalidcategory', 'question');
3bee1ead 1639 }
1640 }
1641 $category = $categories[$question->category];
d197ea43 1642 $context = context::instance_by_id($category->contextid);
3bee1ead 1643
aac80ff3
TH
1644 if (array_search($cap, $question_questioncaps)!== false) {
1645 if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
1646 if ($question->createdby == $USER->id) {
1647 return has_capability('moodle/question:' . $cap . 'mine', $context);
3bee1ead 1648 } else {
1649 return false;
1650 }
1651 } else {
1652 return true;
1653 }
1654 } else {
aac80ff3 1655 return has_capability('moodle/question:' . $cap, $context);
3bee1ead 1656 }
1657
1658}
1659
1660/**
1661 * Require capability on question.
1662 */
aac80ff3
TH
1663function question_require_capability_on($question, $cap) {
1664 if (!question_has_capability_on($question, $cap)) {
3bee1ead 1665 print_error('nopermissions', '', '', $cap);
1666 }
1667 return true;
1668}
1669
62e76c67 1670/**
f29aeb5a
TH
1671 * @param object $context a context
1672 * @return string A URL for editing questions in this context.
f62040ed 1673 */
f29aeb5a
TH
1674function question_edit_url($context) {
1675 global $CFG, $SITE;
1676 if (!has_any_capability(question_get_question_capabilities(), $context)) {
1677 return false;
f62040ed 1678 }
f29aeb5a
TH
1679 $baseurl = $CFG->wwwroot . '/question/edit.php?';
1680 $defaultcategory = question_get_default_category($context->id);
1681 if ($defaultcategory) {
1682 $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
f62040ed 1683 }
f29aeb5a
TH
1684 switch ($context->contextlevel) {
1685 case CONTEXT_SYSTEM:
1686 return $baseurl . 'courseid=' . $SITE->id;
1687 case CONTEXT_COURSECAT:
1688 // This is nasty, becuase we can only edit questions in a course
1689 // context at the moment, so for now we just return false.
1690 return false;
1691 case CONTEXT_COURSE:
1692 return $baseurl . 'courseid=' . $context->instanceid;
1693 case CONTEXT_MODULE:
1694 return $baseurl . 'cmid=' . $context->instanceid;
62e76c67 1695 }
f29aeb5a 1696
62e76c67 1697}
56ed242b
SH
1698
1699/**
792881f0 1700 * Adds question bank setting links to the given navigation node if caps are met.
56ed242b
SH
1701 *
1702 * @param navigation_node $navigationnode The navigation node to add the question branch to
0ff4bd08 1703 * @param object $context
56ed242b
SH
1704 * @return navigation_node Returns the question branch that was added
1705 */
1706function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
1707 global $PAGE;
1708
1709 if ($context->contextlevel == CONTEXT_COURSE) {
1710 $params = array('courseid'=>$context->instanceid);
1711 } else if ($context->contextlevel == CONTEXT_MODULE) {
1712 $params = array('cmid'=>$context->instanceid);
1713 } else {
1714 return;
1715 }
1716
8356e6cf
TH
1717 if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1718 $params['cat'] = $cat;
1719 }
1720
aac80ff3 1721 $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
e6b2598b 1722 new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
56ed242b
SH
1723
1724 $contexts = new question_edit_contexts($context);
1725 if ($contexts->have_one_edit_tab_cap('questions')) {
e0c22222 1726 $questionnode->add(get_string('questions', 'question'), new moodle_url(
e6b2598b 1727 '/question/edit.php', $params), navigation_node::TYPE_SETTING, null, 'questions');
56ed242b
SH
1728 }
1729 if ($contexts->have_one_edit_tab_cap('categories')) {
e0c22222 1730 $questionnode->add(get_string('categories', 'question'), new moodle_url(
e6b2598b 1731 '/question/category.php', $params), navigation_node::TYPE_SETTING, null, 'categories');
56ed242b
SH
1732 }
1733 if ($contexts->have_one_edit_tab_cap('import')) {
e0c22222 1734 $questionnode->add(get_string('import', 'question'), new moodle_url(
e6b2598b 1735 '/question/import.php', $params), navigation_node::TYPE_SETTING, null, 'import');
56ed242b
SH
1736 }
1737 if ($contexts->have_one_edit_tab_cap('export')) {
e0c22222 1738 $questionnode->add(get_string('export', 'question'), new moodle_url(
e6b2598b 1739 '/question/export.php', $params), navigation_node::TYPE_SETTING, null, 'export');
56ed242b
SH
1740 }
1741
1742 return $questionnode;
1743}
1744
f29aeb5a
TH
1745/**
1746 * @return array all the capabilities that relate to accessing particular questions.
1747 */
1748function question_get_question_capabilities() {
1749 return array(
1750 'moodle/question:add',
1751 'moodle/question:editmine',
1752 'moodle/question:editall',
1753 'moodle/question:viewmine',
1754 'moodle/question:viewall',
1755 'moodle/question:usemine',
1756 'moodle/question:useall',
1757 'moodle/question:movemine',
1758 'moodle/question:moveall',
1759 );
1760}
1761
1762/**
1763 * @return array all the question bank capabilities.
1764 */
1765function question_get_all_capabilities() {
1766 $caps = question_get_question_capabilities();
1767 $caps[] = 'moodle/question:managecategory';
1768 $caps[] = 'moodle/question:flag';
1769 return $caps;
1770}
1771
6f4c71f5
TH
1772
1773/**
1774 * Tracks all the contexts related to the one where we are currently editing
1775 * questions, and provides helper methods to check permissions.
1776 *
1777 * @copyright 2007 Jamie Pratt me@jamiep.org
1778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1779 */
56ed242b
SH
1780class question_edit_contexts {
1781
aac80ff3 1782 public static $caps = array(
56ed242b
SH
1783 'editq' => array('moodle/question:add',
1784 'moodle/question:editmine',
1785 'moodle/question:editall',
1786 'moodle/question:viewmine',
1787 'moodle/question:viewall',
1788 'moodle/question:usemine',
1789 'moodle/question:useall',
1790 'moodle/question:movemine',
1791 'moodle/question:moveall'),
1792 'questions'=>array('moodle/question:add',
1793 'moodle/question:editmine',
1794 'moodle/question:editall',
1795 'moodle/question:viewmine',
1796 'moodle/question:viewall',
1797 'moodle/question:movemine',
1798 'moodle/question:moveall'),
1799 'categories'=>array('moodle/question:managecategory'),
1800 'import'=>array('moodle/question:add'),
1801 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
1802
1803 protected $allcontexts;
1804
1805 /**
6f4c71f5
TH
1806 * Constructor
1807 * @param context the current context.
56ed242b 1808 */
6f4c71f5
TH
1809 public function __construct(context $thiscontext) {
1810 $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
56ed242b 1811 }
6f4c71f5 1812
56ed242b
SH
1813 /**
1814 * @return array all parent contexts
1815 */
f29aeb5a 1816 public function all() {
56ed242b
SH
1817 return $this->allcontexts;
1818 }
6f4c71f5 1819
56ed242b
SH
1820 /**
1821 * @return object lowest context which must be either the module or course context
1822 */
f29aeb5a 1823 public function lowest() {
56ed242b
SH
1824 return $this->allcontexts[0];
1825 }
6f4c71f5 1826
56ed242b
SH
1827 /**
1828 * @param string $cap capability
1829 * @return array parent contexts having capability, zero based index
1830 */
f29aeb5a 1831 public function having_cap($cap) {
56ed242b 1832 $contextswithcap = array();
aac80ff3
TH
1833 foreach ($this->allcontexts as $context) {
1834 if (has_capability($cap, $context)) {
56ed242b
SH
1835 $contextswithcap[] = $context;
1836 }
1837 }
1838 return $contextswithcap;
1839 }
6f4c71f5 1840
56ed242b
SH
1841 /**
1842 * @param array $caps capabilities
1843 * @return array parent contexts having at least one of $caps, zero based index
1844 */
f29aeb5a 1845 public function having_one_cap($caps) {
56ed242b 1846 $contextswithacap = array();
aac80ff3
TH
1847 foreach ($this->allcontexts as $context) {
1848 foreach ($caps as $cap) {
1849 if (has_capability($cap, $context)) {
56ed242b
SH
1850 $contextswithacap[] = $context;
1851 break; //done with caps loop
1852 }
1853 }
1854 }
1855 return $contextswithacap;
1856 }
6f4c71f5 1857
56ed242b
SH
1858 /**
1859 * @param string $tabname edit tab name
1860 * @return array parent contexts having at least one of $caps, zero based index
1861 */
f29aeb5a 1862 public function having_one_edit_tab_cap($tabname) {
aac80ff3 1863 return $this->having_one_cap(self::$caps[$tabname]);
56ed242b 1864 }
6f4c71f5 1865
76cf77e4
TH
1866 /**
1867 * @return those contexts where a user can add a question and then use it.
1868 */
1869 public function having_add_and_use() {
1870 $contextswithcap = array();
1871 foreach ($this->allcontexts as $context) {
1872 if (!has_capability('moodle/question:add', $context)) {
1873 continue;
1874 }
1875 if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
1876 continue;
1877 }
1878 $contextswithcap[] = $context;
1879 }
1880 return $contextswithcap;
1881 }
1882
56ed242b
SH
1883 /**
1884 * Has at least one parent context got the cap $cap?
1885 *
1886 * @param string $cap capability
1887 * @return boolean
1888 */
f29aeb5a 1889 public function have_cap($cap) {
56ed242b
SH
1890 return (count($this->having_cap($cap)));
1891 }
1892
1893 /**
1894 * Has at least one parent context got one of the caps $caps?
1895 *
1896 * @param array $caps capability
1897 * @return boolean
1898 */
f29aeb5a 1899 public function have_one_cap($caps) {
56ed242b
SH
1900 foreach ($caps as $cap) {
1901 if ($this->have_cap($cap)) {
1902 return true;
1903 }
1904 }
1905 return false;
1906 }
f29aeb5a 1907
56ed242b
SH
1908 /**
1909 * Has at least one parent context got one of the caps for actions on $tabname
1910 *
1911 * @param string $tabname edit tab name
1912 * @return boolean
1913 */
aac80ff3
TH
1914 public function have_one_edit_tab_cap($tabname) {
1915 return $this->have_one_cap(self::$caps[$tabname]);
56ed242b 1916 }
f29aeb5a 1917
56ed242b
SH
1918 /**
1919 * Throw error if at least one parent context hasn't got the cap $cap
1920 *
1921 * @param string $cap capability
1922 */
aac80ff3
TH
1923 public function require_cap($cap) {
1924 if (!$this->have_cap($cap)) {
56ed242b
SH
1925 print_error('nopermissions', '', '', $cap);
1926 }
1927 }
f29aeb5a 1928
56ed242b
SH
1929 /**
1930 * Throw error if at least one parent context hasn't got one of the caps $caps
1931 *
1932 * @param array $cap capabilities
1933 */
aac80ff3 1934 public function require_one_cap($caps) {
56ed242b
SH
1935 if (!$this->have_one_cap($caps)) {
1936 $capsstring = join($caps, ', ');
1937 print_error('nopermissions', '', '', $capsstring);
1938 }
1939 }
1940
1941 /**
1942 * Throw error if at least one parent context hasn't got one of the caps $caps
1943 *
1944 * @param string $tabname edit tab name
1945 */
aac80ff3 1946 public function require_one_edit_tab_cap($tabname) {
56ed242b
SH
1947 if (!$this->have_one_edit_tab_cap($tabname)) {
1948 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1949 }
1950 }
fe6ce234
DC
1951}
1952
6f4c71f5 1953
fe6ce234 1954/**
fdb5bc03 1955 * Helps call file_rewrite_pluginfile_urls with the right parameters.
fe6ce234 1956 *
d2b7803e
DC
1957 * @package core_question
1958 * @category files
fe6ce234
DC
1959 * @param string $text text being processed
1960 * @param string $file the php script used to serve files
d2b7803e 1961 * @param int $contextid context ID
fe6ce234
DC
1962 * @param string $component component
1963 * @param string $filearea filearea
1964 * @param array $ids other IDs will be used to check file permission
d2b7803e
DC
1965 * @param int $itemid item ID
1966 * @param array $options options
fe6ce234
DC
1967 * @return string
1968 */
aac80ff3
TH
1969function question_rewrite_question_urls($text, $file, $contextid, $component,
1970 $filearea, array $ids, $itemid, array $options=null) {
fe6ce234 1971
fdb5bc03
TH
1972 $idsstr = '';
1973 if (!empty($ids)) {
1974 $idsstr .= implode('/', $ids);
fe6ce234 1975 }
fdb5bc03
TH
1976 if ($itemid !== null) {
1977 $idsstr .= '/' . $itemid;
fe6ce234 1978 }
fdb5bc03
TH
1979 return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1980 $filearea, $idsstr, $options);
1981}
fe6ce234 1982
181393aa
TH
1983/**
1984 * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1985 * viewing the question outside an attempt (for example, in the question bank
1986 * listing or in the quiz statistics report).
1987 *
1988 * @param string $text the question text.
1989 * @param int $questionid the question id.
1990 * @param int $filecontextid the context id of the question being displayed.
1991 * @param string $filecomponent the component that owns the file area.
1992 * @param string $filearea the file area name.
1993 * @param int|null $itemid the file's itemid
1994 * @param int $previewcontextid the context id where the preview is being displayed.
1995 * @param string $previewcomponent component responsible for displaying the preview.
1996 * @param array $options text and file options ('forcehttps'=>false)
1997 * @return string $questiontext with URLs rewritten.
1998 */
1999function question_rewrite_question_preview_urls($text, $questionid,
2000 $filecontextid, $filecomponent, $filearea, $itemid,
2001 $previewcontextid, $previewcomponent, $options = null) {
fe6ce234 2002
181393aa
TH
2003 $path = "preview/$previewcontextid/$previewcomponent/$questionid";
2004 if ($itemid) {
2005 $path .= '/' . $itemid;
2006 }
2007
2008 return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
2009 $filecomponent, $filearea, $path, $options);
fdb5bc03 2010}
fe6ce234 2011
fe6ce234
DC
2012/**
2013 * Called by pluginfile.php to serve files related to the 'question' core
2014 * component and for files belonging to qtypes.
2015 *
2016 * For files that relate to questions in a question_attempt, then we delegate to
2017 * a function in the component that owns the attempt (for example in the quiz,
2018 * or in core question preview) to get necessary inforation.
2019 *
2020 * (Note that, at the moment, all question file areas relate to questions in
2021 * attempts, so the If at the start of the last paragraph is always true.)
2022 *
2023 * Does not return, either calls send_file_not_found(); or serves the file.
2024 *
d2b7803e
DC
2025 * @package core_question
2026 * @category files
2027 * @param stdClass $course course settings object
2028 * @param stdClass $context context object
fe6ce234
DC
2029 * @param string $component the name of the component we are serving files for.
2030 * @param string $filearea the name of the file area.
2031 * @param array $args the remaining bits of the file path.
2032 * @param bool $forcedownload whether the user must be forced to download the file.
7a00d438 2033 * @param array $options additional options affecting the file serving
fe6ce234 2034 */
7a00d438 2035function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
fe6ce234
DC
2036 global $DB, $CFG;
2037
181393aa 2038 // Special case, sending a question bank export.
cde2709a 2039 if ($filearea === 'export') {
97f1137a
TH
2040 list($context, $course, $cm) = get_context_info_array($context->id);
2041 require_login($course, false, $cm);
2042
cde2709a
DC
2043 require_once($CFG->dirroot . '/question/editlib.php');
2044 $contexts = new question_edit_contexts($context);
2045 // check export capability
2046 $contexts->require_one_edit_tab_cap('export');
2047 $category_id = (int)array_shift($args);
2048 $format = array_shift($args);
2049 $cattofile = array_shift($args);
2050 $contexttofile = array_shift($args);
2051 $filename = array_shift($args);
2052
2053 // load parent class for import/export
2054 require_once($CFG->dirroot . '/question/format.php');
2055 require_once($CFG->dirroot . '/question/editlib.php');
2056 require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
2057
2058 $classname = 'qformat_' . $format;
2059 if (!class_exists($classname)) {
2060 send_file_not_found();
2061 }
2062
2063 $qformat = new $classname();
2064
2065 if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
2066 send_file_not_found();
2067 }
2068
2069 $qformat->setCategory($category);
2070 $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
2071 $qformat->setCourse($course);
2072
2073 if ($cattofile == 'withcategories') {
2074 $qformat->setCattofile(true);
2075 } else {
2076 $qformat->setCattofile(false);
2077 }
2078
2079 if ($contexttofile == 'withcontexts') {
2080 $qformat->setContexttofile(true);
2081 } else {
2082 $qformat->setContexttofile(false);
2083 }
2084
2085 if (!$qformat->exportpreprocess()) {
2086 send_file_not_found();
2087 print_error('exporterror', 'question', $thispageurl->out());
2088 }
2089
2090 // export data to moodle file pool
2091 if (!$content = $qformat->exportprocess(true)) {
2092 send_file_not_found();
2093 }
2094
46732124 2095 send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
cde2709a
DC
2096 }
2097
181393aa
TH
2098 // Normal case, a file belonging to a question.
2099 $qubaidorpreview = array_shift($args);
2100
2101 // Two sub-cases: 1. A question being previewed outside an attempt/usage.
2102 if ($qubaidorpreview === 'preview') {
2103 $previewcontextid = (int)array_shift($args);
2104 $previewcomponent = array_shift($args);
2105 $questionid = (int) array_shift($args);
2106 $previewcontext = context_helper::instance_by_id($previewcontextid);
2107
2108 $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
2109 $previewcontext, $questionid,
2110 $context, $component, $filearea, $args,
1b49f31d
TH
2111 $forcedownload, $options), 'callbackmissing');
2112
2113 if ($result === 'callbackmissing') {
2114 throw new coding_exception("Component {$previewcomponent} does not define the callback " .
2115 "{$previewcomponent}_question_preview_pluginfile callback. " .
2116 "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
181393aa
TH
2117 }
2118
2119 send_file_not_found();
2120 }
2121
2122 // 2. A question being attempted in the normal way.
2123 $qubaid = (int)$qubaidorpreview;
7a719748 2124 $slot = (int)array_shift($args);
fe6ce234 2125
7a719748
TH
2126 $module = $DB->get_field('question_usages', 'component',
2127 array('id' => $qubaid));
9c75f8dc
TH
2128 if (!$module) {
2129 send_file_not_found();
2130 }
fe6ce234 2131
7a719748 2132 if ($module === 'core_question_preview') {
fe6ce234
DC
2133 require_once($CFG->dirroot . '/question/previewlib.php');
2134 return question_preview_question_pluginfile($course, $context,
7a00d438 2135 $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
fe6ce234
DC
2136
2137 } else {
b0d1d941 2138 $dir = core_component::get_component_directory($module);
fe6ce234
DC
2139 if (!file_exists("$dir/lib.php")) {
2140 send_file_not_found();
2141 }
2142 include_once("$dir/lib.php");
2143
2144 $filefunction = $module . '_question_pluginfile';
0dd0f963
AB
2145 if (function_exists($filefunction)) {
2146 $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
2147 $args, $forcedownload, $options);
fe6ce234
DC
2148 }
2149
813f6964
DP
2150 // Okay, we're here so lets check for function without 'mod_'.
2151 if (strpos($module, 'mod_') === 0) {
38d488ce 2152 $filefunctionold = substr($module, 4) . '_question_pluginfile';
0dd0f963
AB
2153 if (function_exists($filefunctionold)) {
2154 $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
2155 $args, $forcedownload, $options);
2156 }
2157 }
fe6ce234
DC
2158
2159 send_file_not_found();
2160 }
2161}
2162
0019a9b7
TH
2163/**
2164 * Serve questiontext files in the question text when they are displayed in this report.
d2b7803e
DC
2165 *
2166 * @package core_files
2167 * @category files
68d2f6a0
TH
2168 * @param context $previewcontext the context in which the preview is happening.
2169 * @param int $questionid the question id.
2170 * @param context $filecontext the file (question) context.
2171 * @param string $filecomponent the component the file belongs to.
2172 * @param string $filearea the file area.
2173 * @param array $args remaining file args.
2174 * @param bool $forcedownload.
2175 * @param array $options additional options affecting the file serving.
0019a9b7 2176 */
68d2f6a0
TH
2177function core_question_question_preview_pluginfile($previewcontext, $questionid,
2178 $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
0019a9b7
TH
2179 global $DB;
2180
2181 // Verify that contextid matches the question.
2182 $question = $DB->get_record_sql('
2183 SELECT q.*, qc.contextid
2184 FROM {question} q
2185 JOIN {question_categories} qc ON qc.id = q.category
2186 WHERE q.id = :id AND qc.contextid = :contextid',
68d2f6a0 2187 array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
0019a9b7
TH
2188
2189 // Check the capability.
68d2f6a0 2190 list($context, $course, $cm) = get_context_info_array($previewcontext->id);
0019a9b7
TH
2191 require_login($course, false, $cm);
2192
2193 question_require_capability_on($question, 'use');
2194
68d2f6a0
TH
2195 $fs = get_file_storage();
2196 $relativepath = implode('/', $args);
2197 $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
2198 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2199 send_file_not_found();
2200 }
2201
2202 send_stored_file($file, 0, 0, $forcedownload, $options);
0019a9b7
TH
2203}
2204
cde2709a
DC
2205/**
2206 * Create url for question export
2207 *
2208 * @param int $contextid, current context
2209 * @param int $categoryid, categoryid
2210 * @param string $format
2211 * @param string $withcategories
2212 * @param string $ithcontexts
2213 * @param moodle_url export file url
2214 */
aac80ff3
TH
2215function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2216 $withcontexts, $filename) {
cde2709a 2217 global $CFG;
672f4836 2218 $urlbase = "$CFG->wwwroot/pluginfile.php";
aac80ff3
TH
2219 return moodle_url::make_file_url($urlbase,
2220 "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
2221 "/{$withcontexts}/{$filename}", true);
cde2709a 2222}
b1627a92
DC
2223
2224/**
2225 * Return a list of page types
2226 * @param string $pagetype current page type
2227 * @param stdClass $parentcontext Block's parent context
2228 * @param stdClass $currentcontext Current context of block
2229 */
b38e2e28 2230function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
2231 global $CFG;
2232 $types = array(
2233 'question-*'=>get_string('page-question-x', 'question'),
2234 'question-edit'=>get_string('page-question-edit', 'question'),
2235 'question-category'=>get_string('page-question-category', 'question'),
2236 'question-export'=>get_string('page-question-export', 'question'),
2237 'question-import'=>get_string('page-question-import', 'question')
2238 );
2239 if ($currentcontext->contextlevel == CONTEXT_COURSE) {
2240 require_once($CFG->dirroot . '/course/lib.php');
b38e2e28 2241 return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
b1627a92
DC
2242 } else {
2243 return $types;
2244 }
2245}
b07ef13b
DP
2246
2247/**
2248 * Does an activity module use the question bank?
2249 *
2250 * @param string $modname The name of the module (without mod_ prefix).
2251 * @return bool true if the module uses questions.
2252 */
2253function question_module_uses_questions($modname) {
2254 if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
2255 return true;
2256 }
2257
2258 $component = 'mod_'.$modname;
2259 if (component_callback_exists($component, 'question_pluginfile')) {
2260 debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
2261 return true;
2262 }
2263
2264 return false;
2265}