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