2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * A class for representing question categories.
21 * @subpackage questionbank
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') ||
die();
29 // number of categories to display on page
30 define('QUESTION_PAGE_LENGTH', 25);
32 require_once($CFG->libdir
. '/listlib.php');
33 require_once($CFG->dirroot
. '/question/category_form.php');
34 require_once($CFG->dirroot
. '/question/move_form.php');
38 * Class representing a list of question categories
40 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 class question_category_list
extends moodle_list
{
44 public $table = "question_categories";
45 public $listitemclassname = 'question_category_list_item';
47 * @var reference to list displayed below this one.
49 public $nextlist = null;
51 * @var reference to list displayed above this one.
53 public $lastlist = null;
55 public $context = null;
56 public $sortby = 'parent, sortorder, name';
58 public function __construct($type='ul', $attributes='', $editable = false, $pageurl=null, $page = 0, $pageparamname = 'page', $itemsperpage = 20, $context = null){
59 parent
::__construct('ul', '', $editable, $pageurl, $page, 'cpage', $itemsperpage);
60 $this->context
= $context;
63 public function get_records() {
64 $this->records
= get_categories_for_contexts($this->context
->id
, $this->sortby
);
70 * An item in a list of question categories.
72 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
73 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
75 class question_category_list_item
extends list_item
{
76 public function set_icon_html($first, $last, $lastitem){
78 $category = $this->item
;
79 $url = new moodle_url('/question/category.php', ($this->parentlist
->pageurl
->params() +
array('edit'=>$category->id
)));
80 $this->icons
['edit']= $this->image_icon(get_string('editthiscategory', 'question'), $url, 'edit');
81 parent
::set_icon_html($first, $last, $lastitem);
82 $toplevel = ($this->parentlist
->parentitem
=== null);//this is a top level item
83 if (($this->parentlist
->nextlist
!== null) && $last && $toplevel && (count($this->parentlist
->items
)>1)){
84 $url = new moodle_url($this->parentlist
->pageurl
, array('movedowncontext'=>$this->id
, 'tocontext'=>$this->parentlist
->nextlist
->context
->id
, 'sesskey'=>sesskey()));
85 $this->icons
['down'] = $this->image_icon(
86 get_string('shareincontext', 'question', print_context_name($this->parentlist
->nextlist
->context
)), $url, 'down');
88 if (($this->parentlist
->lastlist
!== null) && $first && $toplevel && (count($this->parentlist
->items
)>1)){
89 $url = new moodle_url($this->parentlist
->pageurl
, array('moveupcontext'=>$this->id
, 'tocontext'=>$this->parentlist
->lastlist
->context
->id
, 'sesskey'=>sesskey()));
90 $this->icons
['up'] = $this->image_icon(
91 get_string('shareincontext', 'question', print_context_name($this->parentlist
->lastlist
->context
)), $url, 'up');
95 public function item_html($extraargs = array()){
97 $str = $extraargs['str'];
98 $category = $this->item
;
100 $editqestions = get_string('editquestions', 'question');
102 /// Each section adds html to be displayed as part of this list item
103 $questionbankurl = new moodle_url("/question/edit.php", ($this->parentlist
->pageurl
->params() +
array('cat'=>"$category->id,$category->contextid")));
104 $catediturl = $this->parentlist
->pageurl
->out(true, array('edit' => $this->id
));
105 $item = "<b><a title=\"{$str->edit}\" href=\"$catediturl\">" .
106 format_string($category->name
, true, array('context' => $this->parentlist
->context
)) .
107 "</a></b> <a title=\"$editqestions\" href=\"$questionbankurl\">".'('.$category->questioncount
.')</a>';
109 $item .= ' ' . format_text($category->info
, $category->infoformat
,
110 array('context' => $this->parentlist
->context
, 'noclean' => true));
112 // don't allow delete if this is the last category in this context.
113 if (count($this->parentlist
->records
) != 1) {
114 $item .= '<a title="' . $str->delete
. '" href="'.$this->parentlist
->pageurl
->out(true, array('delete'=>$this->id
, 'sesskey'=>sesskey())).'">
115 <img src="' . $OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="' .$str->delete
. '" /></a>';
124 * Class representing q question category
126 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
129 class question_category_object
{
133 * Nested lists to display categories.
137 var $editlists = array();
143 * @var moodle_url Object representing url for this page
147 * @var question_category_edit_form Object representing form for adding / editing categories.
154 * Gets necessary strings and sets relevant path information
156 public function question_category_object($page, $pageurl, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
157 global $CFG, $COURSE, $OUTPUT;
159 $this->tab
= str_repeat(' ', $this->tabsize
);
161 $this->str
= new stdClass();
162 $this->str
->course
= get_string('course');
163 $this->str
->category
= get_string('category', 'question');
164 $this->str
->categoryinfo
= get_string('categoryinfo', 'question');
165 $this->str
->questions
= get_string('questions', 'question');
166 $this->str
->add
= get_string('add');
167 $this->str
->delete
= get_string('delete');
168 $this->str
->moveup
= get_string('moveup');
169 $this->str
->movedown
= get_string('movedown');
170 $this->str
->edit
= get_string('editthiscategory', 'question');
171 $this->str
->hide
= get_string('hide');
172 $this->str
->order
= get_string('order');
173 $this->str
->parent
= get_string('parent', 'question');
174 $this->str
->add
= get_string('add');
175 $this->str
->action
= get_string('action');
176 $this->str
->top
= get_string('top');
177 $this->str
->addcategory
= get_string('addcategory', 'question');
178 $this->str
->editcategory
= get_string('editcategory', 'question');
179 $this->str
->cancel
= get_string('cancel');
180 $this->str
->editcategories
= get_string('editcategories', 'question');
181 $this->str
->page
= get_string('page');
183 $this->pageurl
= $pageurl;
185 $this->initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts);
189 * Initializes this classes general category-related variables
191 public function initialize($page, $contexts, $currentcat, $defaultcategory, $todelete, $addcontexts) {
193 foreach ($contexts as $context){
194 $this->editlists
[$context->id
] = new question_category_list('ul', '', true, $this->pageurl
, $page, 'cpage', QUESTION_PAGE_LENGTH
, $context);
195 $this->editlists
[$context->id
]->lastlist
=& $lastlist;
196 if ($lastlist!== null){
197 $lastlist->nextlist
=& $this->editlists
[$context->id
];
199 $lastlist =& $this->editlists
[$context->id
];
204 foreach ($this->editlists
as $key => $list){
205 list($paged, $count) = $this->editlists
[$key]->list_from_records($paged, $count);
207 $this->catform
= new question_category_edit_form($this->pageurl
, compact('contexts', 'currentcat'));
209 $this->catform
->set_data(array('parent'=>$defaultcategory));
214 * Displays the user interface
217 public function display_user_interface() {
219 /// Interface for editing existing categories
220 $this->output_edit_lists();
224 /// Interface for adding a new category:
225 $this->output_new_table();
231 * Outputs a table to allow entry of a new category
233 public function output_new_table() {
234 $this->catform
->display();
238 * Outputs a list to allow editing/rearranging of existing categories
240 * $this->initialize() must have already been called
243 public function output_edit_lists() {
246 echo $OUTPUT->heading_with_help(get_string('editcategories', 'question'), 'editcategories', 'question');
248 foreach ($this->editlists
as $context => $list){
249 $listhtml = $list->to_html(0, array('str'=>$this->str
));
251 echo $OUTPUT->box_start('boxwidthwide boxaligncenter generalbox questioncategories contextlevel' . $list->context
->contextlevel
);
252 echo $OUTPUT->heading(get_string('questioncatsfor', 'question', print_context_name(context
::instance_by_id($context))), 3);
254 echo $OUTPUT->box_end();
257 echo $list->display_page_numbers();
261 * gets all the courseids for the given categories
263 * @param array categories contains category objects in a tree representation
264 * @return array courseids flat array in form categoryid=>courseid
266 public function get_course_ids($categories) {
267 $courseids = array();
268 foreach ($categories as $key=>$cat) {
269 $courseids[$key] = $cat->course
;
270 if (!empty($cat->children
)) {
271 $courseids = array_merge($courseids, $this->get_course_ids($cat->children
));
277 public function edit_single_category($categoryid) {
278 /// Interface for adding a new category
280 /// Interface for editing existing categories
281 if ($category = $DB->get_record("question_categories", array("id" => $categoryid))) {
283 $category->parent
= "$category->parent,$category->contextid";
284 $category->submitbutton
= get_string('savechanges');
285 $category->categoryheader
= $this->str
->edit
;
286 $this->catform
->set_data($category);
287 $this->catform
->display();
289 print_error('invalidcategory', '', '', $categoryid);
294 * Sets the viable parents
296 * Viable parents are any except for the category itself, or any of it's descendants
297 * The parentstrings parameter is passed by reference and changed by this function.
299 * @param array parentstrings a list of parentstrings
300 * @param object category
302 public function set_viable_parents(&$parentstrings, $category) {
304 unset($parentstrings[$category->id
]);
305 if (isset($category->children
)) {
306 foreach ($category->children
as $child) {
307 $this->set_viable_parents($parentstrings, $child);
313 * Gets question categories
315 * @param int parent - if given, restrict records to those with this parent id.
316 * @param string sort - [[sortfield [,sortfield]] {ASC|DESC}]
317 * @return array categories
319 public function get_question_categories($parent=null, $sort="sortorder ASC") {
321 if (is_null($parent)) {
322 $categories = $DB->get_records('question_categories', array('course' => $COURSE->id
), $sort);
324 $select = "parent = ? AND course = ?";
325 $categories = $DB->get_records_select('question_categories', $select, array($parent, $COURSE->id
), $sort);
331 * Deletes an existing question category
333 * @param int deletecat id of category to delete
335 public function delete_category($categoryid) {
337 question_can_delete_cat($categoryid);
338 if (!$category = $DB->get_record("question_categories", array("id" => $categoryid))) { // security
339 print_error('unknowcategory');
341 /// Send the children categories to live with their grandparent
342 $DB->set_field("question_categories", "parent", $category->parent
, array("parent" => $category->id
));
344 /// Finally delete the category itself
345 $DB->delete_records("question_categories", array("id" => $category->id
));
348 public function move_questions_and_delete_category($oldcat, $newcat){
349 question_can_delete_cat($oldcat);
350 $this->move_questions($oldcat, $newcat);
351 $this->delete_category($oldcat);
354 public function display_move_form($questionsincategory, $category){
356 $vars = new stdClass();
357 $vars->name
= $category->name
;
358 $vars->count
= $questionsincategory;
359 echo $OUTPUT->box(get_string('categorymove', 'question', $vars), 'generalbox boxaligncenter');
360 $this->moveform
->display();
363 public function move_questions($oldcat, $newcat){
365 $questionids = $DB->get_records_select_menu('question',
366 'category = ? AND (parent = 0 OR parent = id)', array($oldcat), '', 'id,1');
367 question_move_questions_to_category(array_keys($questionids), $newcat);
371 * Creates a new category with given params
373 public function add_category($newparent, $newcategory, $newinfo, $return = false) {
375 if (empty($newcategory)) {
376 print_error('categorynamecantbeblank', 'question');
378 list($parentid, $contextid) = explode(',', $newparent);
379 //moodle_form makes sure select element output is legal no need for further cleaning
380 require_capability('moodle/question:managecategory', context
::instance_by_id($contextid));
383 if(!($DB->get_field('question_categories', 'contextid', array('id' => $parentid)) == $contextid)) {
384 print_error('cannotinsertquestioncatecontext', 'question', '', array('cat'=>$newcategory, 'ctx'=>$contextid));
388 $cat = new stdClass();
389 $cat->parent
= $parentid;
390 $cat->contextid
= $contextid;
391 $cat->name
= $newcategory;
392 $cat->info
= $newinfo;
393 $cat->sortorder
= 999;
394 $cat->stamp
= make_unique_id_code();
395 $categoryid = $DB->insert_record("question_categories", $cat);
399 redirect($this->pageurl
);//always redirect after successful action
404 * Updates an existing category with given params
406 public function update_category($updateid, $newparent, $newname, $newinfo) {
408 if (empty($newname)) {
409 print_error('categorynamecantbeblank', 'question');
412 // Get the record we are updating.
413 $oldcat = $DB->get_record('question_categories', array('id' => $updateid));
414 $lastcategoryinthiscontext = question_is_only_toplevel_category_in_context($updateid);
416 if (!empty($newparent) && !$lastcategoryinthiscontext) {
417 list($parentid, $tocontextid) = explode(',', $newparent);
419 $parentid = $oldcat->parent
;
420 $tocontextid = $oldcat->contextid
;
423 // Check permissions.
424 $fromcontext = context
::instance_by_id($oldcat->contextid
);
425 require_capability('moodle/question:managecategory', $fromcontext);
427 // If moving to another context, check permissions some more.
428 if ($oldcat->contextid
!= $tocontextid) {
429 $tocontext = context
::instance_by_id($tocontextid);
430 require_capability('moodle/question:managecategory', $tocontext);
433 // Update the category record.
434 $cat = new stdClass();
435 $cat->id
= $updateid;
436 $cat->name
= $newname;
437 $cat->info
= $newinfo;
438 $cat->parent
= $parentid;
439 $cat->contextid
= $tocontextid;
440 $DB->update_record('question_categories', $cat);
442 // If the category name has changed, rename any random questions in that category.
443 if ($oldcat->name
!= $cat->name
) {
444 $where = "qtype = 'random' AND category = ? AND " . $DB->sql_compare_text('questiontext') . " = ?";
446 $randomqtype = question_bank
::get_qtype('random');
447 $randomqname = $randomqtype->question_name($cat, false);
448 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id
, '0'));
450 $randomqname = $randomqtype->question_name($cat, true);
451 $DB->set_field_select('question', 'name', $randomqname, $where, array($cat->id
, '1'));
454 if ($oldcat->contextid
!= $tocontextid) {
455 // Moving to a new context. Must move files belonging to questions.
456 question_move_category_to_context($cat->id
, $oldcat->contextid
, $tocontextid);
459 // Cat param depends on the context id, so update it.
460 $this->pageurl
->param('cat', $updateid . ',' . $tocontextid);
461 redirect($this->pageurl
);