2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * A class for representing question categories.
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
27 defined('MOODLE_INTERNAL') ||
die();
29 // number of categories to display on page
30 define('QUESTION_PAGE_LENGTH', 25);
32 require_once($CFG->libdir
. '/listlib.php');
33 require_once($CFG->dirroot
. '/question/category_form.php');
34 require_once($CFG->dirroot
. '/question/move_form.php');
38 * Class representing a list of question categories
40 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 class question_category_list
extends moodle_list
{
44 public $table = "question_categories";
45 public $listitemclassname = 'question_category_list_item';
47 * @var reference to list displayed below this one.
49 public $nextlist = null;
51 * @var reference to list displayed above this one.
53 public $lastlist = null;
55 public $context = null;
56 public $sortby = 'parent, sortorder, name';
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);
60 $this->context
= $context;
63 public function get_records() {
64 $this->records
= get_categories_for_contexts($this->context
->id
, $this->sortby
);
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.
71 * @param list_item $item The item which its top level parent is going to be returned.
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
;
81 * process any actions.
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
88 * @throws coding_exception
90 public function process_actions($left, $right, $moveup, $movedown) {
91 $category = new stdClass();
93 // Moved Left (In to another category).
94 $category->id
= $left;
95 $category->contextid
= $this->context
->id
;
96 $event = \core\event\question_category_moved
::create_from_question_category_instance($category);
98 } else if (!empty($right)) {
99 // Moved Right (Out of the current category).
100 $category->id
= $right;
101 $category->contextid
= $this->context
->id
;
102 $event = \core\event\question_category_moved
::create_from_question_category_instance($category);
105 parent
::process_actions($left, $right, $moveup, $movedown);
110 * An item in a list of question categories.
112 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
113 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
115 class question_category_list_item
extends list_item
{
116 public function set_icon_html($first, $last, $lastitem){
118 $category = $this->item
;
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');
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)){
124 $url = new moodle_url($this->parentlist
->pageurl
, array('movedowncontext'=>$this->id
, 'tocontext'=>$this->parentlist
->nextlist
->context
->id
, 'sesskey'=>sesskey()));
125 $this->icons
['down'] = $this->image_icon(
126 get_string('shareincontext', 'question', $this->parentlist
->nextlist
->context
->get_context_name()), $url, 'down');
128 if (($this->parentlist
->lastlist
!== null) && $first && $toplevel && (count($this->parentlist
->items
)>1)){
129 $url = new moodle_url($this->parentlist
->pageurl
, array('moveupcontext'=>$this->id
, 'tocontext'=>$this->parentlist
->lastlist
->context
->id
, 'sesskey'=>sesskey()));
130 $this->icons
['up'] = $this->image_icon(
131 get_string('shareincontext', 'question', $this->parentlist
->lastlist
->context
->get_context_name()), $url, 'up');
135 public function item_html($extraargs = array()){
136 global $CFG, $OUTPUT;
137 $str = $extraargs['str'];
138 $category = $this->item
;
140 $editqestions = get_string('editquestions', 'question');
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
);
146 $text = format_string($category->name
, true, ['context' => $this->parentlist
->context
]);
147 if ($category->idnumber
!== null && $category->idnumber
!== '') {
148 $text .= ' ' . html_writer
::span(
149 html_writer
::span(get_string('idnumber', 'question'), 'accesshide') .
150 ' ' . $category->idnumber
, 'badge badge-primary');
152 $text .= ' (' . $category->questioncount
. ')';
153 $item .= html_writer
::tag('b', html_writer
::link($questionbankurl, $text,
154 ['title' => $editqestions]) . ' ');
155 $item .= format_text($category->info
, $category->infoformat
,
156 array('context' => $this->parentlist
->context
, 'noclean' => true));
158 // Don't allow delete if this is the top category, or the last editable category in this context.
159 if ($category->parent
&& !question_is_only_child_of_top_category_in_context($category->id
)) {
160 $deleteurl = new moodle_url($this->parentlist
->pageurl
, array('delete' => $this->id
, 'sesskey' => sesskey()));
161 $item .= html_writer
::link($deleteurl,
162 $OUTPUT->pix_icon('t/delete', $str->delete
),
163 array('title' => $str->delete
));
172 * Class representing q question category
174 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
175 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
177 class question_category_object
{
180 * @var array common language strings.
185 * @var array nested lists to display categories.
187 public $editlists = array();
193 * @var moodle_url Object representing url for this page
198 * @var question_category_edit_form Object representing form for adding / editing categories.
205 * Gets necessary strings and sets relevant path information
207 public function __construct($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
208 global $CFG, $COURSE, $OUTPUT;
210 $this->tab
= str_repeat(' ', $this->tabsize
);
212 $this->str
= new stdClass();
213 $this->str
->course
= get_string('course');
214 $this->str
->category
= get_string('category', 'question');
215 $this->str
->categoryinfo
= get_string('categoryinfo', 'question');
216 $this->str
->questions
= get_string('questions', 'question');
217 $this->str
->add
= get_string('add');
218 $this->str
->delete
= get_string('delete');
219 $this->str
->moveup
= get_string('moveup');
220 $this->str
->movedown
= get_string('movedown');
221 $this->str
->edit
= get_string('editthiscategory', 'question');
222 $this->str
->hide
= get_string('hide');
223 $this->str
->order
= get_string('order');
224 $this->str
->parent
= get_string('parent', 'question');
225 $this->str
->add
= get_string('add');
226 $this->str
->action
= get_string('action');
227 $this->str
->top
= get_string('top');
228 $this->str
->addcategory
= get_string('addcategory', 'question');
229 $this->str
->editcategory
= get_string('editcategory', 'question');
230 $this->str
->cancel
= get_string('cancel');
231 $this->str
->editcategories
= get_string('editcategories', 'question');
232 $this->str
->page
= get_string('page');
234 $this->pageurl
= $pageurl;
236 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
240 * Old syntax of class constructor. Deprecated in PHP7.
242 * @deprecated since Moodle 3.1
244 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
245 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
246 self
::__construct($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
250 * Initializes this classes general category-related variables
252 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
254 foreach ($contexts as $context){
255 $this->editlists
[$context->id
] = new question_category_list('ul', '', true, $this->pageurl
, $page, 'cpage', QUESTION_PAGE_LENGTH
, $context);
256 $this->editlists
[$context->id
]->lastlist
=& $lastlist;
257 if ($lastlist!== null){
258 $lastlist->nextlist
=& $this->editlists
[$context->id
];
260 $lastlist =& $this->editlists
[$context->id
];
265 foreach ($this->editlists
as $key => $list){
266 list($paged, $count) = $this->editlists
[$key]->list_from_records($paged, $count);
268 $this->catform
= new question_category_edit_form($this->pageurl
, compact('contexts', 'currentcat'));
270 $this->catform
->set_data(array('parent'=>$defaultcategory));
275 * Displays the user interface
278 public function display_user_interface() {
280 /// Interface for editing existing categories
281 $this->output_edit_lists();
285 /// Interface for adding a new category:
286 $this->output_new_table();
292 * Outputs a table to allow entry of a new category
294 public function output_new_table() {
295 $this->catform
->display();
299 * Outputs a list to allow editing/rearranging of existing categories
301 * $this->initialize() must have already been called
304 public function output_edit_lists() {
307 echo $OUTPUT->heading_with_help(get_string('editcategories', 'question'), 'editcategories', 'question');
309 foreach ($this->editlists
as $context => $list){
310 $listhtml = $list->to_html(0, array('str'=>$this->str
));
312 echo $OUTPUT->box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context
->contextlevel
);
313 $fullcontext = context
::instance_by_id($context);
314 echo $OUTPUT->heading(get_string('questioncatsfor', 'question', $fullcontext->get_context_name()), 3);
316 echo $OUTPUT->box_end();
319 echo $list->display_page_numbers();
323 * gets all the courseids for the given categories
325 * @param array categories contains category objects in a tree representation
326 * @return array courseids flat array in form categoryid=>courseid
328 public function get_course_ids($categories) {
329 $courseids = array();
330 foreach ($categories as $key=>$cat) {
331 $courseids[$key] = $cat->course
;
332 if (!empty($cat->children
)) {
333 $courseids = array_merge($courseids, $this->get_course_ids($cat->children
));
339 public function edit_single_category($categoryid) {
340 /// Interface for adding a new category
342 /// Interface for editing existing categories
343 $category = $DB->get_record("question_categories", array("id" => $categoryid));
344 if (empty($category)) {
345 print_error('invalidcategory', '', '', $categoryid);
346 } else if ($category->parent
== 0) {
347 print_error('cannotedittopcat', 'question', '', $categoryid);
349 $category->parent
= "{$category->parent},{$category->contextid}";
350 $category->submitbutton
= get_string('savechanges');
351 $category->categoryheader
= $this->str
->edit
;
352 $this->catform
->set_data($category);
353 $this->catform
->display();
358 * Sets the viable parents
360 * Viable parents are any except for the category itself, or any of it's descendants
361 * The parentstrings parameter is passed by reference and changed by this function.
363 * @param array parentstrings a list of parentstrings
364 * @param object category
366 public function set_viable_parents(&$parentstrings, $category) {
368 unset($parentstrings[$category->id
]);
369 if (isset($category->children
)) {
370 foreach ($category->children
as $child) {
371 $this->set_viable_parents($parentstrings, $child);
377 * Gets question categories
379 * @param int parent - if given, restrict records to those with this parent id.
380 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
381 * @return array categories
383 public function get_question_categories($parent=null, $sort="sortorder ASC") {
385 if (is_null($parent)) {
386 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id
), $sort);
388 $select = "parent = ? AND course = ?";
389 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id
), $sort);
395 * Deletes an existing question category
397 * @param int deletecat id of category to delete
399 public function delete_category($categoryid) {
401 question_can_delete_cat($categoryid);
402 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
403 print_error('unknowcategory');
405 /// Send the children categories to live with their grandparent
406 $DB->set_field("question_categories", "parent", $category->parent
, array("parent" => $category->id
));
408 /// Finally delete the category itself
409 $DB->delete_records("question_categories", array("id" => $category->id
));
411 // Log the deletion of this category.
412 $event = \core\event\question_category_deleted
::create_from_question_category_instance($category);
413 $event->add_record_snapshot('question_categories', $category);
418 public function move_questions_and_delete_category($oldcat, $newcat){
419 question_can_delete_cat($oldcat);
420 $this->move_questions($oldcat, $newcat);
421 $this->delete_category($oldcat);
424 public function display_move_form($questionsincategory, $category){
426 $vars = new stdClass();
427 $vars->name
= $category->name
;
428 $vars->count
= $questionsincategory;
429 echo $OUTPUT->box(get_string('categorymove', 'question', $vars), 'generalbox boxaligncenter');
430 $this->moveform
->display();
433 public function move_questions($oldcat, $newcat){
435 $questionids = $DB->get_records_select_menu('question',
436 'category = ? AND (parent = 0 OR parent = id)', array($oldcat), '', 'id,1');
437 question_move_questions_to_category(array_keys($questionids), $newcat);
441 * Creates a new category with given params
443 public function add_category($newparent, $newcategory, $newinfo, $return = false, $newinfoformat = FORMAT_HTML
,
446 if (empty($newcategory)) {
447 print_error('categorynamecantbeblank', 'question');
449 list($parentid, $contextid) = explode(',', $newparent);
450 //moodle_form makes sure select element output is legal no need for further cleaning
451 require_capability('moodle/question:managecategory', context
::instance_by_id($contextid));
454 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
455 print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
459 if ((string) $idnumber === '') {
461 } else if (!empty($contextid)) {
462 // While this check already exists in the form validation, this is a backstop preventing unnecessary errors.
463 if ($DB->record_exists('question_categories',
464 ['idnumber' => $idnumber, 'contextid' => $contextid])) {
469 $cat = new stdClass();
470 $cat->parent
= $parentid;
471 $cat->contextid
= $contextid;
472 $cat->name
= $newcategory;
473 $cat->info
= $newinfo;
474 $cat->infoformat
= $newinfoformat;
475 $cat->sortorder
= 999;
476 $cat->stamp
= make_unique_id_code();
477 $cat->idnumber
= $idnumber;
479 $categoryid = $DB->insert_record("question_categories", $cat);
481 // Log the creation of this category.
482 $category = new stdClass();
483 $category->id
= $categoryid;
484 $category->contextid
= $contextid;
485 $event = \core\event\question_category_created
::create_from_question_category_instance($category);
491 redirect($this->pageurl
);//always redirect after successful action
496 * Updates an existing category with given params
498 * @param int $updateid
499 * @param int $newparent
500 * @param string $newname
501 * @param string $newinfo
502 * @param int $newinfoformat
503 * @param int $idnumber
504 * @param bool $redirect
507 public function update_category($updateid, $newparent, $newname, $newinfo, $newinfoformat = FORMAT_HTML
,
508 $idnumber = null, $redirect = true) {
510 if (empty($newname)) {
511 print_error('categorynamecantbeblank', 'question');
514 // Get the record we are updating.
515 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
516 $lastcategoryinthiscontext = question_is_only_child_of_top_category_in_context($updateid);
518 if (!empty($newparent) && !$lastcategoryinthiscontext) {
519 list($parentid, $tocontextid) = explode(',', $newparent);
521 $parentid = $oldcat->parent
;
522 $tocontextid = $oldcat->contextid
;
525 // Check permissions.
526 $fromcontext = context
::instance_by_id($oldcat->contextid
);
527 require_capability('moodle/question:managecategory', $fromcontext);
529 // If moving to another context, check permissions some more, and confirm contextid,stamp uniqueness.
530 $newstamprequired = false;
531 if ($oldcat->contextid
!= $tocontextid) {
532 $tocontext = context
::instance_by_id($tocontextid);
533 require_capability('moodle/question:managecategory', $tocontext);
535 // Confirm stamp uniqueness in the new context. If the stamp already exists, generate a new one.
536 if ($DB->record_exists('question_categories', array('contextid' => $tocontextid, 'stamp' => $oldcat->stamp
))) {
537 $newstamprequired = true;
541 $updateidnumber = true;
542 if ((string) $idnumber === '') {
544 } else if (!empty($tocontextid)) {
545 // While this check already exists in the form validation, this is a backstop preventing unnecessary errors.
546 if ($DB->record_exists('question_categories',
547 ['idnumber' => $idnumber, 'contextid' => $tocontextid])) {
549 $updateidnumber = false;
553 // Update the category record.
554 $cat = new stdClass();
555 $cat->id
= $updateid;
556 $cat->name
= $newname;
557 $cat->info
= $newinfo;
558 $cat->infoformat
= $newinfoformat;
559 $cat->parent
= $parentid;
560 $cat->contextid
= $tocontextid;
561 if ($updateidnumber) {
562 $cat->idnumber
= $idnumber;
564 if ($newstamprequired) {
565 $cat->stamp
= make_unique_id_code();
567 $DB->update_record('question_categories', $cat);
569 // Log the update of this category.
570 $event = \core\event\question_category_updated
::create_from_question_category_instance($cat);
573 // If the category name has changed, rename any random questions in that category.
574 if ($oldcat->name
!= $cat->name
) {
575 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
577 $randomqtype = question_bank
::get_qtype('random');
578 $randomqname = $randomqtype->question_name($cat, false);
579 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id
, '0'));
581 $randomqname = $randomqtype->question_name($cat, true);
582 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id
, '1'));
585 if ($oldcat->contextid
!= $tocontextid) {
586 // Moving to a new context. Must move files belonging to questions.
587 question_move_category_to_context($cat->id
, $oldcat->contextid
, $tocontextid);
590 // Cat param depends on the context id, so update it.
591 $this->pageurl
->param('cat', $updateid . ',' . $tocontextid);
593 redirect($this->pageurl
); // Always redirect after successful action.