MDL-9636 corrected the creation of new manual grade items, added source parameter
[moodle-pu.git] / question / category_class.php
blobb0e10bd67eb7f6dc70857e70a44b8ab871085f97
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'),
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 = "<a title=\"{$str->edit}\" href=\"$catediturl\">".$category->name ."</a> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount.')</a>';
92 $item .= '&nbsp;'. $category->info;
95 if (count($this->parentlist->records)!=1){ // don't allow delete if this is the last category in this context.
96 $item .= '<a title="' . $str->delete . '" href="'.$this->parentlist->pageurl->out_action(array('delete'=>$this->id)).'">
97 <img src="' . $pixpath . '/t/delete.gif" class="iconsmall" alt="' .$str->delete. '" /></a> ';
100 return $item;
109 * Class representing question categories
111 * @package questionbank
113 class question_category_object {
115 var $str;
116 var $pixpath;
118 * Nested lists to display categories.
120 * @var array
122 var $editlists = array();
123 var $newtable;
124 var $tab;
125 var $tabsize = 3;
126 //------------------------------------------------------
128 * @var moodle_url Object representing url for this page
130 var $pageurl;
132 * @var question_category_edit_form Object representing form for adding / editing categories.
134 var $catform;
137 * Constructor
139 * Gets necessary strings and sets relevant path information
141 function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
142 global $CFG, $COURSE;
144 $this->tab = str_repeat('&nbsp;', $this->tabsize);
146 $this->str->course = get_string('course');
147 $this->str->category = get_string('category', 'quiz');
148 $this->str->categoryinfo = get_string('categoryinfo', 'quiz');
149 $this->str->questions = get_string('questions', 'quiz');
150 $this->str->add = get_string('add');
151 $this->str->delete = get_string('delete');
152 $this->str->moveup = get_string('moveup');
153 $this->str->movedown = get_string('movedown');
154 $this->str->edit = get_string('editthiscategory');
155 $this->str->hide = get_string('hide');
156 $this->str->publish = get_string('publish', 'quiz');
157 $this->str->order = get_string('order');
158 $this->str->parent = get_string('parent', 'quiz');
159 $this->str->add = get_string('add');
160 $this->str->action = get_string('action');
161 $this->str->top = get_string('top', 'quiz');
162 $this->str->addcategory = get_string('addcategory', 'quiz');
163 $this->str->editcategory = get_string('editcategory', 'quiz');
164 $this->str->cancel = get_string('cancel');
165 $this->str->editcategories = get_string('editcategories', 'quiz');
166 $this->str->page = get_string('page');
167 $this->pixpath = $CFG->pixpath;
169 $this->pageurl = $pageurl;
171 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
178 * Initializes this classes general category-related variables
180 function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
181 $lastlist = null;
182 foreach ($contexts as $context){
183 $this->editlists[$context->id] = new question_category_list('ul', '', true, $this->pageurl, $page, 'cpage', QUESTION_PAGE_LENGTH, $context);
184 $this->editlists[$context->id]->lastlist =& $lastlist;
185 if ($lastlist!== null){
186 $lastlist->nextlist =& $this->editlists[$context->id];
188 $lastlist =& $this->editlists[$context->id];
191 $count = 1;
192 $paged = false;
193 foreach ($this->editlists as $key => $list){
194 list($paged, $count) = $this->editlists[$key]->list_from_records($paged, $count);
196 $this->catform = new question_category_edit_form($this->pageurl, compact('contexts', 'currentcat'));
197 if (!$currentcat){
198 $this->catform->set_data(array('parent'=>$defaultcategory));
202 * Displays the user interface
205 function display_user_interface() {
207 /// Interface for editing existing categories
208 $this->output_edit_lists();
211 echo '<br />';
212 /// Interface for adding a new category:
213 $this->output_new_table();
214 echo '<br />';
219 * Outputs a table to allow entry of a new category
221 function output_new_table() {
222 $this->catform->display();
227 * Outputs a list to allow editing/rearranging of existing categories
229 * $this->initialize() must have already been called
232 function output_edit_lists() {
233 print_heading_with_help(get_string('editcategories', 'quiz'), 'categories', 'question');
234 foreach ($this->editlists as $context => $list){
235 $listhtml = $list->to_html(0, array('str'=>$this->str));
236 if ($listhtml){
237 print_heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), '', 3);
238 print_box_start('boxwidthwide boxaligncenter generalbox');
239 echo $listhtml;
240 print_box_end();
243 echo $list->display_page_numbers();
249 * gets all the courseids for the given categories
251 * @param array categories contains category objects in a tree representation
252 * @return array courseids flat array in form categoryid=>courseid
254 function get_course_ids($categories) {
255 $courseids = array();
256 foreach ($categories as $key=>$cat) {
257 $courseids[$key] = $cat->course;
258 if (!empty($cat->children)) {
259 $courseids = array_merge($courseids, $this->get_course_ids($cat->children));
262 return $courseids;
267 function edit_single_category($categoryid) {
268 /// Interface for adding a new category
269 global $COURSE;
270 /// Interface for editing existing categories
271 if ($category = get_record("question_categories", "id", $categoryid)) {
273 $category->parent = "$category->parent,$category->contextid";
274 $category->submitbutton = get_string('savechanges');
275 $category->categoryheader = $this->str->edit;
276 $this->catform->set_data($category);
277 $this->catform->display();
278 } else {
279 error("Category $categoryid not found");
285 * Sets the viable parents
287 * Viable parents are any except for the category itself, or any of it's descendants
288 * The parentstrings parameter is passed by reference and changed by this function.
290 * @param array parentstrings a list of parentstrings
291 * @param object category
293 function set_viable_parents(&$parentstrings, $category) {
295 unset($parentstrings[$category->id]);
296 if (isset($category->children)) {
297 foreach ($category->children as $child) {
298 $this->set_viable_parents($parentstrings, $child);
304 * Gets question categories
306 * @param int parent - if given, restrict records to those with this parent id.
307 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
308 * @return array categories
310 function get_question_categories($parent=null, $sort="sortorder ASC") {
311 global $COURSE;
312 if (is_null($parent)) {
313 $categories = get_records('question_categories', 'course', "{$COURSE->id}", $sort);
314 } else {
315 $select = "parent = '$parent' AND course = '{$COURSE->id}'";
316 $categories = get_records_select('question_categories', $select, $sort);
318 return $categories;
322 * Deletes an existing question category
324 * @param int deletecat id of category to delete
326 function delete_category($categoryid) {
327 global $CFG;
328 question_can_delete_cat($categoryid);
329 if (!$category = get_record("question_categories", "id", $categoryid)) { // security
330 error("No such category $cat!", $this->pageurl->out());
332 /// Send the children categories to live with their grandparent
333 if (!set_field("question_categories", "parent", $category->parent, "parent", $category->id)) {
334 error("Could not update a child category!", $this->pageurl->out());
337 /// Finally delete the category itself
338 if (delete_records("question_categories", "id", $category->id)) {
339 notify(get_string("categorydeleted", "quiz", format_string($category->name)), 'notifysuccess');
340 redirect($this->pageurl->out());//always redirect after successful action
343 function move_questions_and_delete_category($oldcat, $newcat){
344 question_can_delete_cat($oldcat);
345 $this->move_questions($oldcat, $newcat);
346 $this->delete_category($oldcat);
349 function display_move_form($questionsincategory, $category){
350 $vars = new stdClass;
351 $vars->name = $category->name;
352 $vars->count = $questionsincategory;
353 print_simple_box(get_string("categorymove", "quiz", $vars), "center");
354 $this->moveform->display();
357 function move_questions($oldcat, $newcat){
358 if (!set_field('question', 'category', $newcat, 'category', $oldcat)) {
359 error("Error while moving questions from category '$oldcat' to '$newcat'", $this->pageurl->out());
364 * Creates a new category with given params
367 function add_category($newparent, $newcategory, $newinfo) {
368 if (empty($newcategory)) {
369 error(get_string('categorynamecantbeblank', 'quiz'));
371 list($parentid, $contextid) = explode(',', $newparent);
372 //moodle_form makes sure select element output is legal no need for further cleaning
373 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
375 if ($parentid) {
376 if(!(get_field('question_categories', 'contextid', 'id', $parentid) == $contextid)) {
377 error("Could not insert the new question category '$newcategory' illegal contextid '$contextid'.");
381 $cat = new object();
382 $cat->parent = $parentid;
383 $cat->contextid = $contextid;
384 $cat->name = $newcategory;
385 $cat->info = $newinfo;
386 $cat->sortorder = 999;
387 $cat->stamp = make_unique_id_code();
388 if (!insert_record("question_categories", $cat)) {
389 error("Could not insert the new question category '$newcategory'");
390 } else {
391 redirect($this->pageurl->out());//always redirect after successful action
396 * Updates an existing category with given params
399 function update_category($updateid, $newparent, $newname, $newinfo) {
400 global $CFG, $QTYPES;
401 if (empty($newname)) {
402 error(get_string('categorynamecantbeblank', 'quiz'));
405 list($parentid, $tocontextid) = explode(',', $newparent);
407 $oldcat = get_record('question_categories', 'id', $updateid);
408 $fromcontext = get_context_instance_by_id($oldcat->contextid);
409 require_capability('moodle/question:managecategory', $fromcontext);
410 if ($oldcat->contextid == $tocontextid){
411 $tocontext = get_context_instance_by_id($tocontextid);
412 require_capability('moodle/question:managecategory', $tocontext);
414 $cat = NULL;
415 $cat->id = $updateid;
416 $cat->name = $newname;
417 $cat->info = $newinfo;
418 //never move category where it is the default
419 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")){
420 if ($oldcat->contextid == $tocontextid){ // not moving contexts
421 $cat->parent = $parentid;
422 if (!update_record("question_categories", $cat)) {
423 error("Could not update the category '$newname'", $this->pageurl->out());
424 } else {
425 redirect($this->pageurl->out());
427 } else {
428 if (!update_record("question_categories", $cat)) {
429 error("Could not update the category '$newname'", $this->pageurl->out());
430 } else {
431 redirect($CFG->wwwroot.'/question/contextmove.php?'.
432 $this->pageurl->get_query_string(array('cattomove' => $updateid,
433 'toparent'=>$newparent)));
436 } else {
437 error("Cannot move the category '$newname'. It is the last in this context.", $this->pageurl->out());
441 function move_question_from_cat_confirm($fromcat, $fromcourse, $tocat=null, $question=null){
442 global $QTYPES;
443 if (!$question){
444 $questions[] = $question;
445 } else {
446 $questions = get_records('question', 'category', $tocat->id);
448 $urls = array();
449 foreach ($questions as $question){
450 $urls = array_merge($urls, $QTYPES[$question->qtype]->find_file_links_in_question($question));
452 if ($fromcourse){
453 $append = 'tocourse';
454 } else {
455 $append = 'tosite';
457 if ($tocat){
458 echo '<p>'.get_string('needtomovethesefilesincat','question').'</p>';
459 } else {
460 echo '<p>'.get_string('needtomovethesefilesinquestion','question').'</p>';