Merge branch 'MDL-62619' of git://github.com/stronk7/moodle
[moodle.git] / question / category_class.php
blobe7f6ccb6a5605ed69f70d0e3a4f7a6c7dba46797
1 <?php
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.
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/>.
17 /**
18 * A class for representing question categories.
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
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');
37 /**
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';
46 /**
47 * @var reference to list displayed below this one.
49 public $nextlist = null;
50 /**
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);
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.
71 * @param list_item $item The item which its top level parent is going to be returned.
72 * @return int
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;
82 /**
83 * An item in a list of question categories.
85 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
86 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
88 class question_category_list_item extends list_item {
89 public function set_icon_html($first, $last, $lastitem){
90 global $CFG;
91 $category = $this->item;
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');
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)){
97 $url = new moodle_url($this->parentlist->pageurl, array('movedowncontext'=>$this->id, 'tocontext'=>$this->parentlist->nextlist->context->id, 'sesskey'=>sesskey()));
98 $this->icons['down'] = $this->image_icon(
99 get_string('shareincontext', 'question', $this->parentlist->nextlist->context->get_context_name()), $url, 'down');
101 if (($this->parentlist->lastlist !== null) && $first && $toplevel && (count($this->parentlist->items)>1)){
102 $url = new moodle_url($this->parentlist->pageurl, array('moveupcontext'=>$this->id, 'tocontext'=>$this->parentlist->lastlist->context->id, 'sesskey'=>sesskey()));
103 $this->icons['up'] = $this->image_icon(
104 get_string('shareincontext', 'question', $this->parentlist->lastlist->context->get_context_name()), $url, 'up');
108 public function item_html($extraargs = array()){
109 global $CFG, $OUTPUT;
110 $str = $extraargs['str'];
111 $category = $this->item;
113 $editqestions = get_string('editquestions', 'question');
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);
118 $catediturl = new moodle_url($this->parentlist->pageurl, array('edit' => $this->id));
119 $item = '';
120 $item .= html_writer::tag('b', html_writer::link($catediturl,
121 format_string($category->name, true, array('context' => $this->parentlist->context)),
122 array('title' => $str->edit))) . ' ';
123 $item .= html_writer::link($questionbankurl, '(' . $category->questioncount . ')',
124 array('title' => $editqestions)) . ' ';
125 $item .= format_text($category->info, $category->infoformat,
126 array('context' => $this->parentlist->context, 'noclean' => true));
128 // Don't allow delete if this is the top category, or the last editable category in this context.
129 if ($category->parent && !question_is_only_child_of_top_category_in_context($category->id)) {
130 $deleteurl = new moodle_url($this->parentlist->pageurl, array('delete' => $this->id, 'sesskey' => sesskey()));
131 $item .= html_writer::link($deleteurl,
132 $OUTPUT->pix_icon('t/delete', $str->delete),
133 array('title' => $str->delete));
136 return $item;
142 * Class representing q question category
144 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
145 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
147 class question_category_object {
150 * @var array common language strings.
152 public $str;
155 * @var array nested lists to display categories.
157 public $editlists = array();
158 public $newtable;
159 public $tab;
160 public $tabsize = 3;
163 * @var moodle_url Object representing url for this page
165 public $pageurl;
168 * @var question_category_edit_form Object representing form for adding / editing categories.
170 public $catform;
173 * Constructor
175 * Gets necessary strings and sets relevant path information
177 public function __construct($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
178 global $CFG, $COURSE, $OUTPUT;
180 $this->tab = str_repeat('&nbsp;', $this->tabsize);
182 $this->str = new stdClass();
183 $this->str->course = get_string('course');
184 $this->str->category = get_string('category', 'question');
185 $this->str->categoryinfo = get_string('categoryinfo', 'question');
186 $this->str->questions = get_string('questions', 'question');
187 $this->str->add = get_string('add');
188 $this->str->delete = get_string('delete');
189 $this->str->moveup = get_string('moveup');
190 $this->str->movedown = get_string('movedown');
191 $this->str->edit = get_string('editthiscategory', 'question');
192 $this->str->hide = get_string('hide');
193 $this->str->order = get_string('order');
194 $this->str->parent = get_string('parent', 'question');
195 $this->str->add = get_string('add');
196 $this->str->action = get_string('action');
197 $this->str->top = get_string('top');
198 $this->str->addcategory = get_string('addcategory', 'question');
199 $this->str->editcategory = get_string('editcategory', 'question');
200 $this->str->cancel = get_string('cancel');
201 $this->str->editcategories = get_string('editcategories', 'question');
202 $this->str->page = get_string('page');
204 $this->pageurl = $pageurl;
206 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
210 * Old syntax of class constructor. Deprecated in PHP7.
212 * @deprecated since Moodle 3.1
214 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
215 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
216 self::__construct($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
220 * Initializes this classes general category-related variables
222 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
223 $lastlist = null;
224 foreach ($contexts as $context){
225 $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context);
226 $this->editlists[$context->id]->lastlist =& $lastlist;
227 if ($lastlist!== null){
228 $lastlist->nextlist =& $this->editlists[$context->id];
230 $lastlist =& $this->editlists[$context->id];
233 $count = 1;
234 $paged = false;
235 foreach ($this->editlists as $key => $list){
236 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
238 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
239 if (!$currentcat){
240 $this->catform->set_data(array('parent'=>$defaultcategory));
245 * Displays the user interface
248 public function display_user_interface() {
250 /// Interface for editing existing categories
251 $this->output_edit_lists();
254 echo '<br />';
255 /// Interface for adding a new category:
256 $this->output_new_table();
257 echo '<br />';
262 * Outputs a table to allow entry of a new category
264 public function output_new_table() {
265 $this->catform->display();
269 * Outputs a list to allow editing/rearranging of existing categories
271 * $this->initialize() must have already been called
274 public function output_edit_lists() {
275 global $OUTPUT;
277 echo $OUTPUT->heading_with_help(get_string('editcategories', 'question'), 'editcategories', 'question');
279 foreach ($this->editlists as $context => $list){
280 $listhtml = $list->to_html(0, array('str'=>$this->str));
281 if ($listhtml){
282 echo $OUTPUT->box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
283 $fullcontext = context::instance_by_id($context);
284 echo $OUTPUT->heading(get_string('questioncatsfor', 'question', $fullcontext->get_context_name()), 3);
285 echo $listhtml;
286 echo $OUTPUT->box_end();
289 echo $list->display_page_numbers();
293 * gets all the courseids for the given categories
295 * @param array categories contains category objects in a tree representation
296 * @return array courseids flat array in form categoryid=>courseid
298 public function get_course_ids($categories) {
299 $courseids = array();
300 foreach ($categories as $key=>$cat) {
301 $courseids[$key] = $cat->course;
302 if (!empty($cat->children)) {
303 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
306 return $courseids;
309 public function edit_single_category($categoryid) {
310 /// Interface for adding a new category
311 global $DB;
312 /// Interface for editing existing categories
313 $category = $DB->get_record("question_categories", array("id" => $categoryid));
314 if (empty($category)) {
315 print_error('invalidcategory', '', '', $categoryid);
316 } else if ($category->parent == 0) {
317 print_error('cannotedittopcat', 'question', '', $categoryid);
318 } else {
319 $category->parent = "{$category->parent},{$category->contextid}";
320 $category->submitbutton = get_string('savechanges');
321 $category->categoryheader = $this->str->edit;
322 $this->catform->set_data($category);
323 $this->catform->display();
328 * Sets the viable parents
330 * Viable parents are any except for the category itself, or any of it's descendants
331 * The parentstrings parameter is passed by reference and changed by this function.
333 * @param array parentstrings a list of parentstrings
334 * @param object category
336 public function set_viable_parents(&$parentstrings, $category) {
338 unset($parentstrings[$category->id]);
339 if (isset($category->children)) {
340 foreach ($category->children as $child) {
341 $this->set_viable_parents($parentstrings, $child);
347 * Gets question categories
349 * @param int parent - if given, restrict records to those with this parent id.
350 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
351 * @return array categories
353 public function get_question_categories($parent=null, $sort="sortorder ASC") {
354 global $COURSE, $DB;
355 if (is_null($parent)) {
356 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort);
357 } else {
358 $select = "parent = ? AND course = ?";
359 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort);
361 return $categories;
365 * Deletes an existing question category
367 * @param int deletecat id of category to delete
369 public function delete_category($categoryid) {
370 global $CFG, $DB;
371 question_can_delete_cat($categoryid);
372 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
373 print_error('unknowcategory');
375 /// Send the children categories to live with their grandparent
376 $DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id));
378 /// Finally delete the category itself
379 $DB->delete_records("question_categories", array("id" => $category->id));
382 public function move_questions_and_delete_category($oldcat, $newcat){
383 question_can_delete_cat($oldcat);
384 $this->move_questions($oldcat, $newcat);
385 $this->delete_category($oldcat);
388 public function display_move_form($questionsincategory, $category){
389 global $OUTPUT;
390 $vars = new stdClass();
391 $vars->name = $category->name;
392 $vars->count = $questionsincategory;
393 echo $OUTPUT->box(get_string('categorymove', 'question', $vars), 'generalbox boxaligncenter');
394 $this->moveform->display();
397 public function move_questions($oldcat, $newcat){
398 global $DB;
399 $questionids = $DB->get_records_select_menu('question',
400 'category = ? AND (parent = 0 OR parent = id)', array($oldcat), '', 'id,1');
401 question_move_questions_to_category(array_keys($questionids), $newcat);
405 * Creates a new category with given params
407 public function add_category($newparent, $newcategory, $newinfo, $return = false, $newinfoformat = FORMAT_HTML) {
408 global $DB;
409 if (empty($newcategory)) {
410 print_error('categorynamecantbeblank', 'question');
412 list($parentid, $contextid) = explode(',', $newparent);
413 //moodle_form makes sure select element output is legal no need for further cleaning
414 require_capability('moodle/question:managecategory', context::instance_by_id($contextid));
416 if ($parentid) {
417 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
418 print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
422 $cat = new stdClass();
423 $cat->parent = $parentid;
424 $cat->contextid = $contextid;
425 $cat->name = $newcategory;
426 $cat->info = $newinfo;
427 $cat->infoformat = $newinfoformat;
428 $cat->sortorder = 999;
429 $cat->stamp = make_unique_id_code();
430 $categoryid = $DB->insert_record("question_categories", $cat);
432 // Log the creation of this category.
433 $params = array(
434 'objectid' => $categoryid,
435 'contextid' => $contextid
437 $event = \core\event\question_category_created::create($params);
438 $event->trigger();
440 if ($return) {
441 return $categoryid;
442 } else {
443 redirect($this->pageurl);//always redirect after successful action
448 * Updates an existing category with given params
450 public function update_category($updateid, $newparent, $newname, $newinfo, $newinfoformat = FORMAT_HTML) {
451 global $CFG, $DB;
452 if (empty($newname)) {
453 print_error('categorynamecantbeblank', 'question');
456 // Get the record we are updating.
457 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
458 $lastcategoryinthiscontext = question_is_only_child_of_top_category_in_context($updateid);
460 if (!empty($newparent) && !$lastcategoryinthiscontext) {
461 list($parentid, $tocontextid) = explode(',', $newparent);
462 } else {
463 $parentid = $oldcat->parent;
464 $tocontextid = $oldcat->contextid;
467 // Check permissions.
468 $fromcontext = context::instance_by_id($oldcat->contextid);
469 require_capability('moodle/question:managecategory', $fromcontext);
471 // If moving to another context, check permissions some more, and confirm contextid,stamp uniqueness.
472 $newstamprequired = false;
473 if ($oldcat->contextid != $tocontextid) {
474 $tocontext = context::instance_by_id($tocontextid);
475 require_capability('moodle/question:managecategory', $tocontext);
477 // Confirm stamp uniqueness in the new context. If the stamp already exists, generate a new one.
478 if ($DB->record_exists('question_categories', array('contextid' => $tocontextid, 'stamp' => $oldcat->stamp))) {
479 $newstamprequired = true;
483 // Update the category record.
484 $cat = new stdClass();
485 $cat->id = $updateid;
486 $cat->name = $newname;
487 $cat->info = $newinfo;
488 $cat->infoformat = $newinfoformat;
489 $cat->parent = $parentid;
490 $cat->contextid = $tocontextid;
491 if ($newstamprequired) {
492 $cat->stamp = make_unique_id_code();
494 $DB->update_record('question_categories', $cat);
496 // If the category name has changed, rename any random questions in that category.
497 if ($oldcat->name != $cat->name) {
498 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
500 $randomqtype = question_bank::get_qtype('random');
501 $randomqname = $randomqtype->question_name($cat, false);
502 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '0'));
504 $randomqname = $randomqtype->question_name($cat, true);
505 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '1'));
508 if ($oldcat->contextid != $tocontextid) {
509 // Moving to a new context. Must move files belonging to questions.
510 question_move_category_to_context($cat->id, $oldcat->contextid, $tocontextid);
513 // Cat param depends on the context id, so update it.
514 $this->pageurl->param('cat', $updateid . ',' . $tocontextid);
515 redirect($this->pageurl);