MDL-18293 removed obsoleted checking of return values from insert and update_record
[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()){
dac786f3 87 global $CFG;
88 $pixpath = $CFG->pixpath;
89 $str = $extraargs['str'];
90 $category = $this->item;
91
271e6dec 92 $editqestions = get_string('editquestions', 'quiz');
dac786f3 93
94 /// Each section adds html to be displayed as part of this list item
271e6dec 95 $questionbankurl = "{$CFG->wwwroot}/question/edit.php?".
96 $this->parentlist->pageurl->get_query_string(array('category'=>"$category->id,$category->contextid"));
97 $catediturl = $this->parentlist->pageurl->out(false, array('edit'=>$this->id));
6e4ca69a 98 $item = "<b><a title=\"{$str->edit}\" href=\"$catediturl\">".$category->name ."</a></b> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount.')</a>';
dac786f3 99
100 $item .= '&nbsp;'. $category->info;
101
271e6dec 102 if (count($this->parentlist->records)!=1){ // don't allow delete if this is the last category in this context.
986effb6 103 $item .= '<a title="' . $str->delete . '" href="'.$this->parentlist->pageurl->out_action(array('delete'=>$this->id)).'">
6e4ca69a 104 <img src="' . $pixpath . '/t/delete.gif" class="iconsmall" alt="' .$str->delete. '" /></a>';
dac786f3 105 }
106
107 return $item;
dac786f3 108 }
109
110}
111
516cf3eb 112
4323d029 113/**
114 * Class representing question categories
dac786f3 115 *
4323d029 116 * @package questionbank
117 */
dc1f00de 118class question_category_object {
516cf3eb 119
120 var $str;
121 var $pixpath;
dac786f3 122 /**
271e6dec 123 * Nested lists to display categories.
dac786f3 124 *
271e6dec 125 * @var array
dac786f3 126 */
271e6dec 127 var $editlists = array();
516cf3eb 128 var $newtable;
129 var $tab;
130 var $tabsize = 3;
a982d582 131//------------------------------------------------------
986effb6 132 /**
133 * @var moodle_url Object representing url for this page
134 */
a982d582 135 var $pageurl;
271e6dec 136 /**
137 * @var question_category_edit_form Object representing form for adding / editing categories.
138 */
139 var $catform;
fa583f5f 140 /**
141 * @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.
142 */
143 var $catform_rand;
516cf3eb 144
bc649d80 145 /**
146 * Constructor
147 *
148 * Gets necessary strings and sets relevant path information
149 */
f34488b2 150 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
dac786f3 151 global $CFG, $COURSE;
516cf3eb 152
153 $this->tab = str_repeat('&nbsp;', $this->tabsize);
154
155 $this->str->course = get_string('course');
156 $this->str->category = get_string('category', 'quiz');
157 $this->str->categoryinfo = get_string('categoryinfo', 'quiz');
158 $this->str->questions = get_string('questions', 'quiz');
159 $this->str->add = get_string('add');
160 $this->str->delete = get_string('delete');
161 $this->str->moveup = get_string('moveup');
162 $this->str->movedown = get_string('movedown');
163 $this->str->edit = get_string('editthiscategory');
164 $this->str->hide = get_string('hide');
165 $this->str->publish = get_string('publish', 'quiz');
166 $this->str->order = get_string('order');
167 $this->str->parent = get_string('parent', 'quiz');
168 $this->str->add = get_string('add');
169 $this->str->action = get_string('action');
170 $this->str->top = get_string('top', 'quiz');
171 $this->str->addcategory = get_string('addcategory', 'quiz');
172 $this->str->editcategory = get_string('editcategory', 'quiz');
173 $this->str->cancel = get_string('cancel');
174 $this->str->editcategories = get_string('editcategories', 'quiz');
2befe778 175 $this->str->page = get_string('page');
516cf3eb 176 $this->pixpath = $CFG->pixpath;
177
986effb6 178 $this->pageurl = $pageurl;
271e6dec 179
180 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
516cf3eb 181
516cf3eb 182 }
271e6dec 183
184
185
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'));
fa583f5f 206 $this->catform_rand = new question_category_edit_form_randomquestion($this->pageurl, compact('contexts', 'currentcat'));
271e6dec 207 if (!$currentcat){
208 $this->catform->set_data(array('parent'=>$defaultcategory));
fa583f5f 209 $this->catform_rand->set_data(array('parent'=>$defaultcategory));
271e6dec 210 }
211 }
bc649d80 212 /**
213 * Displays the user interface
214 *
bc649d80 215 */
f34488b2 216 public function display_user_interface() {
dac786f3 217
218 /// Interface for editing existing categories
271e6dec 219 $this->output_edit_lists();
dac786f3 220
516cf3eb 221
dac786f3 222 echo '<br />';
516cf3eb 223 /// Interface for adding a new category:
516cf3eb 224 $this->output_new_table();
225 echo '<br />';
226
fa583f5f 227 }
228 /**
229 * Displays the user interface
230 *
231 */
4070210d 232 function display_randomquestion_user_interface($addonpage=0) {
5c8505d0 233 $this->catform_rand->set_data(array('addonpage'=>$addonpage));
fa583f5f 234 /// Interface for adding a new category:
235 $this->output_new_randomquestion_table();
236
516cf3eb 237 }
238
bc649d80 239 /**
240 * Outputs a table to allow entry of a new category
241 */
f34488b2 242 public function output_new_table() {
271e6dec 243 $this->catform->display();
516cf3eb 244 }
245
fa583f5f 246 /**
247 * Outputs a table to allow entry of a new category
248 */
249 function output_new_randomquestion_table() {
250 $this->catform_rand->display();
251 }
252
dac786f3 253
bc649d80 254 /**
dac786f3 255 * Outputs a list to allow editing/rearranging of existing categories
bc649d80 256 *
257 * $this->initialize() must have already been called
258 *
bc649d80 259 */
f34488b2 260 public function output_edit_lists() {
35241c76 261 print_heading_with_help(get_string('editcategories', 'quiz'), 'categories', 'question');
271e6dec 262 foreach ($this->editlists as $context => $list){
263 $listhtml = $list->to_html(0, array('str'=>$this->str));
264 if ($listhtml){
9fc523e0 265 print_box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
271e6dec 266 print_heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), '', 3);
271e6dec 267 echo $listhtml;
268 print_box_end();
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
f34488b2 361 if (!$DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id))) {
64e71d27 362 print_error('cannotupdatesubcate', 'question');
516cf3eb 363 }
364
365 /// Finally delete the category itself
21cbf9da 366 $DB->delete_records("question_categories", array("id" => $category->id));
516cf3eb 367 }
21cbf9da 368
f34488b2 369 public function move_questions_and_delete_category($oldcat, $newcat){
271e6dec 370 question_can_delete_cat($oldcat);
371 $this->move_questions($oldcat, $newcat);
372 $this->delete_category($oldcat);
373 }
516cf3eb 374
f34488b2 375 public function display_move_form($questionsincategory, $category){
271e6dec 376 $vars = new stdClass;
377 $vars->name = $category->name;
378 $vars->count = $questionsincategory;
379 print_simple_box(get_string("categorymove", "quiz", $vars), "center");
380 $this->moveform->display();
381 }
516cf3eb 382
f34488b2 383 public function move_questions($oldcat, $newcat){
534792cd 384 global $DB;
385 $questionids = $DB->get_records_select_menu('question', "category = ? AND (parent = 0 OR parent = id)", array($oldcat), '', 'id,1');
41c96651 386 $ids = implode(',', array_keys($questionids));
387 if (!question_move_questions_to_category($ids, $newcat)) {
388 print_error('errormovingquestions', 'question', $this->pageurl->out(), $ids);
516cf3eb 389 }
390 }
391
bc649d80 392 /**
393 * Creates a new category with given params
bc649d80 394 */
fa583f5f 395 public function add_category($newparent, $newcategory, $newinfo, $return=false) {
f34488b2 396 global $DB;
bc649d80 397 if (empty($newcategory)) {
5a2a5331 398 print_error('categorynamecantbeblank', 'quiz');
bc649d80 399 }
271e6dec 400 list($parentid, $contextid) = explode(',', $newparent);
401 //moodle_form makes sure select element output is legal no need for further cleaning
402 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
516cf3eb 403
271e6dec 404 if ($parentid) {
f34488b2 405 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
64e71d27 406 print_error('cannotinsertquestioncatecontext', 'question', '', array($newcategory, $contextid));
516cf3eb 407 }
408 }
409
271e6dec 410 $cat = new object();
411 $cat->parent = $parentid;
412 $cat->contextid = $contextid;
516cf3eb 413 $cat->name = $newcategory;
414 $cat->info = $newinfo;
516cf3eb 415 $cat->sortorder = 999;
416 $cat->stamp = make_unique_id_code();
fa583f5f 417 if (!$categoryid=$DB->insert_record("question_categories", $cat)) {
64e71d27 418 print_error('cannotinsertquestioncate', 'question', '', $newcategory);
516cf3eb 419 } else {
fa583f5f 420 if($return){
421 return $categoryid;
422 }else{
423 redirect($this->pageurl->out());//always redirect after successful action
424 }
516cf3eb 425 }
516cf3eb 426 }
427
bc649d80 428 /**
429 * Updates an existing category with given params
bc649d80 430 */
f34488b2 431 public function update_category($updateid, $newparent, $newname, $newinfo) {
432 global $CFG, $QTYPES, $DB;
271e6dec 433 if (empty($newname)) {
5a2a5331 434 print_error('categorynamecantbeblank', 'quiz');
bc649d80 435 }
516cf3eb 436
41c96651 437 // Get the record we are updating.
f34488b2 438 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
df4e2244 439 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
41c96651 440
441 if (!empty($newparent) && !$lastcategoryinthiscontext) {
442 list($parentid, $tocontextid) = explode(',', $newparent);
443 } else {
444 $parentid = $oldcat->parent;
445 $tocontextid = $oldcat->contextid;
446 }
447
448 // Check permissions.
271e6dec 449 $fromcontext = get_context_instance_by_id($oldcat->contextid);
450 require_capability('moodle/question:managecategory', $fromcontext);
41c96651 451
452 // If moving to another context, check permissions some more.
453 if ($oldcat->contextid != $tocontextid){
271e6dec 454 $tocontext = get_context_instance_by_id($tocontextid);
455 require_capability('moodle/question:managecategory', $tocontext);
456 }
41c96651 457
458 // Update the category record.
516cf3eb 459 $cat = NULL;
460 $cat->id = $updateid;
271e6dec 461 $cat->name = $newname;
462 $cat->info = $newinfo;
41c96651 463 $cat->parent = $parentid;
464 // We don't change $cat->contextid here, if necessary we redirect to contextmove.php later.
465 if (!$DB->update_record('question_categories', $cat)) {
466 print_error('cannotupdatecate', 'question', $this->pageurl->out(), $newname);
467 }
f59dba84 468
df4e2244 469 // If the category name has changed, rename any random questions in that category.
41c96651 470 if ($oldcat->name != $cat->name) {
3cac440b 471 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
472
473 $randomqname = $QTYPES[RANDOM]->question_name($cat, false);
474 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '0'));
475
476 $randomqname = $QTYPES[RANDOM]->question_name($cat, true);
477 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '1'));
41c96651 478 }
479
480 // Then redirect to an appropriate place.
481 if ($oldcat->contextid == $tocontextid) { // not moving contexts
482 redirect($this->pageurl->out());
516cf3eb 483 } else {
41c96651 484 redirect($CFG->wwwroot.'/question/contextmove.php?' .
485 $this->pageurl->get_query_string(array(
486 'cattomove' => $updateid, 'toparent'=>$newparent)));
516cf3eb 487 }
488 }
271e6dec 489
f34488b2 490 public function move_question_from_cat_confirm($fromcat, $fromcourse, $tocat=null, $question=null){
491 global $QTYPES, $DB;
271e6dec 492 if (!$question){
493 $questions[] = $question;
494 } else {
f34488b2 495 $questions = $DB->get_records('question', array('category' => $tocat->id));
271e6dec 496 }
497 $urls = array();
498 foreach ($questions as $question){
499 $urls = array_merge($urls, $QTYPES[$question->qtype]->find_file_links_in_question($question));
500 }
501 if ($fromcourse){
502 $append = 'tocourse';
503 } else {
504 $append = 'tosite';
505 }
506 if ($tocat){
507 echo '<p>'.get_string('needtomovethesefilesincat','question').'</p>';
508 } else {
509 echo '<p>'.get_string('needtomovethesefilesinquestion','question').'</p>';
510 }
511 }
512
513
514
515
516cf3eb 516}
517
518?>