MDL-20636 Fix new stdClass -> stdClass(), and trailing whitespace.
[moodle.git] / question / category_class.php
CommitLineData
aeb15530 1<?php
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
94dbfb3a
TH
13require_once($CFG->libdir . '/listlib.php');
14require_once($CFG->dirroot . '/question/category_form.php');
271e6dec 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;
c65921d4 30 public $sortby = 'parent, sortorder, name';
271e6dec 31
20d89122
TH
32 public function __construct($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){
33 parent::__construct('ul', '', $editable, $pageurl, $page, 'cpage', $itemsperpage);
271e6dec 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 }
dac786f3 40}
41
42class question_category_list_item extends list_item {
f34488b2 43 public function set_icon_html($first, $last, &$lastitem){
271e6dec 44 global $CFG;
45 $category = $this->item;
8afba50b
PS
46 $url = new moodle_url('/question/category.php', ($this->parentlist->pageurl->params() + array('edit'=>$category->id)));
47 $this->icons['edit']= $this->image_icon(get_string('editthiscategory', 'question'), $url, 'edit');
271e6dec 48 parent::set_icon_html($first, $last, $lastitem);
49 $toplevel = ($this->parentlist->parentitem === null);//this is a top level item
50 if (($this->parentlist->nextlist !== null) && $last && $toplevel && (count($this->parentlist->items)>1)){
8afba50b 51 $url = new moodle_url($this->parentlist->pageurl, array('movedowncontext'=>$this->id, 'tocontext'=>$this->parentlist->nextlist->context->id, 'sesskey'=>sesskey()));
f34488b2 52 $this->icons['down'] = $this->image_icon(
8afba50b 53 get_string('shareincontext', 'question', print_context_name($this->parentlist->nextlist->context)), $url, 'down');
271e6dec 54 }
55 if (($this->parentlist->lastlist !== null) && $first && $toplevel && (count($this->parentlist->items)>1)){
8afba50b 56 $url = new moodle_url($this->parentlist->pageurl, array('moveupcontext'=>$this->id, 'tocontext'=>$this->parentlist->lastlist->context->id, 'sesskey'=>sesskey()));
f34488b2 57 $this->icons['up'] = $this->image_icon(
8afba50b 58 get_string('shareincontext', 'question', print_context_name($this->parentlist->lastlist->context)), $url, 'up');
271e6dec 59 }
60 }
20d89122 61
f34488b2 62 public function item_html($extraargs = array()){
42d5737a 63 global $CFG, $OUTPUT;
dac786f3 64 $str = $extraargs['str'];
65 $category = $this->item;
66
271e6dec 67 $editqestions = get_string('editquestions', 'quiz');
dac786f3 68
69 /// Each section adds html to be displayed as part of this list item
8afba50b 70 $questionbankurl = new moodle_url("/question/edit.php", ($this->parentlist->pageurl->params() + array('category'=>"$category->id,$category->contextid")));
5d548d3e 71 $catediturl = $this->parentlist->pageurl->out(true, array('edit' => $this->id));
6e4ca69a 72 $item = "<b><a title=\"{$str->edit}\" href=\"$catediturl\">".$category->name ."</a></b> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount.')</a>';
dac786f3 73
74 $item .= '&nbsp;'. $category->info;
75
5d548d3e
TH
76 // don't allow delete if this is the last category in this context.
77 if (count($this->parentlist->records) != 1) {
8afba50b 78 $item .= '<a title="' . $str->delete . '" href="'.$this->parentlist->pageurl->out(true, array('delete'=>$this->id, 'sesskey'=>sesskey())).'">
b5d0cafc 79 <img src="' . $OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="' .$str->delete. '" /></a>';
dac786f3 80 }
81
82 return $item;
dac786f3 83 }
dac786f3 84}
85
516cf3eb 86
4323d029 87/**
88 * Class representing question categories
dac786f3 89 *
4323d029 90 * @package questionbank
91 */
dc1f00de 92class question_category_object {
516cf3eb 93
94 var $str;
dac786f3 95 /**
271e6dec 96 * Nested lists to display categories.
dac786f3 97 *
271e6dec 98 * @var array
dac786f3 99 */
271e6dec 100 var $editlists = array();
516cf3eb 101 var $newtable;
102 var $tab;
103 var $tabsize = 3;
a982d582 104//------------------------------------------------------
986effb6 105 /**
106 * @var moodle_url Object representing url for this page
107 */
a982d582 108 var $pageurl;
271e6dec 109 /**
110 * @var question_category_edit_form Object representing form for adding / editing categories.
111 */
112 var $catform;
516cf3eb 113
bc649d80 114 /**
115 * Constructor
116 *
117 * Gets necessary strings and sets relevant path information
118 */
f34488b2 119 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
a5cb8d69 120 global $CFG, $COURSE, $OUTPUT;
516cf3eb 121
122 $this->tab = str_repeat('&nbsp;', $this->tabsize);
123
124 $this->str->course = get_string('course');
125 $this->str->category = get_string('category', 'quiz');
126 $this->str->categoryinfo = get_string('categoryinfo', 'quiz');
127 $this->str->questions = get_string('questions', 'quiz');
128 $this->str->add = get_string('add');
129 $this->str->delete = get_string('delete');
130 $this->str->moveup = get_string('moveup');
131 $this->str->movedown = get_string('movedown');
85edde5c 132 $this->str->edit = get_string('editthiscategory', 'question');
516cf3eb 133 $this->str->hide = get_string('hide');
134 $this->str->publish = get_string('publish', 'quiz');
135 $this->str->order = get_string('order');
136 $this->str->parent = get_string('parent', 'quiz');
137 $this->str->add = get_string('add');
138 $this->str->action = get_string('action');
139 $this->str->top = get_string('top', 'quiz');
140 $this->str->addcategory = get_string('addcategory', 'quiz');
141 $this->str->editcategory = get_string('editcategory', 'quiz');
142 $this->str->cancel = get_string('cancel');
143 $this->str->editcategories = get_string('editcategories', 'quiz');
2befe778 144 $this->str->page = get_string('page');
516cf3eb 145
986effb6 146 $this->pageurl = $pageurl;
271e6dec 147
148 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
516cf3eb 149
516cf3eb 150 }
271e6dec 151
152
153
154 /**
155 * Initializes this classes general category-related variables
156 */
f34488b2 157 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
271e6dec 158 $lastlist = null;
159 foreach ($contexts as $context){
160 $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context);
161 $this->editlists[$context->id]->lastlist =& $lastlist;
162 if ($lastlist!== null){
163 $lastlist->nextlist =& $this->editlists[$context->id];
164 }
165 $lastlist =& $this->editlists[$context->id];
166 }
167
168 $count = 1;
169 $paged = false;
170 foreach ($this->editlists as $key => $list){
20f500dc 171 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
271e6dec 172 }
173 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
174 if (!$currentcat){
175 $this->catform->set_data(array('parent'=>$defaultcategory));
176 }
177 }
bc649d80 178 /**
179 * Displays the user interface
180 *
bc649d80 181 */
f34488b2 182 public function display_user_interface() {
dac786f3 183
184 /// Interface for editing existing categories
271e6dec 185 $this->output_edit_lists();
dac786f3 186
516cf3eb 187
dac786f3 188 echo '<br />';
516cf3eb 189 /// Interface for adding a new category:
516cf3eb 190 $this->output_new_table();
191 echo '<br />';
192
516cf3eb 193 }
194
bc649d80 195 /**
196 * Outputs a table to allow entry of a new category
197 */
f34488b2 198 public function output_new_table() {
271e6dec 199 $this->catform->display();
516cf3eb 200 }
201
bc649d80 202 /**
dac786f3 203 * Outputs a list to allow editing/rearranging of existing categories
bc649d80 204 *
205 * $this->initialize() must have already been called
206 *
bc649d80 207 */
f34488b2 208 public function output_edit_lists() {
723d610c 209 global $OUTPUT;
1d58b567 210
5fcefc97 211 echo $OUTPUT->heading_with_help(get_string('editcategories', 'question'), 'editcategories', 'question');
1d58b567 212
271e6dec 213 foreach ($this->editlists as $context => $list){
214 $listhtml = $list->to_html(0, array('str'=>$this->str));
215 if ($listhtml){
beb677cd 216 echo $OUTPUT->box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
723d610c 217 echo $OUTPUT->heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), 3);
271e6dec 218 echo $listhtml;
beb677cd 219 echo $OUTPUT->box_end();
271e6dec 220 }
221 }
222 echo $list->display_page_numbers();
223 }
516cf3eb 224
dac786f3 225
226
bc649d80 227 /**
228 * gets all the courseids for the given categories
229 *
230 * @param array categories contains category objects in a tree representation
231 * @return array courseids flat array in form categoryid=>courseid
232 */
f34488b2 233 public function get_course_ids($categories) {
516cf3eb 234 $courseids = array();
235 foreach ($categories as $key=>$cat) {
236 $courseids[$key] = $cat->course;
237 if (!empty($cat->children)) {
238 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
239 }
240 }
241 return $courseids;
242 }
243
516cf3eb 244
516cf3eb 245
f34488b2 246 public function edit_single_category($categoryid) {
516cf3eb 247 /// Interface for adding a new category
f34488b2 248 global $COURSE, $DB;
516cf3eb 249 /// Interface for editing existing categories
f34488b2 250 if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) {
516cf3eb 251
271e6dec 252 $category->parent = "$category->parent,$category->contextid";
253 $category->submitbutton = get_string('savechanges');
254 $category->categoryheader = $this->str->edit;
255 $this->catform->set_data($category);
256 $this->catform->display();
257 } else {
64e71d27 258 print_error('invalidcategory', '', '', $categoryid);
516cf3eb 259 }
516cf3eb 260 }
261
516cf3eb 262
bc649d80 263 /**
264 * Sets the viable parents
265 *
266 * Viable parents are any except for the category itself, or any of it's descendants
267 * The parentstrings parameter is passed by reference and changed by this function.
268 *
269 * @param array parentstrings a list of parentstrings
270 * @param object category
271 */
f34488b2 272 public function set_viable_parents(&$parentstrings, $category) {
516cf3eb 273
274 unset($parentstrings[$category->id]);
275 if (isset($category->children)) {
276 foreach ($category->children as $child) {
277 $this->set_viable_parents($parentstrings, $child);
278 }
279 }
280 }
281
bc649d80 282 /**
283 * Gets question categories
284 *
285 * @param int parent - if given, restrict records to those with this parent id.
286 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
287 * @return array categories
288 */
f34488b2 289 public function get_question_categories($parent=null, $sort="sortorder ASC") {
290 global $COURSE, $DB;
516cf3eb 291 if (is_null($parent)) {
f34488b2 292 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id), $sort);
516cf3eb 293 } else {
f34488b2 294 $select = "parent = ? AND course = ?";
295 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id), $sort);
516cf3eb 296 }
297 return $categories;
298 }
299
bc649d80 300 /**
301 * Deletes an existing question category
302 *
21cbf9da 303 * @param int deletecat id of category to delete
bc649d80 304 */
f34488b2 305 public function delete_category($categoryid) {
306 global $CFG, $DB;
271e6dec 307 question_can_delete_cat($categoryid);
f34488b2 308 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
64e71d27 309 print_error('unknowcategory');
516cf3eb 310 }
516cf3eb 311 /// Send the children categories to live with their grandparent
bb4b6010 312 $DB->set_field("question_categories", "parent", $category->parent, array("parent" => $category->id));
516cf3eb 313
314 /// Finally delete the category itself
21cbf9da 315 $DB->delete_records("question_categories", array("id" => $category->id));
516cf3eb 316 }
21cbf9da 317
f34488b2 318 public function move_questions_and_delete_category($oldcat, $newcat){
271e6dec 319 question_can_delete_cat($oldcat);
320 $this->move_questions($oldcat, $newcat);
321 $this->delete_category($oldcat);
322 }
516cf3eb 323
f34488b2 324 public function display_move_form($questionsincategory, $category){
beb677cd 325 global $OUTPUT;
0ff4bd08 326 $vars = new stdClass();
271e6dec 327 $vars->name = $category->name;
328 $vars->count = $questionsincategory;
beb677cd 329 echo $OUTPUT->box(get_string('categorymove', 'quiz', $vars), 'generalbox boxaligncenter');
271e6dec 330 $this->moveform->display();
331 }
516cf3eb 332
f34488b2 333 public function move_questions($oldcat, $newcat){
534792cd 334 global $DB;
5d548d3e
TH
335 $questionids = $DB->get_records_select_menu('question',
336 'category = ? AND (parent = 0 OR parent = id)', array($oldcat), '', 'id,1');
337 question_move_questions_to_category($questionids, $newcat);
516cf3eb 338 }
339
bc649d80 340 /**
341 * Creates a new category with given params
bc649d80 342 */
94dbfb3a 343 public function add_category($newparent, $newcategory, $newinfo, $return = false) {
f34488b2 344 global $DB;
bc649d80 345 if (empty($newcategory)) {
5a2a5331 346 print_error('categorynamecantbeblank', 'quiz');
bc649d80 347 }
271e6dec 348 list($parentid, $contextid) = explode(',', $newparent);
349 //moodle_form makes sure select element output is legal no need for further cleaning
350 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
516cf3eb 351
271e6dec 352 if ($parentid) {
f34488b2 353 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
3e0e25ef 354 print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
516cf3eb 355 }
356 }
357
7f389342 358 $cat = new stdClass();
271e6dec 359 $cat->parent = $parentid;
360 $cat->contextid = $contextid;
516cf3eb 361 $cat->name = $newcategory;
362 $cat->info = $newinfo;
516cf3eb 363 $cat->sortorder = 999;
364 $cat->stamp = make_unique_id_code();
bb4b6010 365 $categoryid = $DB->insert_record("question_categories", $cat);
366 if ($return) {
367 return $categoryid;
516cf3eb 368 } else {
e42f153c 369 redirect($this->pageurl);//always redirect after successful action
516cf3eb 370 }
516cf3eb 371 }
372
bc649d80 373 /**
374 * Updates an existing category with given params
bc649d80 375 */
f34488b2 376 public function update_category($updateid, $newparent, $newname, $newinfo) {
f9b0500f 377 global $CFG, $DB;
271e6dec 378 if (empty($newname)) {
5a2a5331 379 print_error('categorynamecantbeblank', 'quiz');
bc649d80 380 }
516cf3eb 381
41c96651 382 // Get the record we are updating.
f34488b2 383 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
df4e2244 384 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
41c96651 385
386 if (!empty($newparent) && !$lastcategoryinthiscontext) {
387 list($parentid, $tocontextid) = explode(',', $newparent);
388 } else {
389 $parentid = $oldcat->parent;
390 $tocontextid = $oldcat->contextid;
391 }
392
393 // Check permissions.
271e6dec 394 $fromcontext = get_context_instance_by_id($oldcat->contextid);
395 require_capability('moodle/question:managecategory', $fromcontext);
41c96651 396
397 // If moving to another context, check permissions some more.
5d548d3e 398 if ($oldcat->contextid != $tocontextid) {
271e6dec 399 $tocontext = get_context_instance_by_id($tocontextid);
400 require_capability('moodle/question:managecategory', $tocontext);
401 }
41c96651 402
403 // Update the category record.
516cf3eb 404 $cat = NULL;
405 $cat->id = $updateid;
271e6dec 406 $cat->name = $newname;
407 $cat->info = $newinfo;
41c96651 408 $cat->parent = $parentid;
5d548d3e 409 $cat->contextid = $tocontextid;
bb4b6010 410 $DB->update_record('question_categories', $cat);
f59dba84 411
df4e2244 412 // If the category name has changed, rename any random questions in that category.
41c96651 413 if ($oldcat->name != $cat->name) {
3cac440b 414 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
415
f9b0500f
TH
416 $randomqtype = question_bank::get_qtype('random');
417 $randomqname = $randomqtype->question_name($cat, false);
3cac440b 418 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '0'));
419
f9b0500f 420 $randomqname = $randomqtype->question_name($cat, true);
3cac440b 421 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id, '1'));
41c96651 422 }
423
5d548d3e
TH
424 if ($oldcat->contextid != $tocontextid) {
425 // Moving to a new context. Must move files belonging to questions.
426 question_move_category_to_context($cat->id, $oldcat->contextid, $tocontextid);
516cf3eb 427 }
271e6dec 428
5d548d3e 429 redirect($this->pageurl);
271e6dec 430 }
516cf3eb 431}