MDL-25755 enrol ldap - avoid reserved keyword. (k) goes to Chris Myers
[moodle.git] / question / category_class.php
blob691eb621a08bbab143574f46acca4b3fdd4066b5
1 <?php // $Id$
2 /**
3 * Class representing question categories
5 * @author Martin Dougiamas and many others. {@link http://moodle.org}
6 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7 * @package questionbank
8 */
10 // number of categories to display on page
11 define("QUESTION_PAGE_LENGTH", 25);
13 require_once("$CFG->libdir/listlib.php");
14 require_once("$CFG->dirroot/question/category_form.php");
15 require_once('move_form.php');
17 class question_category_list extends moodle_list {
18 var $table = "question_categories";
19 var $listitemclassname = 'question_category_list_item';
20 /**
21 * @var reference to list displayed below this one.
23 var $nextlist = null;
24 /**
25 * @var reference to list displayed above this one.
27 var $lastlist = null;
29 var $context = null;
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;
36 function get_records() {
37 $this->records = get_categories_for_contexts($this->context->id, $this->sortby);
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;
52 $toparent = "0,{$this->context->id}";
53 redirect($CFG->wwwroot.'/question/contextmove.php?'.
54 $this->pageurl->get_query_string(compact('cattomove', 'totop', 'toparent')));
59 class question_category_list_item extends list_item {
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', 'question'),
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');
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');
78 function item_html($extraargs = array()){
79 global $CFG;
80 $pixpath = $CFG->pixpath;
81 $str = $extraargs['str'];
82 $category = $this->item;
84 $editqestions = get_string('editquestions', 'quiz');
86 /// Each section adds html to be displayed as part of this list item
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));
90 $item = "<b><a title=\"{$str->edit}\" href=\"$catediturl\">".$category->name ."</a></b> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount.')</a>';
92 $item .= '&nbsp;'. $category->info;
94 if (count($this->parentlist->records)!=1){ // don't allow delete if this is the last category in this context.
95 $item .= '<a title="' . $str->delete . '" href="'.$this->parentlist->pageurl->out_action(array('delete'=>$this->id)).'">
96 <img src="' . $pixpath . '/t/delete.gif" class="iconsmall" alt="' .$str->delete. '" /></a>';
99 return $item;
106 * Class representing question categories
108 * @package questionbank
110 class question_category_object {
112 var $str;
113 var $pixpath;
115 * Nested lists to display categories.
117 * @var array
119 var $editlists = array();
120 var $newtable;
121 var $tab;
122 var $tabsize = 3;
123 //------------------------------------------------------
125 * @var moodle_url Object representing url for this page
127 var $pageurl;
129 * @var question_category_edit_form Object representing form for adding / editing categories.
131 var $catform;
134 * Constructor
136 * Gets necessary strings and sets relevant path information
138 function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
139 global $CFG, $COURSE;
141 $this->tab = str_repeat('&nbsp;', $this->tabsize);
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', 'question');
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');
163 $this->str->page = get_string('page');
164 $this->pixpath = $CFG->pixpath;
166 $this->pageurl = $pageurl;
168 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
175 * Initializes this classes general category-related variables
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];
185 $lastlist =& $this->editlists[$context->id];
188 $count = 1;
189 $paged = false;
190 foreach ($this->editlists as $key => $list){
191 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
193 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
194 if (!$currentcat){
195 $this->catform->set_data(array('parent'=>$defaultcategory));
199 * Displays the user interface
202 function display_user_interface() {
204 /// Interface for editing existing categories
205 $this->output_edit_lists();
208 echo '<br />';
209 /// Interface for adding a new category:
210 $this->output_new_table();
211 echo '<br />';
216 * Outputs a table to allow entry of a new category
218 function output_new_table() {
219 $this->catform->display();
224 * Outputs a list to allow editing/rearranging of existing categories
226 * $this->initialize() must have already been called
229 function output_edit_lists() {
230 print_heading_with_help(get_string('editcategories', 'quiz'), 'categories', 'question');
231 foreach ($this->editlists as $context => $list){
232 $listhtml = $list->to_html(0, array('str'=>$this->str));
233 if ($listhtml){
234 print_box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context->contextlevel);
235 print_heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), '', 3);
236 echo $listhtml;
237 print_box_end();
240 echo $list->display_page_numbers();
246 * gets all the courseids for the given categories
248 * @param array categories contains category objects in a tree representation
249 * @return array courseids flat array in form categoryid=>courseid
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));
259 return $courseids;
264 function edit_single_category($categoryid) {
265 /// Interface for adding a new category
266 global $COURSE;
267 /// Interface for editing existing categories
268 if ($category = get_record("question_categories", "id", $categoryid)) {
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 {
276 error("Category $categoryid not found");
282 * Sets the viable parents
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.
287 * @param array parentstrings a list of parentstrings
288 * @param object category
290 function set_viable_parents(&$parentstrings, $category) {
292 unset($parentstrings[$category->id]);
293 if (isset($category->children)) {
294 foreach ($category->children as $child) {
295 $this->set_viable_parents($parentstrings, $child);
301 * Gets question categories
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
307 function get_question_categories($parent=null, $sort="sortorder ASC") {
308 global $COURSE;
309 if (is_null($parent)) {
310 $categories = get_records('question_categories', 'course', "{$COURSE->id}", $sort);
311 } else {
312 $select = "parent = '$parent' AND course = '{$COURSE->id}'";
313 $categories = get_records_select('question_categories', $select, $sort);
315 return $categories;
319 * Deletes an existing question category
321 * @param int deletecat id of category to delete
323 function delete_category($categoryid) {
324 global $CFG;
325 question_can_delete_cat($categoryid);
326 if (!$category = get_record("question_categories", "id", $categoryid)) { // security
327 error("No such category $cat!", $this->pageurl->out());
329 /// Send the children categories to live with their grandparent
330 if (!set_field("question_categories", "parent", $category->parent, "parent", $category->id)) {
331 error("Could not update a child category!", $this->pageurl->out());
334 /// Finally delete the category itself
335 delete_records("question_categories", "id", $category->id);
337 function move_questions_and_delete_category($oldcat, $newcat){
338 question_can_delete_cat($oldcat);
339 $this->move_questions($oldcat, $newcat);
340 $this->delete_category($oldcat);
343 function display_move_form($questionsincategory, $category){
344 $vars = new stdClass;
345 $vars->name = $category->name;
346 $vars->count = $questionsincategory;
347 print_simple_box(get_string("categorymove", "quiz", $vars), "center");
348 $this->moveform->display();
351 function move_questions($oldcat, $newcat){
352 $questionids = get_records_select_menu('question', "category = $oldcat AND (parent = 0 OR parent = id)", '', 'id,1');
353 if (!question_move_questions_to_category(implode(',', array_keys($questionids)), $newcat)) {
354 print_error('errormovingquestions', 'question', $returnurl, $ids);
359 * Creates a new category with given params
362 function add_category($newparent, $newcategory, $newinfo) {
363 if (empty($newcategory)) {
364 print_error('categorynamecantbeblank', 'quiz');
366 list($parentid, $contextid) = explode(',', $newparent);
367 //moodle_form makes sure select element output is legal no need for further cleaning
368 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
370 if ($parentid) {
371 if(!(get_field('question_categories', 'contextid', 'id', $parentid) == $contextid)) {
372 error("Could not insert the new question category '$newcategory' illegal contextid '$contextid'.");
376 $cat = new object();
377 $cat->parent = $parentid;
378 $cat->contextid = $contextid;
379 $cat->name = $newcategory;
380 $cat->info = $newinfo;
381 $cat->sortorder = 999;
382 $cat->stamp = make_unique_id_code();
383 if (!insert_record("question_categories", $cat)) {
384 error("Could not insert the new question category '$newcategory'");
385 } else {
386 redirect($this->pageurl->out());//always redirect after successful action
391 * Updates an existing category with given params
393 function update_category($updateid, $newparent, $newname, $newinfo) {
394 global $CFG, $QTYPES;
395 if (empty($newname)) {
396 print_error('categorynamecantbeblank', 'quiz');
399 // Get the record we are updating.
400 $oldcat = get_record('question_categories', 'id', $updateid);
401 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
403 if (!empty($newparent) && !$lastcategoryinthiscontext) {
404 list($parentid, $tocontextid) = explode(',', $newparent);
405 } else {
406 $parentid = $oldcat->parent;
407 $tocontextid = $oldcat->contextid;
410 // Check permissions.
411 $fromcontext = get_context_instance_by_id($oldcat->contextid);
412 require_capability('moodle/question:managecategory', $fromcontext);
414 // If moving to another context, check permissions some more.
415 if ($oldcat->contextid != $tocontextid){
416 $tocontext = get_context_instance_by_id($tocontextid);
417 require_capability('moodle/question:managecategory', $tocontext);
420 // Update the category record.
421 $cat = NULL;
422 $cat->id = $updateid;
423 $cat->name = $newname;
424 $cat->info = $newinfo;
425 $cat->parent = $parentid;
426 // We don't change $cat->contextid here, if necessary we redirect to contextmove.php later.
427 if (!update_record("question_categories", $cat)) {
428 error("Could not update the category '$newname'", $this->pageurl->out());
431 // If the category name has changed, rename any random questions in that category.
432 if (addslashes($oldcat->name) != $cat->name) {
433 $randomqname = $QTYPES[RANDOM]->question_name($cat);
434 set_field('question', 'name', addslashes($randomqname), 'category', $cat->id, 'qtype', RANDOM);
435 // Ignore errors here. It is not a big deal if the questions are not renamed.
438 // Then redirect to an appropriate place.
439 if ($oldcat->contextid == $tocontextid) { // not moving contexts
440 redirect($this->pageurl->out());
441 } else {
442 redirect($CFG->wwwroot.'/question/contextmove.php?' .
443 $this->pageurl->get_query_string(array(
444 'cattomove' => $updateid, 'toparent'=>$newparent)));
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);
455 $urls = array();
456 foreach ($questions as $question){
457 $urls = array_merge($urls, $QTYPES[$question->qtype]->find_file_links_in_question($question));
459 if ($fromcourse){
460 $append = 'tocourse';
461 } else {
462 $append = 'tosite';
464 if ($tocat){
465 echo '<p>'.get_string('needtomovethesefilesincat','question').'</p>';
466 } else {
467 echo '<p>'.get_string('needtomovethesefilesinquestion','question').'</p>';