MDL-19976 Changing redirect($url->out()) to redirect($url). NEVER, NEVER use redirect...
[moodle.git] / question / category_class.php
CommitLineData
107e7612 1<?php // $Id$
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;
67 $this->icons['edit']= $this->image_icon(get_string('editthiscategory'),
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"));
96 $catediturl = $this->parentlist->pageurl->out(false, 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)).'">
42d5737a 103 <img src="' . $OUTPUT->old_icon_url('t/delete.gif') . '" 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');
161 $this->str->edit = get_string('editthiscategory');
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() {
35241c76 258 print_heading_with_help(get_string('editcategories', 'quiz'), 'categories', 'question');
271e6dec 259 foreach ($this->editlists as $context => $list){
260 $listhtml = $list->to_html(0, array('str'=>$this->str));
261 if ($listhtml){
9fc523e0 262 print_box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
271e6dec 263 print_heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), '', 3);
271e6dec 264 echo $listhtml;
265 print_box_end();
266 }
267 }
268 echo $list->display_page_numbers();
269 }
516cf3eb 270
dac786f3 271
272
bc649d80 273 /**
274 * gets all the courseids for the given categories
275 *
276 * @param array categories contains category objects in a tree representation
277 * @return array courseids flat array in form categoryid=>courseid
278 */
f34488b2 279 public function get_course_ids($categories) {
516cf3eb 280 $courseids = array();
281 foreach ($categories as $key=>$cat) {
282 $courseids[$key] = $cat->course;
283 if (!empty($cat->children)) {
284 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
285 }
286 }
287 return $courseids;
288 }
289
516cf3eb 290
516cf3eb 291
f34488b2 292 public function edit_single_category($categoryid) {
516cf3eb 293 /// Interface for adding a new category
f34488b2 294 global $COURSE, $DB;
516cf3eb 295 /// Interface for editing existing categories
f34488b2 296 if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) {
516cf3eb 297
271e6dec 298 $category->parent = "$category->parent,$category->contextid";
299 $category->submitbutton = get_string('savechanges');
300 $category->categoryheader = $this->str->edit;
301 $this->catform->set_data($category);
302 $this->catform->display();
303 } else {
64e71d27 304 print_error('invalidcategory', '', '', $categoryid);
516cf3eb 305 }
516cf3eb 306 }
307
516cf3eb 308
bc649d80 309 /**
310 * Sets the viable parents
311 *
312 * Viable parents are any except for the category itself, or any of it's descendants
313 * The parentstrings parameter is passed by reference and changed by this function.
314 *
315 * @param array parentstrings a list of parentstrings
316 * @param object category
317 */
f34488b2 318 public function set_viable_parents(&$parentstrings, $category) {
516cf3eb 319
320 unset($parentstrings[$category->id]);
321 if (isset($category->children)) {
322 foreach ($category->children as $child) {
323 $this->set_viable_parents($parentstrings, $child);
324 }
325 }
326 }
327
bc649d80 328 /**
329 * Gets question categories
330 *
331 * @param int parent - if given, restrict records to those with this parent id.
332 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
333 * @return array categories
334 */
f34488b2 335 public function get_question_categories($parent=null, $sort="sortorder ASC") {
336 global $COURSE, $DB;
516cf3eb 337 if (is_null($parent)) {
f34488b2 338 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort);
516cf3eb 339 } else {
f34488b2 340 $select = "parent = ? AND course = ?";
341 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort);
516cf3eb 342 }
343 return $categories;
344 }
345
bc649d80 346 /**
347 * Deletes an existing question category
348 *
21cbf9da 349 * @param int deletecat id of category to delete
bc649d80 350 */
f34488b2 351 public function delete_category($categoryid) {
352 global $CFG, $DB;
271e6dec 353 question_can_delete_cat($categoryid);
f34488b2 354 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
64e71d27 355 print_error('unknowcategory');
516cf3eb 356 }
516cf3eb 357 /// Send the children categories to live with their grandparent
bb4b6010 358 $DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id));
516cf3eb 359
360 /// Finally delete the category itself
21cbf9da 361 $DB->delete_records("question_categories", array("id" => $category->id));
516cf3eb 362 }
21cbf9da 363
f34488b2 364 public function move_questions_and_delete_category($oldcat, $newcat){
271e6dec 365 question_can_delete_cat($oldcat);
366 $this->move_questions($oldcat, $newcat);
367 $this->delete_category($oldcat);
368 }
516cf3eb 369
f34488b2 370 public function display_move_form($questionsincategory, $category){
271e6dec 371 $vars = new stdClass;
372 $vars->name = $category->name;
373 $vars->count = $questionsincategory;
6acbb319 374 print_box(get_string('categorymove', 'quiz', $vars), 'generalbox boxaligncenter');
271e6dec 375 $this->moveform->display();
376 }
516cf3eb 377
f34488b2 378 public function move_questions($oldcat, $newcat){
534792cd 379 global $DB;
380 $questionids = $DB->get_records_select_menu('question', "category = ? AND (parent = 0 OR parent = id)", array($oldcat), '', 'id,1');
41c96651 381 $ids = implode(',', array_keys($questionids));
382 if (!question_move_questions_to_category($ids, $newcat)) {
383 print_error('errormovingquestions', 'question', $this->pageurl->out(), $ids);
516cf3eb 384 }
385 }
386
bc649d80 387 /**
388 * Creates a new category with given params
bc649d80 389 */
fa583f5f 390 public function add_category($newparent, $newcategory, $newinfo, $return=false) {
f34488b2 391 global $DB;
bc649d80 392 if (empty($newcategory)) {
5a2a5331 393 print_error('categorynamecantbeblank', 'quiz');
bc649d80 394 }
271e6dec 395 list($parentid, $contextid) = explode(',', $newparent);
396 //moodle_form makes sure select element output is legal no need for further cleaning
397 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
516cf3eb 398
271e6dec 399 if ($parentid) {
f34488b2 400 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
64e71d27 401 print_error('cannotinsertquestioncatecontext', 'question', '', array($newcategory, $contextid));
516cf3eb 402 }
403 }
404
271e6dec 405 $cat = new object();
406 $cat->parent = $parentid;
407 $cat->contextid = $contextid;
516cf3eb 408 $cat->name = $newcategory;
409 $cat->info = $newinfo;
516cf3eb 410 $cat->sortorder = 999;
411 $cat->stamp = make_unique_id_code();
bb4b6010 412 $categoryid = $DB->insert_record("question_categories", $cat);
413 if ($return) {
414 return $categoryid;
516cf3eb 415 } else {
e42f153c 416 redirect($this->pageurl);//always redirect after successful action
516cf3eb 417 }
516cf3eb 418 }
419
bc649d80 420 /**
421 * Updates an existing category with given params
bc649d80 422 */
f34488b2 423 public function update_category($updateid, $newparent, $newname, $newinfo) {
424 global $CFG, $QTYPES, $DB;
271e6dec 425 if (empty($newname)) {
5a2a5331 426 print_error('categorynamecantbeblank', 'quiz');
bc649d80 427 }
516cf3eb 428
41c96651 429 // Get the record we are updating.
f34488b2 430 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
df4e2244 431 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
41c96651 432
433 if (!empty($newparent) && !$lastcategoryinthiscontext) {
434 list($parentid, $tocontextid) = explode(',', $newparent);
435 } else {
436 $parentid = $oldcat->parent;
437 $tocontextid = $oldcat->contextid;
438 }
439
440 // Check permissions.
271e6dec 441 $fromcontext = get_context_instance_by_id($oldcat->contextid);
442 require_capability('moodle/question:managecategory', $fromcontext);
41c96651 443
444 // If moving to another context, check permissions some more.
445 if ($oldcat->contextid != $tocontextid){
271e6dec 446 $tocontext = get_context_instance_by_id($tocontextid);
447 require_capability('moodle/question:managecategory', $tocontext);
448 }
41c96651 449
450 // Update the category record.
516cf3eb 451 $cat = NULL;
452 $cat->id = $updateid;
271e6dec 453 $cat->name = $newname;
454 $cat->info = $newinfo;
41c96651 455 $cat->parent = $parentid;
456 // We don't change $cat->contextid here, if necessary we redirect to contextmove.php later.
bb4b6010 457 $DB->update_record('question_categories', $cat);
f59dba84 458
df4e2244 459 // If the category name has changed, rename any random questions in that category.
41c96651 460 if ($oldcat->name != $cat->name) {
3cac440b 461 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
462
463 $randomqname = $QTYPES[RANDOM]->question_name($cat, false);
464 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '0'));
465
466 $randomqname = $QTYPES[RANDOM]->question_name($cat, true);
467 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '1'));
41c96651 468 }
469
470 // Then redirect to an appropriate place.
471 if ($oldcat->contextid == $tocontextid) { // not moving contexts
e42f153c 472 redirect($this->pageurl);
516cf3eb 473 } else {
41c96651 474 redirect($CFG->wwwroot.'/question/contextmove.php?' .
475 $this->pageurl->get_query_string(array(
476 'cattomove' => $updateid, 'toparent'=>$newparent)));
516cf3eb 477 }
478 }
271e6dec 479
f34488b2 480 public function move_question_from_cat_confirm($fromcat, $fromcourse, $tocat=null, $question=null){
481 global $QTYPES, $DB;
271e6dec 482 if (!$question){
483 $questions[] = $question;
484 } else {
f34488b2 485 $questions = $DB->get_records('question', array('category' => $tocat->id));
271e6dec 486 }
487 $urls = array();
488 foreach ($questions as $question){
489 $urls = array_merge($urls, $QTYPES[$question->qtype]->find_file_links_in_question($question));
490 }
491 if ($fromcourse){
492 $append = 'tocourse';
493 } else {
494 $append = 'tosite';
495 }
496 if ($tocat){
497 echo '<p>'.get_string('needtomovethesefilesincat','question').'</p>';
498 } else {
499 echo '<p>'.get_string('needtomovethesefilesinquestion','question').'</p>';
500 }
501 }
502
503
504
505
516cf3eb 506}
507
508?>