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