Merged branch 'MDL-27692_master' of git://github.com/MaryE/moodle.git
[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 {
f34488b2 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(
8afba50b 86 get_string('shareincontext', 'question', print_context_name($this->parentlist->nextlist->context)), $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(
8afba50b 91 get_string('shareincontext', 'question', print_context_name($this->parentlist->lastlist->context)), $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
102 /// Each section adds html to be displayed as part of this list item
8afba50b 103 $questionbankurl = new moodle_url("/question/edit.php", ($this->parentlist->pageurl->params() + array('category'=>"$category->id,$category->contextid")));
5d548d3e 104 $catediturl = $this->parentlist->pageurl->out(true, array('edit' => $this->id));
6e4ca69a 105 $item = "<b><a title=\"{$str->edit}\" href=\"$catediturl\">".$category->name ."</a></b> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount.')</a>';
dac786f3 106
107 $item .= '&nbsp;'. $category->info;
108
5d548d3e
TH
109 // don't allow delete if this is the last category in this context.
110 if (count($this->parentlist->records) != 1) {
8afba50b 111 $item .= '<a title="' . $str->delete . '" href="'.$this->parentlist->pageurl->out(true, array('delete'=>$this->id, 'sesskey'=>sesskey())).'">
b5d0cafc 112 <img src="' . $OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="' .$str->delete. '" /></a>';
dac786f3 113 }
114
115 return $item;
dac786f3 116 }
dac786f3 117}
118
516cf3eb 119
4323d029 120/**
017bc1d9 121 * Class representing q question category
dac786f3 122 *
017bc1d9
TH
123 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4323d029 125 */
dc1f00de 126class question_category_object {
516cf3eb 127
128 var $str;
dac786f3 129 /**
271e6dec 130 * Nested lists to display categories.
dac786f3 131 *
271e6dec 132 * @var array
dac786f3 133 */
271e6dec 134 var $editlists = array();
516cf3eb 135 var $newtable;
136 var $tab;
137 var $tabsize = 3;
017bc1d9 138
986effb6 139 /**
140 * @var moodle_url Object representing url for this page
141 */
a982d582 142 var $pageurl;
271e6dec 143 /**
144 * @var question_category_edit_form Object representing form for adding / editing categories.
145 */
146 var $catform;
516cf3eb 147
bc649d80 148 /**
149 * Constructor
150 *
151 * Gets necessary strings and sets relevant path information
152 */
f34488b2 153 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
a5cb8d69 154 global $CFG, $COURSE, $OUTPUT;
516cf3eb 155
156 $this->tab = str_repeat('&nbsp;', $this->tabsize);
157
158 $this->str->course = get_string('course');
5e8a85aa
TH
159 $this->str->category = get_string('category', 'question');
160 $this->str->categoryinfo = get_string('categoryinfo', 'question');
161 $this->str->questions = get_string('questions', 'question');
516cf3eb 162 $this->str->add = get_string('add');
163 $this->str->delete = get_string('delete');
164 $this->str->moveup = get_string('moveup');
165 $this->str->movedown = get_string('movedown');
85edde5c 166 $this->str->edit = get_string('editthiscategory', 'question');
516cf3eb 167 $this->str->hide = get_string('hide');
516cf3eb 168 $this->str->order = get_string('order');
5e8a85aa 169 $this->str->parent = get_string('parent', 'question');
516cf3eb 170 $this->str->add = get_string('add');
171 $this->str->action = get_string('action');
5e8a85aa
TH
172 $this->str->top = get_string('top');
173 $this->str->addcategory = get_string('addcategory', 'question');
174 $this->str->editcategory = get_string('editcategory', 'question');
516cf3eb 175 $this->str->cancel = get_string('cancel');
5e8a85aa 176 $this->str->editcategories = get_string('editcategories', 'question');
2befe778 177 $this->str->page = get_string('page');
516cf3eb 178
986effb6 179 $this->pageurl = $pageurl;
271e6dec 180
181 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
516cf3eb 182 }
271e6dec 183
271e6dec 184 /**
185 * Initializes this classes general category-related variables
186 */
f34488b2 187 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
271e6dec 188 $lastlist = null;
189 foreach ($contexts as $context){
190 $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context);
191 $this->editlists[$context->id]->lastlist =& $lastlist;
192 if ($lastlist!== null){
193 $lastlist->nextlist =& $this->editlists[$context->id];
194 }
195 $lastlist =& $this->editlists[$context->id];
196 }
197
198 $count = 1;
199 $paged = false;
200 foreach ($this->editlists as $key => $list){
20f500dc 201 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
271e6dec 202 }
203 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
204 if (!$currentcat){
205 $this->catform->set_data(array('parent'=>$defaultcategory));
206 }
207 }
017bc1d9 208
bc649d80 209 /**
210 * Displays the user interface
211 *
bc649d80 212 */
f34488b2 213 public function display_user_interface() {
dac786f3 214
215 /// Interface for editing existing categories
271e6dec 216 $this->output_edit_lists();
dac786f3 217
516cf3eb 218
dac786f3 219 echo '<br />';
516cf3eb 220 /// Interface for adding a new category:
516cf3eb 221 $this->output_new_table();
222 echo '<br />';
223
516cf3eb 224 }
225
bc649d80 226 /**
227 * Outputs a table to allow entry of a new category
228 */
f34488b2 229 public function output_new_table() {
271e6dec 230 $this->catform->display();
516cf3eb 231 }
232
bc649d80 233 /**
dac786f3 234 * Outputs a list to allow editing/rearranging of existing categories
bc649d80 235 *
236 * $this->initialize() must have already been called
237 *
bc649d80 238 */
f34488b2 239 public function output_edit_lists() {
723d610c 240 global $OUTPUT;
1d58b567 241
5fcefc97 242 echo $OUTPUT->heading_with_help(get_string('editcategories', 'question'), 'editcategories', 'question');
1d58b567 243
271e6dec 244 foreach ($this->editlists as $context => $list){
245 $listhtml = $list->to_html(0, array('str'=>$this->str));
246 if ($listhtml){
beb677cd 247 echo $OUTPUT->box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
723d610c 248 echo $OUTPUT->heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), 3);
271e6dec 249 echo $listhtml;
beb677cd 250 echo $OUTPUT->box_end();
271e6dec 251 }
252 }
253 echo $list->display_page_numbers();
254 }
516cf3eb 255
bc649d80 256 /**
257 * gets all the courseids for the given categories
258 *
259 * @param array categories contains category objects in a tree representation
260 * @return array courseids flat array in form categoryid=>courseid
261 */
f34488b2 262 public function get_course_ids($categories) {
516cf3eb 263 $courseids = array();
264 foreach ($categories as $key=>$cat) {
265 $courseids[$key] = $cat->course;
266 if (!empty($cat->children)) {
267 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
268 }
269 }
270 return $courseids;
271 }
272
f34488b2 273 public function edit_single_category($categoryid) {
516cf3eb 274 /// Interface for adding a new category
f34488b2 275 global $COURSE, $DB;
516cf3eb 276 /// Interface for editing existing categories
f34488b2 277 if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) {
516cf3eb 278
271e6dec 279 $category->parent = "$category->parent,$category->contextid";
280 $category->submitbutton = get_string('savechanges');
281 $category->categoryheader = $this->str->edit;
282 $this->catform->set_data($category);
283 $this->catform->display();
284 } else {
64e71d27 285 print_error('invalidcategory', '', '', $categoryid);
516cf3eb 286 }
516cf3eb 287 }
288
bc649d80 289 /**
290 * Sets the viable parents
291 *
292 * Viable parents are any except for the category itself, or any of it's descendants
293 * The parentstrings parameter is passed by reference and changed by this function.
294 *
295 * @param array parentstrings a list of parentstrings
296 * @param object category
297 */
f34488b2 298 public function set_viable_parents(&$parentstrings, $category) {
516cf3eb 299
300 unset($parentstrings[$category->id]);
301 if (isset($category->children)) {
302 foreach ($category->children as $child) {
303 $this->set_viable_parents($parentstrings, $child);
304 }
305 }
306 }
307
bc649d80 308 /**
309 * Gets question categories
310 *
311 * @param int parent - if given, restrict records to those with this parent id.
312 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
313 * @return array categories
314 */
f34488b2 315 public function get_question_categories($parent=null, $sort="sortorder ASC") {
316 global $COURSE, $DB;
516cf3eb 317 if (is_null($parent)) {
f34488b2 318 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort);
516cf3eb 319 } else {
f34488b2 320 $select = "parent = ? AND course = ?";
321 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort);
516cf3eb 322 }
323 return $categories;
324 }
325
bc649d80 326 /**
327 * Deletes an existing question category
328 *
21cbf9da 329 * @param int deletecat id of category to delete
bc649d80 330 */
f34488b2 331 public function delete_category($categoryid) {
332 global $CFG, $DB;
271e6dec 333 question_can_delete_cat($categoryid);
f34488b2 334 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
64e71d27 335 print_error('unknowcategory');
516cf3eb 336 }
516cf3eb 337 /// Send the children categories to live with their grandparent
bb4b6010 338 $DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id));
516cf3eb 339
340 /// Finally delete the category itself
21cbf9da 341 $DB->delete_records("question_categories", array("id" => $category->id));
516cf3eb 342 }
21cbf9da 343
f34488b2 344 public function move_questions_and_delete_category($oldcat, $newcat){
271e6dec 345 question_can_delete_cat($oldcat);
346 $this->move_questions($oldcat, $newcat);
347 $this->delete_category($oldcat);
348 }
516cf3eb 349
f34488b2 350 public function display_move_form($questionsincategory, $category){
beb677cd 351 global $OUTPUT;
0ff4bd08 352 $vars = new stdClass();
271e6dec 353 $vars->name = $category->name;
354 $vars->count = $questionsincategory;
5e8a85aa 355 echo $OUTPUT->box(get_string('categorymove', 'question', $vars), 'generalbox boxaligncenter');
271e6dec 356 $this->moveform->display();
357 }
516cf3eb 358
f34488b2 359 public function move_questions($oldcat, $newcat){
534792cd 360 global $DB;
5d548d3e
TH
361 $questionids = $DB->get_records_select_menu('question',
362 'category = ? AND (parent = 0 OR parent = id)', array($oldcat), '', 'id,1');
363 question_move_questions_to_category($questionids, $newcat);
516cf3eb 364 }
365
bc649d80 366 /**
367 * Creates a new category with given params
bc649d80 368 */
94dbfb3a 369 public function add_category($newparent, $newcategory, $newinfo, $return = false) {
f34488b2 370 global $DB;
bc649d80 371 if (empty($newcategory)) {
5e8a85aa 372 print_error('categorynamecantbeblank', 'question');
bc649d80 373 }
271e6dec 374 list($parentid, $contextid) = explode(',', $newparent);
375 //moodle_form makes sure select element output is legal no need for further cleaning
376 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
516cf3eb 377
271e6dec 378 if ($parentid) {
f34488b2 379 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
3e0e25ef 380 print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
516cf3eb 381 }
382 }
383
7f389342 384 $cat = new stdClass();
271e6dec 385 $cat->parent = $parentid;
386 $cat->contextid = $contextid;
516cf3eb 387 $cat->name = $newcategory;
388 $cat->info = $newinfo;
516cf3eb 389 $cat->sortorder = 999;
390 $cat->stamp = make_unique_id_code();
bb4b6010 391 $categoryid = $DB->insert_record("question_categories", $cat);
392 if ($return) {
393 return $categoryid;
516cf3eb 394 } else {
e42f153c 395 redirect($this->pageurl);//always redirect after successful action
516cf3eb 396 }
516cf3eb 397 }
398
bc649d80 399 /**
400 * Updates an existing category with given params
bc649d80 401 */
f34488b2 402 public function update_category($updateid, $newparent, $newname, $newinfo) {
f9b0500f 403 global $CFG, $DB;
271e6dec 404 if (empty($newname)) {
5e8a85aa 405 print_error('categorynamecantbeblank', 'question');
bc649d80 406 }
516cf3eb 407
41c96651 408 // Get the record we are updating.
f34488b2 409 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
df4e2244 410 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
41c96651 411
412 if (!empty($newparent) && !$lastcategoryinthiscontext) {
413 list($parentid, $tocontextid) = explode(',', $newparent);
414 } else {
415 $parentid = $oldcat->parent;
416 $tocontextid = $oldcat->contextid;
417 }
418
419 // Check permissions.
271e6dec 420 $fromcontext = get_context_instance_by_id($oldcat->contextid);
421 require_capability('moodle/question:managecategory', $fromcontext);
41c96651 422
423 // If moving to another context, check permissions some more.
5d548d3e 424 if ($oldcat->contextid != $tocontextid) {
271e6dec 425 $tocontext = get_context_instance_by_id($tocontextid);
426 require_capability('moodle/question:managecategory', $tocontext);
427 }
41c96651 428
429 // Update the category record.
e0736817 430 $cat = null;
516cf3eb 431 $cat->id = $updateid;
271e6dec 432 $cat->name = $newname;
433 $cat->info = $newinfo;
41c96651 434 $cat->parent = $parentid;
5d548d3e 435 $cat->contextid = $tocontextid;
bb4b6010 436 $DB->update_record('question_categories', $cat);
f59dba84 437
df4e2244 438 // If the category name has changed, rename any random questions in that category.
41c96651 439 if ($oldcat->name != $cat->name) {
3cac440b 440 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
441
f9b0500f
TH
442 $randomqtype = question_bank::get_qtype('random');
443 $randomqname = $randomqtype->question_name($cat, false);
3cac440b 444 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '0'));
445
f9b0500f 446 $randomqname = $randomqtype->question_name($cat, true);
3cac440b 447 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '1'));
41c96651 448 }
449
5d548d3e
TH
450 if ($oldcat->contextid != $tocontextid) {
451 // Moving to a new context. Must move files belonging to questions.
452 question_move_category_to_context($cat->id, $oldcat->contextid, $tocontextid);
516cf3eb 453 }
271e6dec 454
5d548d3e 455 redirect($this->pageurl);
271e6dec 456 }
516cf3eb 457}