MDL-20636 Add @package and GPL boiler-plate to files in /question.
[moodle.git] / question / category_class.php
CommitLineData
aeb15530 1<?php
d3603157
TH
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * A class for representing question categories.
20 *
21 * @package moodlecore
22 * @subpackage questionbank
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
516cf3eb 27/**
4323d029 28 * Class representing question categories
bc649d80 29 *
d3603157
TH
30 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
31 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
bc649d80 32 */
516cf3eb 33
34// number of categories to display on page
d3603157 35define('QUESTION_PAGE_LENGTH', 25);
dac786f3 36
94dbfb3a
TH
37require_once($CFG->libdir . '/listlib.php');
38require_once($CFG->dirroot . '/question/category_form.php');
271e6dec 39require_once('move_form.php');
dac786f3 40
41class question_category_list extends moodle_list {
f34488b2 42 public $table = "question_categories";
43 public $listitemclassname = 'question_category_list_item';
271e6dec 44 /**
45 * @var reference to list displayed below this one.
46 */
f34488b2 47 public $nextlist = null;
271e6dec 48 /**
49 * @var reference to list displayed above this one.
50 */
f34488b2 51 public $lastlist = null;
271e6dec 52
f34488b2 53 public $context = null;
c65921d4 54 public $sortby = 'parent, sortorder, name';
271e6dec 55
20d89122
TH
56 public function __construct($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){
57 parent::__construct('ul', '', $editable, $pageurl, $page, 'cpage', $itemsperpage);
271e6dec 58 $this->context = $context;
59 }
986effb6 60
f34488b2 61 public function get_records() {
271e6dec 62 $this->records = get_categories_for_contexts($this->context->id, $this->sortby);
63 }
dac786f3 64}
65
66class question_category_list_item extends list_item {
f34488b2 67 public function set_icon_html($first, $last, &$lastitem){
271e6dec 68 global $CFG;
69 $category = $this->item;
8afba50b
PS
70 $url = new moodle_url('/question/category.php', ($this->parentlist->pageurl->params() + array('edit'=>$category->id)));
71 $this->icons['edit']= $this->image_icon(get_string('editthiscategory', 'question'), $url, 'edit');
271e6dec 72 parent::set_icon_html($first, $last, $lastitem);
73 $toplevel = ($this->parentlist->parentitem === null);//this is a top level item
74 if (($this->parentlist->nextlist !== null) && $last && $toplevel && (count($this->parentlist->items)>1)){
8afba50b 75 $url = new moodle_url($this->parentlist->pageurl, array('movedowncontext'=>$this->id, 'tocontext'=>$this->parentlist->nextlist->context->id, 'sesskey'=>sesskey()));
f34488b2 76 $this->icons['down'] = $this->image_icon(
8afba50b 77 get_string('shareincontext', 'question', print_context_name($this->parentlist->nextlist->context)), $url, 'down');
271e6dec 78 }
79 if (($this->parentlist->lastlist !== null) && $first && $toplevel && (count($this->parentlist->items)>1)){
8afba50b 80 $url = new moodle_url($this->parentlist->pageurl, array('moveupcontext'=>$this->id, 'tocontext'=>$this->parentlist->lastlist->context->id, 'sesskey'=>sesskey()));
f34488b2 81 $this->icons['up'] = $this->image_icon(
8afba50b 82 get_string('shareincontext', 'question', print_context_name($this->parentlist->lastlist->context)), $url, 'up');
271e6dec 83 }
84 }
20d89122 85
f34488b2 86 public function item_html($extraargs = array()){
42d5737a 87 global $CFG, $OUTPUT;
dac786f3 88 $str = $extraargs['str'];
89 $category = $this->item;
90
271e6dec 91 $editqestions = get_string('editquestions', 'quiz');
dac786f3 92
93 /// Each section adds html to be displayed as part of this list item
8afba50b 94 $questionbankurl = new moodle_url("/question/edit.php", ($this->parentlist->pageurl->params() + array('category'=>"$category->id,$category->contextid")));
5d548d3e 95 $catediturl = $this->parentlist->pageurl->out(true, array('edit' => $this->id));
6e4ca69a 96 $item = "<b><a title=\"{$str->edit}\" href=\"$catediturl\">".$category->name ."</a></b> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount.')</a>';
dac786f3 97
98 $item .= '&nbsp;'. $category->info;
99
5d548d3e
TH
100 // don't allow delete if this is the last category in this context.
101 if (count($this->parentlist->records) != 1) {
8afba50b 102 $item .= '<a title="' . $str->delete . '" href="'.$this->parentlist->pageurl->out(true, array('delete'=>$this->id, 'sesskey'=>sesskey())).'">
b5d0cafc 103 <img src="' . $OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="' .$str->delete. '" /></a>';
dac786f3 104 }
105
106 return $item;
dac786f3 107 }
dac786f3 108}
109
516cf3eb 110
4323d029 111/**
112 * Class representing question categories
dac786f3 113 *
4323d029 114 * @package questionbank
115 */
dc1f00de 116class question_category_object {
516cf3eb 117
118 var $str;
dac786f3 119 /**
271e6dec 120 * Nested lists to display categories.
dac786f3 121 *
271e6dec 122 * @var array
dac786f3 123 */
271e6dec 124 var $editlists = array();
516cf3eb 125 var $newtable;
126 var $tab;
127 var $tabsize = 3;
a982d582 128//------------------------------------------------------
986effb6 129 /**
130 * @var moodle_url Object representing url for this page
131 */
a982d582 132 var $pageurl;
271e6dec 133 /**
134 * @var question_category_edit_form Object representing form for adding / editing categories.
135 */
136 var $catform;
516cf3eb 137
bc649d80 138 /**
139 * Constructor
140 *
141 * Gets necessary strings and sets relevant path information
142 */
f34488b2 143 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
a5cb8d69 144 global $CFG, $COURSE, $OUTPUT;
516cf3eb 145
146 $this->tab = str_repeat('&nbsp;', $this->tabsize);
147
148 $this->str->course = get_string('course');
149 $this->str->category = get_string('category', 'quiz');
150 $this->str->categoryinfo = get_string('categoryinfo', 'quiz');
151 $this->str->questions = get_string('questions', 'quiz');
152 $this->str->add = get_string('add');
153 $this->str->delete = get_string('delete');
154 $this->str->moveup = get_string('moveup');
155 $this->str->movedown = get_string('movedown');
85edde5c 156 $this->str->edit = get_string('editthiscategory', 'question');
516cf3eb 157 $this->str->hide = get_string('hide');
158 $this->str->publish = get_string('publish', 'quiz');
159 $this->str->order = get_string('order');
160 $this->str->parent = get_string('parent', 'quiz');
161 $this->str->add = get_string('add');
162 $this->str->action = get_string('action');
163 $this->str->top = get_string('top', 'quiz');
164 $this->str->addcategory = get_string('addcategory', 'quiz');
165 $this->str->editcategory = get_string('editcategory', 'quiz');
166 $this->str->cancel = get_string('cancel');
167 $this->str->editcategories = get_string('editcategories', 'quiz');
2befe778 168 $this->str->page = get_string('page');
516cf3eb 169
986effb6 170 $this->pageurl = $pageurl;
271e6dec 171
172 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
516cf3eb 173
516cf3eb 174 }
271e6dec 175
176
177
178 /**
179 * Initializes this classes general category-related variables
180 */
f34488b2 181 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
271e6dec 182 $lastlist = null;
183 foreach ($contexts as $context){
184 $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context);
185 $this->editlists[$context->id]->lastlist =& $lastlist;
186 if ($lastlist!== null){
187 $lastlist->nextlist =& $this->editlists[$context->id];
188 }
189 $lastlist =& $this->editlists[$context->id];
190 }
191
192 $count = 1;
193 $paged = false;
194 foreach ($this->editlists as $key => $list){
20f500dc 195 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
271e6dec 196 }
197 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
198 if (!$currentcat){
199 $this->catform->set_data(array('parent'=>$defaultcategory));
200 }
201 }
bc649d80 202 /**
203 * Displays the user interface
204 *
bc649d80 205 */
f34488b2 206 public function display_user_interface() {
dac786f3 207
208 /// Interface for editing existing categories
271e6dec 209 $this->output_edit_lists();
dac786f3 210
516cf3eb 211
dac786f3 212 echo '<br />';
516cf3eb 213 /// Interface for adding a new category:
516cf3eb 214 $this->output_new_table();
215 echo '<br />';
216
516cf3eb 217 }
218
bc649d80 219 /**
220 * Outputs a table to allow entry of a new category
221 */
f34488b2 222 public function output_new_table() {
271e6dec 223 $this->catform->display();
516cf3eb 224 }
225
bc649d80 226 /**
dac786f3 227 * Outputs a list to allow editing/rearranging of existing categories
bc649d80 228 *
229 * $this->initialize() must have already been called
230 *
bc649d80 231 */
f34488b2 232 public function output_edit_lists() {
723d610c 233 global $OUTPUT;
1d58b567 234
5fcefc97 235 echo $OUTPUT->heading_with_help(get_string('editcategories', 'question'), 'editcategories', 'question');
1d58b567 236
271e6dec 237 foreach ($this->editlists as $context => $list){
238 $listhtml = $list->to_html(0, array('str'=>$this->str));
239 if ($listhtml){
beb677cd 240 echo $OUTPUT->box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
723d610c 241 echo $OUTPUT->heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), 3);
271e6dec 242 echo $listhtml;
beb677cd 243 echo $OUTPUT->box_end();
271e6dec 244 }
245 }
246 echo $list->display_page_numbers();
247 }
516cf3eb 248
dac786f3 249
250
bc649d80 251 /**
252 * gets all the courseids for the given categories
253 *
254 * @param array categories contains category objects in a tree representation
255 * @return array courseids flat array in form categoryid=>courseid
256 */
f34488b2 257 public function get_course_ids($categories) {
516cf3eb 258 $courseids = array();
259 foreach ($categories as $key=>$cat) {
260 $courseids[$key] = $cat->course;
261 if (!empty($cat->children)) {
262 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
263 }
264 }
265 return $courseids;
266 }
267
516cf3eb 268
516cf3eb 269
f34488b2 270 public function edit_single_category($categoryid) {
516cf3eb 271 /// Interface for adding a new category
f34488b2 272 global $COURSE, $DB;
516cf3eb 273 /// Interface for editing existing categories
f34488b2 274 if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) {
516cf3eb 275
271e6dec 276 $category->parent = "$category->parent,$category->contextid";
277 $category->submitbutton = get_string('savechanges');
278 $category->categoryheader = $this->str->edit;
279 $this->catform->set_data($category);
280 $this->catform->display();
281 } else {
64e71d27 282 print_error('invalidcategory', '', '', $categoryid);
516cf3eb 283 }
516cf3eb 284 }
285
516cf3eb 286
bc649d80 287 /**
288 * Sets the viable parents
289 *
290 * Viable parents are any except for the category itself, or any of it's descendants
291 * The parentstrings parameter is passed by reference and changed by this function.
292 *
293 * @param array parentstrings a list of parentstrings
294 * @param object category
295 */
f34488b2 296 public function set_viable_parents(&$parentstrings, $category) {
516cf3eb 297
298 unset($parentstrings[$category->id]);
299 if (isset($category->children)) {
300 foreach ($category->children as $child) {
301 $this->set_viable_parents($parentstrings, $child);
302 }
303 }
304 }
305
bc649d80 306 /**
307 * Gets question categories
308 *
309 * @param int parent - if given, restrict records to those with this parent id.
310 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
311 * @return array categories
312 */
f34488b2 313 public function get_question_categories($parent=null, $sort="sortorder ASC") {
314 global $COURSE, $DB;
516cf3eb 315 if (is_null($parent)) {
f34488b2 316 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort);
516cf3eb 317 } else {
f34488b2 318 $select = "parent = ? AND course = ?";
319 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort);
516cf3eb 320 }
321 return $categories;
322 }
323
bc649d80 324 /**
325 * Deletes an existing question category
326 *
21cbf9da 327 * @param int deletecat id of category to delete
bc649d80 328 */
f34488b2 329 public function delete_category($categoryid) {
330 global $CFG, $DB;
271e6dec 331 question_can_delete_cat($categoryid);
f34488b2 332 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
64e71d27 333 print_error('unknowcategory');
516cf3eb 334 }
516cf3eb 335 /// Send the children categories to live with their grandparent
bb4b6010 336 $DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id));
516cf3eb 337
338 /// Finally delete the category itself
21cbf9da 339 $DB->delete_records("question_categories", array("id" => $category->id));
516cf3eb 340 }
21cbf9da 341
f34488b2 342 public function move_questions_and_delete_category($oldcat, $newcat){
271e6dec 343 question_can_delete_cat($oldcat);
344 $this->move_questions($oldcat, $newcat);
345 $this->delete_category($oldcat);
346 }
516cf3eb 347
f34488b2 348 public function display_move_form($questionsincategory, $category){
beb677cd 349 global $OUTPUT;
0ff4bd08 350 $vars = new stdClass();
271e6dec 351 $vars->name = $category->name;
352 $vars->count = $questionsincategory;
beb677cd 353 echo $OUTPUT->box(get_string('categorymove', 'quiz', $vars), 'generalbox boxaligncenter');
271e6dec 354 $this->moveform->display();
355 }
516cf3eb 356
f34488b2 357 public function move_questions($oldcat, $newcat){
534792cd 358 global $DB;
5d548d3e
TH
359 $questionids = $DB->get_records_select_menu('question',
360 'category = ? AND (parent = 0 OR parent = id)', array($oldcat), '', 'id,1');
361 question_move_questions_to_category($questionids, $newcat);
516cf3eb 362 }
363
bc649d80 364 /**
365 * Creates a new category with given params
bc649d80 366 */
94dbfb3a 367 public function add_category($newparent, $newcategory, $newinfo, $return = false) {
f34488b2 368 global $DB;
bc649d80 369 if (empty($newcategory)) {
5a2a5331 370 print_error('categorynamecantbeblank', 'quiz');
bc649d80 371 }
271e6dec 372 list($parentid, $contextid) = explode(',', $newparent);
373 //moodle_form makes sure select element output is legal no need for further cleaning
374 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
516cf3eb 375
271e6dec 376 if ($parentid) {
f34488b2 377 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
3e0e25ef 378 print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
516cf3eb 379 }
380 }
381
7f389342 382 $cat = new stdClass();
271e6dec 383 $cat->parent = $parentid;
384 $cat->contextid = $contextid;
516cf3eb 385 $cat->name = $newcategory;
386 $cat->info = $newinfo;
516cf3eb 387 $cat->sortorder = 999;
388 $cat->stamp = make_unique_id_code();
bb4b6010 389 $categoryid = $DB->insert_record("question_categories", $cat);
390 if ($return) {
391 return $categoryid;
516cf3eb 392 } else {
e42f153c 393 redirect($this->pageurl);//always redirect after successful action
516cf3eb 394 }
516cf3eb 395 }
396
bc649d80 397 /**
398 * Updates an existing category with given params
bc649d80 399 */
f34488b2 400 public function update_category($updateid, $newparent, $newname, $newinfo) {
f9b0500f 401 global $CFG, $DB;
271e6dec 402 if (empty($newname)) {
5a2a5331 403 print_error('categorynamecantbeblank', 'quiz');
bc649d80 404 }
516cf3eb 405
41c96651 406 // Get the record we are updating.
f34488b2 407 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
df4e2244 408 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
41c96651 409
410 if (!empty($newparent) && !$lastcategoryinthiscontext) {
411 list($parentid, $tocontextid) = explode(',', $newparent);
412 } else {
413 $parentid = $oldcat->parent;
414 $tocontextid = $oldcat->contextid;
415 }
416
417 // Check permissions.
271e6dec 418 $fromcontext = get_context_instance_by_id($oldcat->contextid);
419 require_capability('moodle/question:managecategory', $fromcontext);
41c96651 420
421 // If moving to another context, check permissions some more.
5d548d3e 422 if ($oldcat->contextid != $tocontextid) {
271e6dec 423 $tocontext = get_context_instance_by_id($tocontextid);
424 require_capability('moodle/question:managecategory', $tocontext);
425 }
41c96651 426
427 // Update the category record.
516cf3eb 428 $cat = NULL;
429 $cat->id = $updateid;
271e6dec 430 $cat->name = $newname;
431 $cat->info = $newinfo;
41c96651 432 $cat->parent = $parentid;
5d548d3e 433 $cat->contextid = $tocontextid;
bb4b6010 434 $DB->update_record('question_categories', $cat);
f59dba84 435
df4e2244 436 // If the category name has changed, rename any random questions in that category.
41c96651 437 if ($oldcat->name != $cat->name) {
3cac440b 438 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
439
f9b0500f
TH
440 $randomqtype = question_bank::get_qtype('random');
441 $randomqname = $randomqtype->question_name($cat, false);
3cac440b 442 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '0'));
443
f9b0500f 444 $randomqname = $randomqtype->question_name($cat, true);
3cac440b 445 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '1'));
41c96651 446 }
447
5d548d3e
TH
448 if ($oldcat->contextid != $tocontextid) {
449 // Moving to a new context. Must move files belonging to questions.
450 question_move_category_to_context($cat->id, $oldcat->contextid, $tocontextid);
516cf3eb 451 }
271e6dec 452
5d548d3e 453 redirect($this->pageurl);
271e6dec 454 }
516cf3eb 455}