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