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