MDL-66796 question bank: 0 is a valid question category idnumber
[moodle.git] / question / category_class.php
CommitLineData
aeb15530 1<?php
d3603157
TH
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
17/**
18 * A class for representing question categories.
19 *
20 * @package moodlecore
21 * @subpackage questionbank
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
516cf3eb 26
a17b297d
TH
27defined('MOODLE_INTERNAL') || die();
28
516cf3eb 29// number of categories to display on page
d3603157 30define('QUESTION_PAGE_LENGTH', 25);
dac786f3 31
94dbfb3a
TH
32require_once($CFG->libdir . '/listlib.php');
33require_once($CFG->dirroot . '/question/category_form.php');
017bc1d9
TH
34require_once($CFG->dirroot . '/question/move_form.php');
35
dac786f3 36
017bc1d9
TH
37/**
38 * Class representing a list of question categories
39 *
40 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 */
dac786f3 43class question_category_list extends moodle_list {
f34488b2 44 public $table = "question_categories";
45 public $listitemclassname = 'question_category_list_item';
271e6dec 46 /**
47 * @var reference to list displayed below this one.
48 */
f34488b2 49 public $nextlist = null;
271e6dec 50 /**
51 * @var reference to list displayed above this one.
52 */
f34488b2 53 public $lastlist = null;
271e6dec 54
f34488b2 55 public $context = null;
c65921d4 56 public $sortby = 'parent, sortorder, name';
271e6dec 57
20d89122
TH
58 public function __construct($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){
59 parent::__construct('ul', '', $editable, $pageurl, $page, 'cpage', $itemsperpage);
271e6dec 60 $this->context = $context;
61 }
986effb6 62
f34488b2 63 public function get_records() {
271e6dec 64 $this->records = get_categories_for_contexts($this->context->id, $this->sortby);
65 }
18d6ff78
SR
66
67 /**
68 * Returns the highest category id that the $item can have as its parent.
69 * Note: question categories cannot go higher than the TOP category.
70 *
71 * @param list_item $item The item which its top level parent is going to be returned.
72 * @return int
73 */
74 public function get_top_level_parent_id($item) {
75 // Put the item at the highest level it can go.
76 $topcategory = question_get_top_category($item->item->contextid, true);
77 return $topcategory->id;
78 }
93e435b9 79
4ca60a56
V
80 /**
81 * process any actions.
82 *
83 * @param integer $left id of item to move left
84 * @param integer $right id of item to move right
85 * @param integer $moveup id of item to move up
86 * @param integer $movedown id of item to move down
87 * @return void
88 * @throws coding_exception
89 */
93e435b9 90 public function process_actions($left, $right, $moveup, $movedown) {
4ca60a56 91 $category = new stdClass();
93e435b9
SB
92 if (!empty($left)) {
93 // Moved Left (In to another category).
4ca60a56
V
94 $category->id = $left;
95 $category->contextid = $this->context->id;
96 $event = \core\event\question_category_moved::create_from_question_category_instance($category);
93e435b9
SB
97 $event->trigger();
98 } else if (!empty($right)) {
99 // Moved Right (Out of the current category).
4ca60a56
V
100 $category->id = $right;
101 $category->contextid = $this->context->id;
102 $event = \core\event\question_category_moved::create_from_question_category_instance($category);
93e435b9 103 $event->trigger();
4ca60a56 104 }
93e435b9
SB
105 parent::process_actions($left, $right, $moveup, $movedown);
106 }
dac786f3 107}
108
017bc1d9
TH
109/**
110 * An item in a list of question categories.
111 *
112 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
113 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
114 */
dac786f3 115class question_category_list_item extends list_item {
e2bb3c92 116 public function set_icon_html($first, $last, $lastitem){
271e6dec 117 global $CFG;
118 $category = $this->item;
8afba50b
PS
119 $url = new moodle_url('/question/category.php', ($this->parentlist->pageurl->params() + array('edit'=>$category->id)));
120 $this->icons['edit']= $this->image_icon(get_string('editthiscategory', 'question'), $url, 'edit');
271e6dec 121 parent::set_icon_html($first, $last, $lastitem);
122 $toplevel = ($this->parentlist->parentitem === null);//this is a top level item
123 if (($this->parentlist->nextlist !== null) && $last && $toplevel && (count($this->parentlist->items)>1)){
8afba50b 124 $url = new moodle_url($this->parentlist->pageurl, array('movedowncontext'=>$this->id, 'tocontext'=>$this->parentlist->nextlist->context->id, 'sesskey'=>sesskey()));
f34488b2 125 $this->icons['down'] = $this->image_icon(
329846f1 126 get_string('shareincontext', 'question', $this->parentlist->nextlist->context->get_context_name()), $url, 'down');
271e6dec 127 }
128 if (($this->parentlist->lastlist !== null) && $first && $toplevel && (count($this->parentlist->items)>1)){
8afba50b 129 $url = new moodle_url($this->parentlist->pageurl, array('moveupcontext'=>$this->id, 'tocontext'=>$this->parentlist->lastlist->context->id, 'sesskey'=>sesskey()));
f34488b2 130 $this->icons['up'] = $this->image_icon(
329846f1 131 get_string('shareincontext', 'question', $this->parentlist->lastlist->context->get_context_name()), $url, 'up');
271e6dec 132 }
133 }
20d89122 134
f34488b2 135 public function item_html($extraargs = array()){
42d5737a 136 global $CFG, $OUTPUT;
dac786f3 137 $str = $extraargs['str'];
138 $category = $this->item;
139
5e8a85aa 140 $editqestions = get_string('editquestions', 'question');
dac786f3 141
8009810e
TH
142 // Each section adds html to be displayed as part of this list item.
143 $questionbankurl = new moodle_url('/question/edit.php', $this->parentlist->pageurl->params());
144 $questionbankurl->param('cat', $category->id . ',' . $category->contextid);
8009810e 145 $item = '';
2ea8fbb0
V
146 $text = format_string($category->name, true, ['context' => $this->parentlist->context])
147 . ' (' . $category->questioncount . ')';
148 $item .= html_writer::tag('b', html_writer::link($questionbankurl, $text,
149 ['title' => $editqestions]) . ' ');
8009810e 150 $item .= format_text($category->info, $category->infoformat,
fc51c2bc 151 array('context' => $this->parentlist->context, 'noclean' => true));
dac786f3 152
9275220d
SR
153 // Don't allow delete if this is the top category, or the last editable category in this context.
154 if ($category->parent && !question_is_only_child_of_top_category_in_context($category->id)) {
8009810e
TH
155 $deleteurl = new moodle_url($this->parentlist->pageurl, array('delete' => $this->id, 'sesskey' => sesskey()));
156 $item .= html_writer::link($deleteurl,
663640f5 157 $OUTPUT->pix_icon('t/delete', $str->delete),
8009810e 158 array('title' => $str->delete));
dac786f3 159 }
160
161 return $item;
dac786f3 162 }
dac786f3 163}
164
516cf3eb 165
4323d029 166/**
017bc1d9 167 * Class representing q question category
dac786f3 168 *
017bc1d9
TH
169 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
170 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4323d029 171 */
dc1f00de 172class question_category_object {
516cf3eb 173
dac786f3 174 /**
fa5c608c 175 * @var array common language strings.
dac786f3 176 */
fa5c608c
TH
177 public $str;
178
179 /**
180 * @var array nested lists to display categories.
181 */
182 public $editlists = array();
183 public $newtable;
184 public $tab;
185 public $tabsize = 3;
017bc1d9 186
986effb6 187 /**
188 * @var moodle_url Object representing url for this page
189 */
fa5c608c
TH
190 public $pageurl;
191
271e6dec 192 /**
193 * @var question_category_edit_form Object representing form for adding / editing categories.
194 */
fa5c608c 195 public $catform;
516cf3eb 196
bc649d80 197 /**
198 * Constructor
199 *
200 * Gets necessary strings and sets relevant path information
201 */
c4d0b752 202 public function __construct($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
a5cb8d69 203 global $CFG, $COURSE, $OUTPUT;
516cf3eb 204
205 $this->tab = str_repeat('&nbsp;', $this->tabsize);
206
e2bb3c92 207 $this->str = new stdClass();
516cf3eb 208 $this->str->course = get_string('course');
5e8a85aa
TH
209 $this->str->category = get_string('category', 'question');
210 $this->str->categoryinfo = get_string('categoryinfo', 'question');
211 $this->str->questions = get_string('questions', 'question');
516cf3eb 212 $this->str->add = get_string('add');
213 $this->str->delete = get_string('delete');
214 $this->str->moveup = get_string('moveup');
215 $this->str->movedown = get_string('movedown');
85edde5c 216 $this->str->edit = get_string('editthiscategory', 'question');
516cf3eb 217 $this->str->hide = get_string('hide');
516cf3eb 218 $this->str->order = get_string('order');
5e8a85aa 219 $this->str->parent = get_string('parent', 'question');
516cf3eb 220 $this->str->add = get_string('add');
221 $this->str->action = get_string('action');
5e8a85aa
TH
222 $this->str->top = get_string('top');
223 $this->str->addcategory = get_string('addcategory', 'question');
224 $this->str->editcategory = get_string('editcategory', 'question');
516cf3eb 225 $this->str->cancel = get_string('cancel');
5e8a85aa 226 $this->str->editcategories = get_string('editcategories', 'question');
2befe778 227 $this->str->page = get_string('page');
516cf3eb 228
986effb6 229 $this->pageurl = $pageurl;
271e6dec 230
231 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
516cf3eb 232 }
271e6dec 233
9e313e79
DM
234 /**
235 * Old syntax of class constructor. Deprecated in PHP7.
236 *
237 * @deprecated since Moodle 3.1
238 */
239 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
240 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
241 self::__construct($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
242 }
243
271e6dec 244 /**
245 * Initializes this classes general category-related variables
246 */
f34488b2 247 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
271e6dec 248 $lastlist = null;
249 foreach ($contexts as $context){
250 $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context);
251 $this->editlists[$context->id]->lastlist =& $lastlist;
252 if ($lastlist!== null){
253 $lastlist->nextlist =& $this->editlists[$context->id];
254 }
255 $lastlist =& $this->editlists[$context->id];
256 }
257
258 $count = 1;
259 $paged = false;
260 foreach ($this->editlists as $key => $list){
20f500dc 261 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
271e6dec 262 }
263 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
264 if (!$currentcat){
265 $this->catform->set_data(array('parent'=>$defaultcategory));
266 }
267 }
017bc1d9 268
bc649d80 269 /**
270 * Displays the user interface
271 *
bc649d80 272 */
f34488b2 273 public function display_user_interface() {
dac786f3 274
275 /// Interface for editing existing categories
271e6dec 276 $this->output_edit_lists();
dac786f3 277
516cf3eb 278
dac786f3 279 echo '<br />';
516cf3eb 280 /// Interface for adding a new category:
516cf3eb 281 $this->output_new_table();
282 echo '<br />';
283
516cf3eb 284 }
285
bc649d80 286 /**
287 * Outputs a table to allow entry of a new category
288 */
f34488b2 289 public function output_new_table() {
271e6dec 290 $this->catform->display();
516cf3eb 291 }
292
bc649d80 293 /**
dac786f3 294 * Outputs a list to allow editing/rearranging of existing categories
bc649d80 295 *
296 * $this->initialize() must have already been called
297 *
bc649d80 298 */
f34488b2 299 public function output_edit_lists() {
723d610c 300 global $OUTPUT;
1d58b567 301
5fcefc97 302 echo $OUTPUT->heading_with_help(get_string('editcategories', 'question'), 'editcategories', 'question');
1d58b567 303
271e6dec 304 foreach ($this->editlists as $context => $list){
305 $listhtml = $list->to_html(0, array('str'=>$this->str));
306 if ($listhtml){
beb677cd 307 echo $OUTPUT->box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
329846f1
AG
308 $fullcontext = context::instance_by_id($context);
309 echo $OUTPUT->heading(get_string('questioncatsfor', 'question', $fullcontext->get_context_name()), 3);
271e6dec 310 echo $listhtml;
beb677cd 311 echo $OUTPUT->box_end();
271e6dec 312 }
313 }
314 echo $list->display_page_numbers();
315 }
516cf3eb 316
bc649d80 317 /**
318 * gets all the courseids for the given categories
319 *
320 * @param array categories contains category objects in a tree representation
321 * @return array courseids flat array in form categoryid=>courseid
322 */
f34488b2 323 public function get_course_ids($categories) {
516cf3eb 324 $courseids = array();
325 foreach ($categories as $key=>$cat) {
326 $courseids[$key] = $cat->course;
327 if (!empty($cat->children)) {
328 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
329 }
330 }
331 return $courseids;
332 }
333
f34488b2 334 public function edit_single_category($categoryid) {
516cf3eb 335 /// Interface for adding a new category
9275220d 336 global $DB;
516cf3eb 337 /// Interface for editing existing categories
9275220d
SR
338 $category = $DB->get_record("question_categories", array("id" => $categoryid));
339 if (empty($category)) {
340 print_error('invalidcategory', '', '', $categoryid);
341 } else if ($category->parent == 0) {
342 print_error('cannotedittopcat', 'question', '', $categoryid);
343 } else {
f4fe3968 344 $category->parent = "{$category->parent},{$category->contextid}";
271e6dec 345 $category->submitbutton = get_string('savechanges');
346 $category->categoryheader = $this->str->edit;
347 $this->catform->set_data($category);
348 $this->catform->display();
516cf3eb 349 }
516cf3eb 350 }
351
bc649d80 352 /**
353 * Sets the viable parents
354 *
355 * Viable parents are any except for the category itself, or any of it's descendants
356 * The parentstrings parameter is passed by reference and changed by this function.
357 *
358 * @param array parentstrings a list of parentstrings
359 * @param object category
360 */
f34488b2 361 public function set_viable_parents(&$parentstrings, $category) {
516cf3eb 362
363 unset($parentstrings[$category->id]);
364 if (isset($category->children)) {
365 foreach ($category->children as $child) {
366 $this->set_viable_parents($parentstrings, $child);
367 }
368 }
369 }
370
bc649d80 371 /**
372 * Gets question categories
373 *
374 * @param int parent - if given, restrict records to those with this parent id.
375 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
376 * @return array categories
377 */
f34488b2 378 public function get_question_categories($parent=null, $sort="sortorder ASC") {
379 global $COURSE, $DB;
516cf3eb 380 if (is_null($parent)) {
f34488b2 381 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort);
516cf3eb 382 } else {
f34488b2 383 $select = "parent = ? AND course = ?";
384 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort);
516cf3eb 385 }
386 return $categories;
387 }
388
bc649d80 389 /**
390 * Deletes an existing question category
391 *
21cbf9da 392 * @param int deletecat id of category to delete
bc649d80 393 */
f34488b2 394 public function delete_category($categoryid) {
395 global $CFG, $DB;
271e6dec 396 question_can_delete_cat($categoryid);
f34488b2 397 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
64e71d27 398 print_error('unknowcategory');
516cf3eb 399 }
516cf3eb 400 /// Send the children categories to live with their grandparent
bb4b6010 401 $DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id));
516cf3eb 402
403 /// Finally delete the category itself
21cbf9da 404 $DB->delete_records("question_categories", array("id" => $category->id));
93e435b9
SB
405
406 // Log the deletion of this category.
4ca60a56
V
407 $event = \core\event\question_category_deleted::create_from_question_category_instance($category);
408 $event->add_record_snapshot('question_categories', $category);
93e435b9
SB
409 $event->trigger();
410
516cf3eb 411 }
21cbf9da 412
f34488b2 413 public function move_questions_and_delete_category($oldcat, $newcat){
271e6dec 414 question_can_delete_cat($oldcat);
415 $this->move_questions($oldcat, $newcat);
416 $this->delete_category($oldcat);
417 }
516cf3eb 418
f34488b2 419 public function display_move_form($questionsincategory, $category){
beb677cd 420 global $OUTPUT;
0ff4bd08 421 $vars = new stdClass();
271e6dec 422 $vars->name = $category->name;
423 $vars->count = $questionsincategory;
5e8a85aa 424 echo $OUTPUT->box(get_string('categorymove', 'question', $vars), 'generalbox boxaligncenter');
271e6dec 425 $this->moveform->display();
426 }
516cf3eb 427
f34488b2 428 public function move_questions($oldcat, $newcat){
534792cd 429 global $DB;
5d548d3e
TH
430 $questionids = $DB->get_records_select_menu('question',
431 'category = ? AND (parent = 0 OR parent = id)', array($oldcat), '', 'id,1');
9d0ac0ff 432 question_move_questions_to_category(array_keys($questionids), $newcat);
516cf3eb 433 }
434
bc649d80 435 /**
436 * Creates a new category with given params
bc649d80 437 */
6189fda4
JB
438 public function add_category($newparent, $newcategory, $newinfo, $return = false, $newinfoformat = FORMAT_HTML,
439 $idnumber = null) {
f34488b2 440 global $DB;
bc649d80 441 if (empty($newcategory)) {
5e8a85aa 442 print_error('categorynamecantbeblank', 'question');
bc649d80 443 }
271e6dec 444 list($parentid, $contextid) = explode(',', $newparent);
445 //moodle_form makes sure select element output is legal no need for further cleaning
d197ea43 446 require_capability('moodle/question:managecategory', context::instance_by_id($contextid));
516cf3eb 447
271e6dec 448 if ($parentid) {
f34488b2 449 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
3e0e25ef 450 print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
516cf3eb 451 }
452 }
453
2d696f8f
TH
454 if ((string) $idnumber === '') {
455 $idnumber = null;
456 } else if (!empty($contextid)) {
6189fda4
JB
457 // While this check already exists in the form validation, this is a backstop preventing unnecessary errors.
458 if ($DB->record_exists('question_categories',
459 ['idnumber' => $idnumber, 'contextid' => $contextid])) {
460 $idnumber = null;
461 }
462 }
463
7f389342 464 $cat = new stdClass();
271e6dec 465 $cat->parent = $parentid;
466 $cat->contextid = $contextid;
516cf3eb 467 $cat->name = $newcategory;
468 $cat->info = $newinfo;
fa5c608c 469 $cat->infoformat = $newinfoformat;
516cf3eb 470 $cat->sortorder = 999;
471 $cat->stamp = make_unique_id_code();
9c4f0fa7 472 $cat->idnumber = $idnumber;
bb4b6010 473 $categoryid = $DB->insert_record("question_categories", $cat);
58940b19
MN
474
475 // Log the creation of this category.
4ca60a56
V
476 $category = new stdClass();
477 $category->id = $categoryid;
478 $category->contextid = $contextid;
479 $event = \core\event\question_category_created::create_from_question_category_instance($category);
58940b19
MN
480 $event->trigger();
481
bb4b6010 482 if ($return) {
483 return $categoryid;
516cf3eb 484 } else {
e42f153c 485 redirect($this->pageurl);//always redirect after successful action
516cf3eb 486 }
516cf3eb 487 }
488
bc649d80 489 /**
490 * Updates an existing category with given params
93e435b9
SB
491 *
492 * @param int $updateid
493 * @param int $newparent
494 * @param string $newname
495 * @param string $newinfo
496 * @param int $newinfoformat
497 * @param int $idnumber
498 * @param bool $redirect
499 * @return int
bc649d80 500 */
6189fda4 501 public function update_category($updateid, $newparent, $newname, $newinfo, $newinfoformat = FORMAT_HTML,
93e435b9 502 $idnumber = null, $redirect = true) {
f9b0500f 503 global $CFG, $DB;
271e6dec 504 if (empty($newname)) {
5e8a85aa 505 print_error('categorynamecantbeblank', 'question');
bc649d80 506 }
516cf3eb 507
41c96651 508 // Get the record we are updating.
f34488b2 509 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
9275220d 510 $lastcategoryinthiscontext = question_is_only_child_of_top_category_in_context($updateid);
41c96651 511
512 if (!empty($newparent) && !$lastcategoryinthiscontext) {
513 list($parentid, $tocontextid) = explode(',', $newparent);
514 } else {
515 $parentid = $oldcat->parent;
516 $tocontextid = $oldcat->contextid;
517 }
518
519 // Check permissions.
d197ea43 520 $fromcontext = context::instance_by_id($oldcat->contextid);
271e6dec 521 require_capability('moodle/question:managecategory', $fromcontext);
41c96651 522
d7d4a097
JD
523 // If moving to another context, check permissions some more, and confirm contextid,stamp uniqueness.
524 $newstamprequired = false;
5d548d3e 525 if ($oldcat->contextid != $tocontextid) {
d197ea43 526 $tocontext = context::instance_by_id($tocontextid);
271e6dec 527 require_capability('moodle/question:managecategory', $tocontext);
d7d4a097
JD
528
529 // Confirm stamp uniqueness in the new context. If the stamp already exists, generate a new one.
530 if ($DB->record_exists('question_categories', array('contextid' => $tocontextid, 'stamp' => $oldcat->stamp))) {
531 $newstamprequired = true;
532 }
271e6dec 533 }
41c96651 534
2d696f8f
TH
535 if ((string) $idnumber === '') {
536 $idnumber = null;
537 } else if (!empty($tocontextid)) {
6189fda4
JB
538 // While this check already exists in the form validation, this is a backstop preventing unnecessary errors.
539 if ($DB->record_exists('question_categories',
540 ['idnumber' => $idnumber, 'contextid' => $tocontextid])) {
541 $idnumber = null;
542 }
543 }
544
41c96651 545 // Update the category record.
9aa09d8f 546 $cat = new stdClass();
516cf3eb 547 $cat->id = $updateid;
271e6dec 548 $cat->name = $newname;
549 $cat->info = $newinfo;
fa5c608c 550 $cat->infoformat = $newinfoformat;
41c96651 551 $cat->parent = $parentid;
5d548d3e 552 $cat->contextid = $tocontextid;
9c4f0fa7 553 $cat->idnumber = $idnumber;
d7d4a097
JD
554 if ($newstamprequired) {
555 $cat->stamp = make_unique_id_code();
556 }
bb4b6010 557 $DB->update_record('question_categories', $cat);
f59dba84 558
93e435b9 559 // Log the update of this category.
4ca60a56 560 $event = \core\event\question_category_updated::create_from_question_category_instance($cat);
93e435b9
SB
561 $event->trigger();
562
df4e2244 563 // If the category name has changed, rename any random questions in that category.
41c96651 564 if ($oldcat->name != $cat->name) {
3cac440b 565 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
566
f9b0500f
TH
567 $randomqtype = question_bank::get_qtype('random');
568 $randomqname = $randomqtype->question_name($cat, false);
3cac440b 569 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '0'));
570
f9b0500f 571 $randomqname = $randomqtype->question_name($cat, true);
3cac440b 572 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '1'));
41c96651 573 }
574
5d548d3e
TH
575 if ($oldcat->contextid != $tocontextid) {
576 // Moving to a new context. Must move files belonging to questions.
577 question_move_category_to_context($cat->id, $oldcat->contextid, $tocontextid);
516cf3eb 578 }
271e6dec 579
9645fe83
TH
580 // Cat param depends on the context id, so update it.
581 $this->pageurl->param('cat', $updateid . ',' . $tocontextid);
93e435b9
SB
582 if ($redirect) {
583 redirect($this->pageurl); // Always redirect after successful action.
584 }
271e6dec 585 }
516cf3eb 586}