web service MDL-12886
[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;
271e6dec 31
f34488b2 32 public function question_category_list($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){
271e6dec 33 parent::moodle_list('ul', '', $editable, $pageurl, $page, 'cpage', $itemsperpage);
34 $this->context = $context;
35 }
986effb6 36
f34488b2 37 public function get_records() {
271e6dec 38 $this->records = get_categories_for_contexts($this->context->id, $this->sortby);
39 }
f34488b2 40 public function process_actions($left, $right, $moveup, $movedown, $moveupcontext, $movedowncontext, $tocontext){
271e6dec 41 global $CFG;
42 //parent::procces_actions redirects after any action
43 parent::process_actions($left, $right, $moveup, $movedown);
44 if ($tocontext == $this->context->id){
45 //only called on toplevel list
46 if ($moveupcontext){
47 $cattomove = $moveupcontext;
48 $totop = 0;
49 } elseif ($movedowncontext){
50 $cattomove = $movedowncontext;
51 $totop = 1;
dac786f3 52 }
271e6dec 53 $toparent = "0,{$this->context->id}";
54 redirect($CFG->wwwroot.'/question/contextmove.php?'.
55 $this->pageurl->get_query_string(compact('cattomove', 'totop', 'toparent')));
dac786f3 56 }
dac786f3 57 }
58}
59
60class question_category_list_item extends list_item {
61
62
f34488b2 63 public function set_icon_html($first, $last, &$lastitem){
271e6dec 64 global $CFG;
65 $category = $this->item;
66 $this->icons['edit']= $this->image_icon(get_string('editthiscategory'),
67 "{$CFG->wwwroot}/question/category.php?".$this->parentlist->pageurl->get_query_string(array('edit'=>$category->id)), 'edit');
68 parent::set_icon_html($first, $last, $lastitem);
69 $toplevel = ($this->parentlist->parentitem === null);//this is a top level item
70 if (($this->parentlist->nextlist !== null) && $last && $toplevel && (count($this->parentlist->items)>1)){
f34488b2 71 $this->icons['down'] = $this->image_icon(
72 get_string('shareincontext', 'question', print_context_name($this->parentlist->nextlist->context)),
73 $this->parentlist->pageurl->out_action(
74 array('movedowncontext'=>$this->id, 'tocontext'=>$this->parentlist->nextlist->context->id)
75 ), 'down');
271e6dec 76 }
77 if (($this->parentlist->lastlist !== null) && $first && $toplevel && (count($this->parentlist->items)>1)){
f34488b2 78 $this->icons['up'] = $this->image_icon(
79 get_string('shareincontext', 'question', print_context_name($this->parentlist->lastlist->context)),
80 $this->parentlist->pageurl->out_action(
81 array('moveupcontext'=>$this->id, 'tocontext'=>$this->parentlist->lastlist->context->id)
82 ), 'up');
271e6dec 83 }
84 }
f34488b2 85 public function item_html($extraargs = array()){
dac786f3 86 global $CFG;
87 $pixpath = $CFG->pixpath;
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)).'">
6e4ca69a 103 <img src="' . $pixpath . '/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;
120 var $pixpath;
dac786f3 121 /**
271e6dec 122 * Nested lists to display categories.
dac786f3 123 *
271e6dec 124 * @var array
dac786f3 125 */
271e6dec 126 var $editlists = array();
516cf3eb 127 var $newtable;
128 var $tab;
129 var $tabsize = 3;
a982d582 130//------------------------------------------------------
986effb6 131 /**
132 * @var moodle_url Object representing url for this page
133 */
a982d582 134 var $pageurl;
271e6dec 135 /**
136 * @var question_category_edit_form Object representing form for adding / editing categories.
137 */
138 var $catform;
fa583f5f 139 /**
140 * @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.
141 */
142 var $catform_rand;
516cf3eb 143
bc649d80 144 /**
145 * Constructor
146 *
147 * Gets necessary strings and sets relevant path information
148 */
f34488b2 149 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
dac786f3 150 global $CFG, $COURSE;
516cf3eb 151
152 $this->tab = str_repeat('&nbsp;', $this->tabsize);
153
154 $this->str->course = get_string('course');
155 $this->str->category = get_string('category', 'quiz');
156 $this->str->categoryinfo = get_string('categoryinfo', 'quiz');
157 $this->str->questions = get_string('questions', 'quiz');
158 $this->str->add = get_string('add');
159 $this->str->delete = get_string('delete');
160 $this->str->moveup = get_string('moveup');
161 $this->str->movedown = get_string('movedown');
162 $this->str->edit = get_string('editthiscategory');
163 $this->str->hide = get_string('hide');
164 $this->str->publish = get_string('publish', 'quiz');
165 $this->str->order = get_string('order');
166 $this->str->parent = get_string('parent', 'quiz');
167 $this->str->add = get_string('add');
168 $this->str->action = get_string('action');
169 $this->str->top = get_string('top', 'quiz');
170 $this->str->addcategory = get_string('addcategory', 'quiz');
171 $this->str->editcategory = get_string('editcategory', 'quiz');
172 $this->str->cancel = get_string('cancel');
173 $this->str->editcategories = get_string('editcategories', 'quiz');
2befe778 174 $this->str->page = get_string('page');
516cf3eb 175 $this->pixpath = $CFG->pixpath;
176
986effb6 177 $this->pageurl = $pageurl;
271e6dec 178
179 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
516cf3eb 180
516cf3eb 181 }
271e6dec 182
183
184
185 /**
186 * Initializes this classes general category-related variables
187 */
f34488b2 188 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
271e6dec 189 $lastlist = null;
190 foreach ($contexts as $context){
191 $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context);
192 $this->editlists[$context->id]->lastlist =& $lastlist;
193 if ($lastlist!== null){
194 $lastlist->nextlist =& $this->editlists[$context->id];
195 }
196 $lastlist =& $this->editlists[$context->id];
197 }
198
199 $count = 1;
200 $paged = false;
201 foreach ($this->editlists as $key => $list){
20f500dc 202 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
271e6dec 203 }
204 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
fa583f5f 205 $this->catform_rand = new question_category_edit_form_randomquestion($this->pageurl, compact('contexts', 'currentcat'));
271e6dec 206 if (!$currentcat){
207 $this->catform->set_data(array('parent'=>$defaultcategory));
fa583f5f 208 $this->catform_rand->set_data(array('parent'=>$defaultcategory));
271e6dec 209 }
210 }
bc649d80 211 /**
212 * Displays the user interface
213 *
bc649d80 214 */
f34488b2 215 public function display_user_interface() {
dac786f3 216
217 /// Interface for editing existing categories
271e6dec 218 $this->output_edit_lists();
dac786f3 219
516cf3eb 220
dac786f3 221 echo '<br />';
516cf3eb 222 /// Interface for adding a new category:
516cf3eb 223 $this->output_new_table();
224 echo '<br />';
225
fa583f5f 226 }
227 /**
228 * Displays the user interface
229 *
230 */
4070210d 231 function display_randomquestion_user_interface($addonpage=0) {
5c8505d0 232 $this->catform_rand->set_data(array('addonpage'=>$addonpage));
fa583f5f 233 /// Interface for adding a new category:
234 $this->output_new_randomquestion_table();
235
516cf3eb 236 }
237
bc649d80 238 /**
239 * Outputs a table to allow entry of a new category
240 */
f34488b2 241 public function output_new_table() {
271e6dec 242 $this->catform->display();
516cf3eb 243 }
244
fa583f5f 245 /**
246 * Outputs a table to allow entry of a new category
247 */
248 function output_new_randomquestion_table() {
249 $this->catform_rand->display();
250 }
251
dac786f3 252
bc649d80 253 /**
dac786f3 254 * Outputs a list to allow editing/rearranging of existing categories
bc649d80 255 *
256 * $this->initialize() must have already been called
257 *
bc649d80 258 */
f34488b2 259 public function output_edit_lists() {
35241c76 260 print_heading_with_help(get_string('editcategories', 'quiz'), 'categories', 'question');
271e6dec 261 foreach ($this->editlists as $context => $list){
262 $listhtml = $list->to_html(0, array('str'=>$this->str));
263 if ($listhtml){
9fc523e0 264 print_box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
271e6dec 265 print_heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), '', 3);
271e6dec 266 echo $listhtml;
267 print_box_end();
268 }
269 }
270 echo $list->display_page_numbers();
271 }
516cf3eb 272
dac786f3 273
274
bc649d80 275 /**
276 * gets all the courseids for the given categories
277 *
278 * @param array categories contains category objects in a tree representation
279 * @return array courseids flat array in form categoryid=>courseid
280 */
f34488b2 281 public function get_course_ids($categories) {
516cf3eb 282 $courseids = array();
283 foreach ($categories as $key=>$cat) {
284 $courseids[$key] = $cat->course;
285 if (!empty($cat->children)) {
286 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
287 }
288 }
289 return $courseids;
290 }
291
516cf3eb 292
516cf3eb 293
f34488b2 294 public function edit_single_category($categoryid) {
516cf3eb 295 /// Interface for adding a new category
f34488b2 296 global $COURSE, $DB;
516cf3eb 297 /// Interface for editing existing categories
f34488b2 298 if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) {
516cf3eb 299
271e6dec 300 $category->parent = "$category->parent,$category->contextid";
301 $category->submitbutton = get_string('savechanges');
302 $category->categoryheader = $this->str->edit;
303 $this->catform->set_data($category);
304 $this->catform->display();
305 } else {
64e71d27 306 print_error('invalidcategory', '', '', $categoryid);
516cf3eb 307 }
516cf3eb 308 }
309
516cf3eb 310
bc649d80 311 /**
312 * Sets the viable parents
313 *
314 * Viable parents are any except for the category itself, or any of it's descendants
315 * The parentstrings parameter is passed by reference and changed by this function.
316 *
317 * @param array parentstrings a list of parentstrings
318 * @param object category
319 */
f34488b2 320 public function set_viable_parents(&$parentstrings, $category) {
516cf3eb 321
322 unset($parentstrings[$category->id]);
323 if (isset($category->children)) {
324 foreach ($category->children as $child) {
325 $this->set_viable_parents($parentstrings, $child);
326 }
327 }
328 }
329
bc649d80 330 /**
331 * Gets question categories
332 *
333 * @param int parent - if given, restrict records to those with this parent id.
334 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
335 * @return array categories
336 */
f34488b2 337 public function get_question_categories($parent=null, $sort="sortorder ASC") {
338 global $COURSE, $DB;
516cf3eb 339 if (is_null($parent)) {
f34488b2 340 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort);
516cf3eb 341 } else {
f34488b2 342 $select = "parent = ? AND course = ?";
343 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort);
516cf3eb 344 }
345 return $categories;
346 }
347
bc649d80 348 /**
349 * Deletes an existing question category
350 *
21cbf9da 351 * @param int deletecat id of category to delete
bc649d80 352 */
f34488b2 353 public function delete_category($categoryid) {
354 global $CFG, $DB;
271e6dec 355 question_can_delete_cat($categoryid);
f34488b2 356 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
64e71d27 357 print_error('unknowcategory');
516cf3eb 358 }
516cf3eb 359 /// Send the children categories to live with their grandparent
f34488b2 360 if (!$DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id))) {
64e71d27 361 print_error('cannotupdatesubcate', 'question');
516cf3eb 362 }
363
364 /// Finally delete the category itself
21cbf9da 365 $DB->delete_records("question_categories", array("id" => $category->id));
516cf3eb 366 }
21cbf9da 367
f34488b2 368 public function move_questions_and_delete_category($oldcat, $newcat){
271e6dec 369 question_can_delete_cat($oldcat);
370 $this->move_questions($oldcat, $newcat);
371 $this->delete_category($oldcat);
372 }
516cf3eb 373
f34488b2 374 public function display_move_form($questionsincategory, $category){
271e6dec 375 $vars = new stdClass;
376 $vars->name = $category->name;
377 $vars->count = $questionsincategory;
378 print_simple_box(get_string("categorymove", "quiz", $vars), "center");
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();
fa583f5f 416 if (!$categoryid=$DB->insert_record("question_categories", $cat)) {
64e71d27 417 print_error('cannotinsertquestioncate', 'question', '', $newcategory);
516cf3eb 418 } else {
fa583f5f 419 if($return){
420 return $categoryid;
421 }else{
422 redirect($this->pageurl->out());//always redirect after successful action
423 }
516cf3eb 424 }
516cf3eb 425 }
426
bc649d80 427 /**
428 * Updates an existing category with given params
bc649d80 429 */
f34488b2 430 public function update_category($updateid, $newparent, $newname, $newinfo) {
431 global $CFG, $QTYPES, $DB;
271e6dec 432 if (empty($newname)) {
5a2a5331 433 print_error('categorynamecantbeblank', 'quiz');
bc649d80 434 }
516cf3eb 435
41c96651 436 // Get the record we are updating.
f34488b2 437 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
df4e2244 438 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
41c96651 439
440 if (!empty($newparent) && !$lastcategoryinthiscontext) {
441 list($parentid, $tocontextid) = explode(',', $newparent);
442 } else {
443 $parentid = $oldcat->parent;
444 $tocontextid = $oldcat->contextid;
445 }
446
447 // Check permissions.
271e6dec 448 $fromcontext = get_context_instance_by_id($oldcat->contextid);
449 require_capability('moodle/question:managecategory', $fromcontext);
41c96651 450
451 // If moving to another context, check permissions some more.
452 if ($oldcat->contextid != $tocontextid){
271e6dec 453 $tocontext = get_context_instance_by_id($tocontextid);
454 require_capability('moodle/question:managecategory', $tocontext);
455 }
41c96651 456
457 // Update the category record.
516cf3eb 458 $cat = NULL;
459 $cat->id = $updateid;
271e6dec 460 $cat->name = $newname;
461 $cat->info = $newinfo;
41c96651 462 $cat->parent = $parentid;
463 // We don't change $cat->contextid here, if necessary we redirect to contextmove.php later.
464 if (!$DB->update_record('question_categories', $cat)) {
465 print_error('cannotupdatecate', 'question', $this->pageurl->out(), $newname);
466 }
f59dba84 467
df4e2244 468 // If the category name has changed, rename any random questions in that category.
41c96651 469 if ($oldcat->name != $cat->name) {
470 $randomqname = $QTYPES[RANDOM]->question_name($cat);
471 $DB->set_field('question', 'name', $randomqname, array('category' => $cat->id), 'qtype', RANDOM);
472 // Ignore errors here. It is not a big deal if the questions are not renamed.
473 }
474
475 // Then redirect to an appropriate place.
476 if ($oldcat->contextid == $tocontextid) { // not moving contexts
477 redirect($this->pageurl->out());
516cf3eb 478 } else {
41c96651 479 redirect($CFG->wwwroot.'/question/contextmove.php?' .
480 $this->pageurl->get_query_string(array(
481 'cattomove' => $updateid, 'toparent'=>$newparent)));
516cf3eb 482 }
483 }
271e6dec 484
f34488b2 485 public function move_question_from_cat_confirm($fromcat, $fromcourse, $tocat=null, $question=null){
486 global $QTYPES, $DB;
271e6dec 487 if (!$question){
488 $questions[] = $question;
489 } else {
f34488b2 490 $questions = $DB->get_records('question', array('category' => $tocat->id));
271e6dec 491 }
492 $urls = array();
493 foreach ($questions as $question){
494 $urls = array_merge($urls, $QTYPES[$question->qtype]->find_file_links_in_question($question));
495 }
496 if ($fromcourse){
497 $append = 'tocourse';
498 } else {
499 $append = 'tosite';
500 }
501 if ($tocat){
502 echo '<p>'.get_string('needtomovethesefilesincat','question').'</p>';
503 } else {
504 echo '<p>'.get_string('needtomovethesefilesinquestion','question').'</p>';
505 }
506 }
507
508
509
510
516cf3eb 511}
512
513?>