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