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