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