MDL-15352: fix a bug introduce when I cleaned mnet/xmlrpc/server.php
[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");
15require_once('move_form.php');
dac786f3 16
17class question_category_list extends moodle_list {
f34488b2 18 public $table = "question_categories";
19 public $listitemclassname = 'question_category_list_item';
271e6dec 20 /**
21 * @var reference to list displayed below this one.
22 */
f34488b2 23 public $nextlist = null;
271e6dec 24 /**
25 * @var reference to list displayed above this one.
26 */
f34488b2 27 public $lastlist = null;
271e6dec 28
f34488b2 29 public $context = null;
271e6dec 30
f34488b2 31 public function question_category_list($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){
271e6dec 32 parent::moodle_list('ul', '', $editable, $pageurl, $page, 'cpage', $itemsperpage);
33 $this->context = $context;
34 }
986effb6 35
f34488b2 36 public function get_records() {
271e6dec 37 $this->records = get_categories_for_contexts($this->context->id, $this->sortby);
38 }
f34488b2 39 public function process_actions($left, $right, $moveup, $movedown, $moveupcontext, $movedowncontext, $tocontext){
271e6dec 40 global $CFG;
41 //parent::procces_actions redirects after any action
42 parent::process_actions($left, $right, $moveup, $movedown);
43 if ($tocontext == $this->context->id){
44 //only called on toplevel list
45 if ($moveupcontext){
46 $cattomove = $moveupcontext;
47 $totop = 0;
48 } elseif ($movedowncontext){
49 $cattomove = $movedowncontext;
50 $totop = 1;
dac786f3 51 }
271e6dec 52 $toparent = "0,{$this->context->id}";
53 redirect($CFG->wwwroot.'/question/contextmove.php?'.
54 $this->pageurl->get_query_string(compact('cattomove', 'totop', 'toparent')));
dac786f3 55 }
dac786f3 56 }
57}
58
59class question_category_list_item extends list_item {
60
61
f34488b2 62 public function set_icon_html($first, $last, &$lastitem){
271e6dec 63 global $CFG;
64 $category = $this->item;
65 $this->icons['edit']= $this->image_icon(get_string('editthiscategory'),
66 "{$CFG->wwwroot}/question/category.php?".$this->parentlist->pageurl->get_query_string(array('edit'=>$category->id)), 'edit');
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)){
f34488b2 70 $this->icons['down'] = $this->image_icon(
71 get_string('shareincontext', 'question', print_context_name($this->parentlist->nextlist->context)),
72 $this->parentlist->pageurl->out_action(
73 array('movedowncontext'=>$this->id, 'tocontext'=>$this->parentlist->nextlist->context->id)
74 ), 'down');
271e6dec 75 }
76 if (($this->parentlist->lastlist !== null) && $first && $toplevel && (count($this->parentlist->items)>1)){
f34488b2 77 $this->icons['up'] = $this->image_icon(
78 get_string('shareincontext', 'question', print_context_name($this->parentlist->lastlist->context)),
79 $this->parentlist->pageurl->out_action(
80 array('moveupcontext'=>$this->id, 'tocontext'=>$this->parentlist->lastlist->context->id)
81 ), 'up');
271e6dec 82 }
83 }
f34488b2 84 public function item_html($extraargs = array()){
dac786f3 85 global $CFG;
86 $pixpath = $CFG->pixpath;
87 $str = $extraargs['str'];
88 $category = $this->item;
89
271e6dec 90 $editqestions = get_string('editquestions', 'quiz');
dac786f3 91
92 /// Each section adds html to be displayed as part of this list item
271e6dec 93 $questionbankurl = "{$CFG->wwwroot}/question/edit.php?".
94 $this->parentlist->pageurl->get_query_string(array('category'=>"$category->id,$category->contextid"));
95 $catediturl = $this->parentlist->pageurl->out(false, array('edit'=>$this->id));
6e4ca69a 96 $item = "<b><a title=\"{$str->edit}\" href=\"$catediturl\">".$category->name ."</a></b> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount.')</a>';
dac786f3 97
98 $item .= '&nbsp;'. $category->info;
99
271e6dec 100 if (count($this->parentlist->records)!=1){ // don't allow delete if this is the last category in this context.
986effb6 101 $item .= '<a title="' . $str->delete . '" href="'.$this->parentlist->pageurl->out_action(array('delete'=>$this->id)).'">
6e4ca69a 102 <img src="' . $pixpath . '/t/delete.gif" class="iconsmall" alt="' .$str->delete. '" /></a>';
dac786f3 103 }
104
105 return $item;
dac786f3 106 }
107
108}
109
516cf3eb 110
4323d029 111/**
112 * Class representing question categories
dac786f3 113 *
4323d029 114 * @package questionbank
115 */
dc1f00de 116class question_category_object {
516cf3eb 117
118 var $str;
119 var $pixpath;
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;
516cf3eb 138
bc649d80 139 /**
140 * Constructor
141 *
142 * Gets necessary strings and sets relevant path information
143 */
f34488b2 144 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
dac786f3 145 global $CFG, $COURSE;
516cf3eb 146
147 $this->tab = str_repeat('&nbsp;', $this->tabsize);
148
149 $this->str->course = get_string('course');
150 $this->str->category = get_string('category', 'quiz');
151 $this->str->categoryinfo = get_string('categoryinfo', 'quiz');
152 $this->str->questions = get_string('questions', 'quiz');
153 $this->str->add = get_string('add');
154 $this->str->delete = get_string('delete');
155 $this->str->moveup = get_string('moveup');
156 $this->str->movedown = get_string('movedown');
157 $this->str->edit = get_string('editthiscategory');
158 $this->str->hide = get_string('hide');
159 $this->str->publish = get_string('publish', 'quiz');
160 $this->str->order = get_string('order');
161 $this->str->parent = get_string('parent', 'quiz');
162 $this->str->add = get_string('add');
163 $this->str->action = get_string('action');
164 $this->str->top = get_string('top', 'quiz');
165 $this->str->addcategory = get_string('addcategory', 'quiz');
166 $this->str->editcategory = get_string('editcategory', 'quiz');
167 $this->str->cancel = get_string('cancel');
168 $this->str->editcategories = get_string('editcategories', 'quiz');
2befe778 169 $this->str->page = get_string('page');
516cf3eb 170 $this->pixpath = $CFG->pixpath;
171
986effb6 172 $this->pageurl = $pageurl;
271e6dec 173
174 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
516cf3eb 175
516cf3eb 176 }
271e6dec 177
178
179
180 /**
181 * Initializes this classes general category-related variables
182 */
f34488b2 183 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
271e6dec 184 $lastlist = null;
185 foreach ($contexts as $context){
186 $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context);
187 $this->editlists[$context->id]->lastlist =& $lastlist;
188 if ($lastlist!== null){
189 $lastlist->nextlist =& $this->editlists[$context->id];
190 }
191 $lastlist =& $this->editlists[$context->id];
192 }
193
194 $count = 1;
195 $paged = false;
196 foreach ($this->editlists as $key => $list){
20f500dc 197 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
271e6dec 198 }
199 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
200 if (!$currentcat){
201 $this->catform->set_data(array('parent'=>$defaultcategory));
202 }
203 }
bc649d80 204 /**
205 * Displays the user interface
206 *
bc649d80 207 */
f34488b2 208 public function display_user_interface() {
dac786f3 209
210 /// Interface for editing existing categories
271e6dec 211 $this->output_edit_lists();
dac786f3 212
516cf3eb 213
dac786f3 214 echo '<br />';
516cf3eb 215 /// Interface for adding a new category:
516cf3eb 216 $this->output_new_table();
217 echo '<br />';
218
516cf3eb 219 }
220
bc649d80 221 /**
222 * Outputs a table to allow entry of a new category
223 */
f34488b2 224 public function output_new_table() {
271e6dec 225 $this->catform->display();
516cf3eb 226 }
227
dac786f3 228
bc649d80 229 /**
dac786f3 230 * Outputs a list to allow editing/rearranging of existing categories
bc649d80 231 *
232 * $this->initialize() must have already been called
233 *
bc649d80 234 */
f34488b2 235 public function output_edit_lists() {
35241c76 236 print_heading_with_help(get_string('editcategories', 'quiz'), 'categories', 'question');
271e6dec 237 foreach ($this->editlists as $context => $list){
238 $listhtml = $list->to_html(0, array('str'=>$this->str));
239 if ($listhtml){
9fc523e0 240 print_box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
271e6dec 241 print_heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), '', 3);
271e6dec 242 echo $listhtml;
243 print_box_end();
244 }
245 }
246 echo $list->display_page_numbers();
247 }
516cf3eb 248
dac786f3 249
250
bc649d80 251 /**
252 * gets all the courseids for the given categories
253 *
254 * @param array categories contains category objects in a tree representation
255 * @return array courseids flat array in form categoryid=>courseid
256 */
f34488b2 257 public function get_course_ids($categories) {
516cf3eb 258 $courseids = array();
259 foreach ($categories as $key=>$cat) {
260 $courseids[$key] = $cat->course;
261 if (!empty($cat->children)) {
262 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
263 }
264 }
265 return $courseids;
266 }
267
516cf3eb 268
516cf3eb 269
f34488b2 270 public function edit_single_category($categoryid) {
516cf3eb 271 /// Interface for adding a new category
f34488b2 272 global $COURSE, $DB;
516cf3eb 273 /// Interface for editing existing categories
f34488b2 274 if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) {
516cf3eb 275
271e6dec 276 $category->parent = "$category->parent,$category->contextid";
277 $category->submitbutton = get_string('savechanges');
278 $category->categoryheader = $this->str->edit;
279 $this->catform->set_data($category);
280 $this->catform->display();
281 } else {
64e71d27 282 print_error('invalidcategory', '', '', $categoryid);
516cf3eb 283 }
516cf3eb 284 }
285
516cf3eb 286
bc649d80 287 /**
288 * Sets the viable parents
289 *
290 * Viable parents are any except for the category itself, or any of it's descendants
291 * The parentstrings parameter is passed by reference and changed by this function.
292 *
293 * @param array parentstrings a list of parentstrings
294 * @param object category
295 */
f34488b2 296 public function set_viable_parents(&$parentstrings, $category) {
516cf3eb 297
298 unset($parentstrings[$category->id]);
299 if (isset($category->children)) {
300 foreach ($category->children as $child) {
301 $this->set_viable_parents($parentstrings, $child);
302 }
303 }
304 }
305
bc649d80 306 /**
307 * Gets question categories
308 *
309 * @param int parent - if given, restrict records to those with this parent id.
310 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
311 * @return array categories
312 */
f34488b2 313 public function get_question_categories($parent=null, $sort="sortorder ASC") {
314 global $COURSE, $DB;
516cf3eb 315 if (is_null($parent)) {
f34488b2 316 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort);
516cf3eb 317 } else {
f34488b2 318 $select = "parent = ? AND course = ?";
319 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort);
516cf3eb 320 }
321 return $categories;
322 }
323
bc649d80 324 /**
325 * Deletes an existing question category
326 *
327 * @param int deletecat id of category to delete
bc649d80 328 */
f34488b2 329 public function delete_category($categoryid) {
330 global $CFG, $DB;
271e6dec 331 question_can_delete_cat($categoryid);
f34488b2 332 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
64e71d27 333 print_error('unknowcategory');
516cf3eb 334 }
516cf3eb 335 /// Send the children categories to live with their grandparent
f34488b2 336 if (!$DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id))) {
64e71d27 337 print_error('cannotupdatesubcate', 'question');
516cf3eb 338 }
339
340 /// Finally delete the category itself
f34488b2 341 if ($DB->delete_records("question_categories", array("id" => $category->id))) {
6ba65fa0 342 notify(get_string("categorydeleted", "quiz", format_string($category->name)), 'notifysuccess');
986effb6 343 redirect($this->pageurl->out());//always redirect after successful action
516cf3eb 344 }
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){
271e6dec 353 $vars = new stdClass;
354 $vars->name = $category->name;
355 $vars->count = $questionsincategory;
356 print_simple_box(get_string("categorymove", "quiz", $vars), "center");
357 $this->moveform->display();
358 }
516cf3eb 359
f34488b2 360 public function move_questions($oldcat, $newcat){
534792cd 361 global $DB;
362 $questionids = $DB->get_records_select_menu('question', "category = ? AND (parent = 0 OR parent = id)", array($oldcat), '', 'id,1');
7fb1b88d 363 if (!question_move_questions_to_category(implode(',', array_keys($questionids)), $newcat)) {
364 print_error('errormovingquestions', 'question', $returnurl, $ids);
516cf3eb 365 }
366 }
367
bc649d80 368 /**
369 * Creates a new category with given params
370 *
bc649d80 371 */
f34488b2 372 public function add_category($newparent, $newcategory, $newinfo) {
373 global $DB;
bc649d80 374 if (empty($newcategory)) {
5a2a5331 375 print_error('categorynamecantbeblank', 'quiz');
bc649d80 376 }
271e6dec 377 list($parentid, $contextid) = explode(',', $newparent);
378 //moodle_form makes sure select element output is legal no need for further cleaning
379 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
516cf3eb 380
271e6dec 381 if ($parentid) {
f34488b2 382 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
64e71d27 383 print_error('cannotinsertquestioncatecontext', 'question', '', array($newcategory, $contextid));
516cf3eb 384 }
385 }
386
271e6dec 387 $cat = new object();
388 $cat->parent = $parentid;
389 $cat->contextid = $contextid;
516cf3eb 390 $cat->name = $newcategory;
391 $cat->info = $newinfo;
516cf3eb 392 $cat->sortorder = 999;
393 $cat->stamp = make_unique_id_code();
f34488b2 394 if (!$DB->insert_record("question_categories", $cat)) {
64e71d27 395 print_error('cannotinsertquestioncate', 'question', '', $newcategory);
516cf3eb 396 } else {
986effb6 397 redirect($this->pageurl->out());//always redirect after successful action
516cf3eb 398 }
516cf3eb 399 }
400
bc649d80 401 /**
402 * Updates an existing category with given params
403 *
bc649d80 404 */
f34488b2 405 public function update_category($updateid, $newparent, $newname, $newinfo) {
406 global $CFG, $QTYPES, $DB;
271e6dec 407 if (empty($newname)) {
5a2a5331 408 print_error('categorynamecantbeblank', 'quiz');
bc649d80 409 }
516cf3eb 410
271e6dec 411 list($parentid, $tocontextid) = explode(',', $newparent);
412
f34488b2 413 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
271e6dec 414 $fromcontext = get_context_instance_by_id($oldcat->contextid);
415 require_capability('moodle/question:managecategory', $fromcontext);
416 if ($oldcat->contextid == $tocontextid){
417 $tocontext = get_context_instance_by_id($tocontextid);
418 require_capability('moodle/question:managecategory', $tocontext);
419 }
516cf3eb 420 $cat = NULL;
421 $cat->id = $updateid;
271e6dec 422 $cat->name = $newname;
423 $cat->info = $newinfo;
424 //never move category where it is the default
f34488b2 425 if (1 != $DB->count_records_sql("SELECT count(*)
426 FROM {question_categories} c1,
427 {question_categories} c2
428 WHERE c2.id = ?
429 AND c1.contextid = c2.contextid", array($updateid))){
f59dba84 430 // If the question name has changed, rename any random questions in that category.
294ce987 431 if ($oldcat->name != $cat->name) {
f59dba84 432 $randomqname = $QTYPES[RANDOM]->question_name($cat);
f34488b2 433 $DB->set_field('question', 'name', $randomqname, array('category' => $cat->id), 'qtype', RANDOM);
f59dba84 434 // Ignore errors here. It is not a big deal if the questions are not renamed.
435 }
436
437 // Then update the category itself.
271e6dec 438 if ($oldcat->contextid == $tocontextid){ // not moving contexts
439 $cat->parent = $parentid;
f34488b2 440 if (!$DB->update_record("question_categories", $cat)) {
64e71d27 441 print_error('cannotupdatecate', 'question', $this->pageurl->out(), $newname);
271e6dec 442 } else {
443 redirect($this->pageurl->out());
444 }
445 } else {
f34488b2 446 if (!$DB->update_record("question_categories", $cat)) {
64e71d27 447 print_error('cannotupdatecate', 'question', $this->pageurl->out(), $newname);
271e6dec 448 } else {
449 redirect($CFG->wwwroot.'/question/contextmove.php?'.
450 $this->pageurl->get_query_string(array('cattomove' => $updateid,
451 'toparent'=>$newparent)));
452 }
453 }
516cf3eb 454 } else {
64e71d27 455 print_error('cannotmovecate', 'question', $this->pageurl->out(), $newname);
516cf3eb 456 }
457 }
271e6dec 458
f34488b2 459 public function move_question_from_cat_confirm($fromcat, $fromcourse, $tocat=null, $question=null){
460 global $QTYPES, $DB;
271e6dec 461 if (!$question){
462 $questions[] = $question;
463 } else {
f34488b2 464 $questions = $DB->get_records('question', array('category' => $tocat->id));
271e6dec 465 }
466 $urls = array();
467 foreach ($questions as $question){
468 $urls = array_merge($urls, $QTYPES[$question->qtype]->find_file_links_in_question($question));
469 }
470 if ($fromcourse){
471 $append = 'tocourse';
472 } else {
473 $append = 'tosite';
474 }
475 if ($tocat){
476 echo '<p>'.get_string('needtomovethesefilesincat','question').'</p>';
477 } else {
478 echo '<p>'.get_string('needtomovethesefilesinquestion','question').'</p>';
479 }
480 }
481
482
483
484
516cf3eb 485}
486
487?>