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
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("$CFG->dirroot/question/category_form_randomquestion.php");
16 require_once('move_form.php');
18 class question_category_list
extends moodle_list
{
19 public $table = "question_categories";
20 public $listitemclassname = 'question_category_list_item';
22 * @var reference to list displayed below this one.
24 public $nextlist = null;
26 * @var reference to list displayed above this one.
28 public $lastlist = null;
30 public $context = null;
31 public $sortby = 'parent, sortorder, name';
33 public function question_category_list($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){
34 parent
::moodle_list('ul', '', $editable, $pageurl, $page, 'cpage', $itemsperpage);
35 $this->context
= $context;
38 public function get_records() {
39 $this->records
= get_categories_for_contexts($this->context
->id
, $this->sortby
);
41 public function process_actions($left, $right, $moveup, $movedown, $moveupcontext, $movedowncontext, $tocontext){
43 //parent::procces_actions redirects after any action
44 parent
::process_actions($left, $right, $moveup, $movedown);
45 if ($tocontext == $this->context
->id
){
46 //only called on toplevel list
48 $cattomove = $moveupcontext;
50 } elseif ($movedowncontext){
51 $cattomove = $movedowncontext;
54 $toparent = "0,{$this->context->id}";
55 $url = new moodle_url('/question/contextmove.php?', $this->pageurl
->params() +
compact('cattomove', 'totop', 'toparent'));
61 class question_category_list_item
extends list_item
{
64 public function set_icon_html($first, $last, &$lastitem){
66 $category = $this->item
;
67 $url = new moodle_url('/question/category.php', ($this->parentlist
->pageurl
->params() +
array('edit'=>$category->id
)));
68 $this->icons
['edit']= $this->image_icon(get_string('editthiscategory', 'question'), $url, 'edit');
69 parent
::set_icon_html($first, $last, $lastitem);
70 $toplevel = ($this->parentlist
->parentitem
=== null);//this is a top level item
71 if (($this->parentlist
->nextlist
!== null) && $last && $toplevel && (count($this->parentlist
->items
)>1)){
72 $url = new moodle_url($this->parentlist
->pageurl
, array('movedowncontext'=>$this->id
, 'tocontext'=>$this->parentlist
->nextlist
->context
->id
, 'sesskey'=>sesskey()));
73 $this->icons
['down'] = $this->image_icon(
74 get_string('shareincontext', 'question', print_context_name($this->parentlist
->nextlist
->context
)), $url, 'down');
76 if (($this->parentlist
->lastlist
!== null) && $first && $toplevel && (count($this->parentlist
->items
)>1)){
77 $url = new moodle_url($this->parentlist
->pageurl
, array('moveupcontext'=>$this->id
, 'tocontext'=>$this->parentlist
->lastlist
->context
->id
, 'sesskey'=>sesskey()));
78 $this->icons
['up'] = $this->image_icon(
79 get_string('shareincontext', 'question', print_context_name($this->parentlist
->lastlist
->context
)), $url, 'up');
82 public function item_html($extraargs = array()){
84 $str = $extraargs['str'];
85 $category = $this->item
;
87 $editqestions = get_string('editquestions', 'quiz');
89 /// Each section adds html to be displayed as part of this list item
90 $questionbankurl = new moodle_url("/question/edit.php", ($this->parentlist
->pageurl
->params() +
array('category'=>"$category->id,$category->contextid")));
91 $catediturl = $this->parentlist
->pageurl
->out(true, array('edit'=>$this->id
));
92 $item = "<b><a title=\"{$str->edit}\" href=\"$catediturl\">".$category->name
."</a></b> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount
.')</a>';
94 $item .= ' '. $category->info
;
96 if (count($this->parentlist
->records
)!=1){ // don't allow delete if this is the last category in this context.
97 $item .= '<a title="' . $str->delete
. '" href="'.$this->parentlist
->pageurl
->out(true, array('delete'=>$this->id
, 'sesskey'=>sesskey())).'">
98 <img src="' . $OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="' .$str->delete
. '" /></a>';
108 * Class representing question categories
110 * @package questionbank
112 class question_category_object
{
116 * Nested lists to display categories.
120 var $editlists = array();
124 //------------------------------------------------------
126 * @var moodle_url Object representing url for this page
130 * @var question_category_edit_form Object representing form for adding / editing categories.
134 * @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 * Gets necessary strings and sets relevant path information
143 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
144 global $CFG, $COURSE, $OUTPUT;
146 $this->tab
= str_repeat(' ', $this->tabsize
);
148 $this->str
->course
= get_string('course');
149 $this->str
->category
= get_string('category', 'quiz');
150 $this->str
->categoryinfo
= get_string('categoryinfo', 'quiz');
151 $this->str
->questions
= get_string('questions', 'quiz');
152 $this->str
->add
= get_string('add');
153 $this->str
->delete
= get_string('delete');
154 $this->str
->moveup
= get_string('moveup');
155 $this->str
->movedown
= get_string('movedown');
156 $this->str
->edit
= get_string('editthiscategory', 'question');
157 $this->str
->hide
= get_string('hide');
158 $this->str
->publish
= get_string('publish', 'quiz');
159 $this->str
->order
= get_string('order');
160 $this->str
->parent
= get_string('parent', 'quiz');
161 $this->str
->add
= get_string('add');
162 $this->str
->action
= get_string('action');
163 $this->str
->top
= get_string('top', 'quiz');
164 $this->str
->addcategory
= get_string('addcategory', 'quiz');
165 $this->str
->editcategory
= get_string('editcategory', 'quiz');
166 $this->str
->cancel
= get_string('cancel');
167 $this->str
->editcategories
= get_string('editcategories', 'quiz');
168 $this->str
->page
= get_string('page');
170 $this->pageurl
= $pageurl;
172 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
179 * Initializes this classes general category-related variables
181 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
183 foreach ($contexts as $context){
184 $this->editlists
[$context->id
] = new question_category_list('ul', '', true, $this->pageurl
, $page, 'cpage', QUESTION_PAGE_LENGTH
, $context);
185 $this->editlists
[$context->id
]->lastlist
=& $lastlist;
186 if ($lastlist!== null){
187 $lastlist->nextlist
=& $this->editlists
[$context->id
];
189 $lastlist =& $this->editlists
[$context->id
];
194 foreach ($this->editlists
as $key => $list){
195 list($paged, $count) = $this->editlists
[$key]->list_from_records($paged, $count);
197 $this->catform
= new question_category_edit_form($this->pageurl
, compact('contexts', 'currentcat'));
198 $this->catform_rand
= new question_category_edit_form_randomquestion($this->pageurl
, compact('contexts', 'currentcat'));
200 $this->catform
->set_data(array('parent'=>$defaultcategory));
201 $this->catform_rand
->set_data(array('parent'=>$defaultcategory));
205 * Displays the user interface
208 public function display_user_interface() {
210 /// Interface for editing existing categories
211 $this->output_edit_lists();
215 /// Interface for adding a new category:
216 $this->output_new_table();
221 * Displays the user interface
224 function display_randomquestion_user_interface($addonpage=0) {
225 $this->catform_rand
->set_data(array('addonpage'=>$addonpage));
226 /// Interface for adding a new category:
227 $this->output_new_randomquestion_table();
232 * Outputs a table to allow entry of a new category
234 public function output_new_table() {
235 $this->catform
->display();
239 * Outputs a table to allow entry of a new category
241 function output_new_randomquestion_table() {
242 $this->catform_rand
->display();
247 * Outputs a list to allow editing/rearranging of existing categories
249 * $this->initialize() must have already been called
252 public function output_edit_lists() {
255 echo $OUTPUT->heading_with_help(get_string('editcategories', 'quiz'), 'categories', 'question');
257 foreach ($this->editlists
as $context => $list){
258 $listhtml = $list->to_html(0, array('str'=>$this->str
));
260 echo $OUTPUT->box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context
->contextlevel
);
261 echo $OUTPUT->heading(get_string('questioncatsfor', 'question', print_context_name(get_context_instance_by_id($context))), 3);
263 echo $OUTPUT->box_end();
266 echo $list->display_page_numbers();
272 * gets all the courseids for the given categories
274 * @param array categories contains category objects in a tree representation
275 * @return array courseids flat array in form categoryid=>courseid
277 public function get_course_ids($categories) {
278 $courseids = array();
279 foreach ($categories as $key=>$cat) {
280 $courseids[$key] = $cat->course
;
281 if (!empty($cat->children
)) {
282 $courseids = array_merge($courseids, $this->get_course_ids($cat->children
));
290 public function edit_single_category($categoryid) {
291 /// Interface for adding a new category
293 /// Interface for editing existing categories
294 if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) {
296 $category->parent
= "$category->parent,$category->contextid";
297 $category->submitbutton
= get_string('savechanges');
298 $category->categoryheader
= $this->str
->edit
;
299 $this->catform
->set_data($category);
300 $this->catform
->display();
302 print_error('invalidcategory', '', '', $categoryid);
308 * Sets the viable parents
310 * Viable parents are any except for the category itself, or any of it's descendants
311 * The parentstrings parameter is passed by reference and changed by this function.
313 * @param array parentstrings a list of parentstrings
314 * @param object category
316 public function set_viable_parents(&$parentstrings, $category) {
318 unset($parentstrings[$category->id
]);
319 if (isset($category->children
)) {
320 foreach ($category->children
as $child) {
321 $this->set_viable_parents($parentstrings, $child);
327 * Gets question categories
329 * @param int parent - if given, restrict records to those with this parent id.
330 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
331 * @return array categories
333 public function get_question_categories($parent=null, $sort="sortorder ASC") {
335 if (is_null($parent)) {
336 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id
), $sort);
338 $select = "parent = ? AND course = ?";
339 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id
), $sort);
345 * Deletes an existing question category
347 * @param int deletecat id of category to delete
349 public function delete_category($categoryid) {
351 question_can_delete_cat($categoryid);
352 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
353 print_error('unknowcategory');
355 /// Send the children categories to live with their grandparent
356 $DB->set_field("question_categories", "parent", $category->parent
, array("parent" => $category->id
));
358 /// Finally delete the category itself
359 $DB->delete_records("question_categories", array("id" => $category->id
));
362 public function move_questions_and_delete_category($oldcat, $newcat){
363 question_can_delete_cat($oldcat);
364 $this->move_questions($oldcat, $newcat);
365 $this->delete_category($oldcat);
368 public function display_move_form($questionsincategory, $category){
370 $vars = new stdClass
;
371 $vars->name
= $category->name
;
372 $vars->count
= $questionsincategory;
373 echo $OUTPUT->box(get_string('categorymove', 'quiz', $vars), 'generalbox boxaligncenter');
374 $this->moveform
->display();
377 public function move_questions($oldcat, $newcat){
379 $questionids = $DB->get_records_select_menu('question', "category = ? AND (parent = 0 OR parent = id)", array($oldcat), '', 'id,1');
380 $ids = implode(',', array_keys($questionids));
381 if (!question_move_questions_to_category($ids, $newcat)) {
382 print_error('errormovingquestions', 'question', $this->pageurl
->out(), $ids);
387 * Creates a new category with given params
389 public function add_category($newparent, $newcategory, $newinfo, $return=false) {
391 if (empty($newcategory)) {
392 print_error('categorynamecantbeblank', 'quiz');
394 list($parentid, $contextid) = explode(',', $newparent);
395 //moodle_form makes sure select element output is legal no need for further cleaning
396 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
399 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
400 print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
405 $cat->parent
= $parentid;
406 $cat->contextid
= $contextid;
407 $cat->name
= $newcategory;
408 $cat->info
= $newinfo;
409 $cat->sortorder
= 999;
410 $cat->stamp
= make_unique_id_code();
411 $categoryid = $DB->insert_record("question_categories", $cat);
415 redirect($this->pageurl
);//always redirect after successful action
420 * Updates an existing category with given params
422 public function update_category($updateid, $newparent, $newname, $newinfo) {
423 global $CFG, $QTYPES, $DB;
424 if (empty($newname)) {
425 print_error('categorynamecantbeblank', 'quiz');
428 // Get the record we are updating.
429 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
430 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
432 if (!empty($newparent) && !$lastcategoryinthiscontext) {
433 list($parentid, $tocontextid) = explode(',', $newparent);
435 $parentid = $oldcat->parent
;
436 $tocontextid = $oldcat->contextid
;
439 // Check permissions.
440 $fromcontext = get_context_instance_by_id($oldcat->contextid
);
441 require_capability('moodle/question:managecategory', $fromcontext);
443 // If moving to another context, check permissions some more.
444 if ($oldcat->contextid
!= $tocontextid){
445 $tocontext = get_context_instance_by_id($tocontextid);
446 require_capability('moodle/question:managecategory', $tocontext);
449 // Update the category record.
451 $cat->id
= $updateid;
452 $cat->name
= $newname;
453 $cat->info
= $newinfo;
454 $cat->parent
= $parentid;
455 // We don't change $cat->contextid here, if necessary we redirect to contextmove.php later.
456 $DB->update_record('question_categories', $cat);
458 // If the category name has changed, rename any random questions in that category.
459 if ($oldcat->name
!= $cat->name
) {
460 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
462 $randomqname = $QTYPES[RANDOM
]->question_name($cat, false);
463 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id
, '0'));
465 $randomqname = $QTYPES[RANDOM
]->question_name($cat, true);
466 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id
, '1'));
469 // Then redirect to an appropriate place.
470 if ($oldcat->contextid
== $tocontextid) { // not moving contexts
471 redirect($this->pageurl
);
473 $url = new moodle_url('/question/contextmove.php', ($this->pageurl
->params() +
array('cattomove' => $updateid, 'toparent'=>$newparent)));
478 public function move_question_from_cat_confirm($fromcat, $fromcourse, $tocat=null, $question=null){
481 $questions[] = $question;
483 $questions = $DB->get_records('question', array('category' => $tocat->id
));
486 foreach ($questions as $question){
487 $urls = array_merge($urls, $QTYPES[$question->qtype
]->find_file_links_in_question($question));
490 $append = 'tocourse';
495 echo '<p>'.get_string('needtomovethesefilesincat','question').'</p>';
497 echo '<p>'.get_string('needtomovethesefilesinquestion','question').'</p>';