Merge branch 'MDL-73468' of git://github.com/paulholden/moodle
[moodle.git] / question / editlib.php
blob871d7b92b4f42ec3356996e47a299fa0196f57c0
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * Functions used to show question editing interface
20 * @package moodlecore
21 * @subpackage questionbank
22 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 use core_question\bank\search\category_condition;
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir . '/questionlib.php');
33 define('DEFAULT_QUESTIONS_PER_PAGE', 20);
34 define('MAXIMUM_QUESTIONS_PER_PAGE', 1000);
36 function get_module_from_cmid($cmid) {
37 global $CFG, $DB;
38 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
39 FROM {course_modules} cm,
40 {modules} md
41 WHERE cm.id = ? AND
42 md.id = cm.module", array($cmid))){
43 print_error('invalidcoursemodule');
44 } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
45 print_error('invalidcoursemodule');
47 $modrec->instance = $modrec->id;
48 $modrec->cmid = $cmrec->id;
49 $cmrec->name = $modrec->name;
51 return array($modrec, $cmrec);
53 /**
54 * Function to read all questions for category into big array
56 * @param int $category category number
57 * @param bool $noparent if true only questions with NO parent will be selected
58 * @param bool $recurse include subdirectories
59 * @param bool $export set true if this is called by questionbank export
61 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
62 global $DB;
64 // Build sql bit for $noparent
65 $npsql = '';
66 if ($noparent) {
67 $npsql = " and parent='0' ";
70 // Get list of categories
71 if ($recurse) {
72 $categorylist = question_categorylist($category->id);
73 } else {
74 $categorylist = array($category->id);
77 // Get the list of questions for the category
78 list($usql, $params) = $DB->get_in_or_equal($categorylist);
79 $questions = $DB->get_records_select('question', "category {$usql} {$npsql}", $params, 'category, qtype, name');
81 // Iterate through questions, getting stuff we need
82 $qresults = array();
83 foreach($questions as $key => $question) {
84 $question->export_process = $export;
85 $qtype = question_bank::get_qtype($question->qtype, false);
86 if ($export && $qtype->name() == 'missingtype') {
87 // Unrecognised question type. Skip this question when exporting.
88 continue;
90 $qtype->get_question_options($question);
91 $qresults[] = $question;
94 return $qresults;
97 /**
98 * Checks whether this is the only child of a top category in a context.
100 * @param int $categoryid a category id.
101 * @return bool
102 * @deprecated since Moodle 4.0 MDL-71585
103 * @see qbank_managecategories\helper
104 * @todo Final deprecation on Moodle 4.4 MDL-72438
106 function question_is_only_child_of_top_category_in_context($categoryid) {
107 debugging('Function question_is_only_child_of_top_category_in_context()
108 has been deprecated and moved to qbank_managecategories plugin,
109 Please use qbank_managecategories\helper::question_is_only_child_of_top_category_in_context() instead.',
110 DEBUG_DEVELOPER);
111 return \qbank_managecategories\helper::question_is_only_child_of_top_category_in_context($categoryid);
115 * Checks whether the category is a "Top" category (with no parent).
117 * @param int $categoryid a category id.
118 * @return bool
119 * @deprecated since Moodle 4.0 MDL-71585
120 * @see qbank_managecategories\helper
121 * @todo Final deprecation on Moodle 4.4 MDL-72438
123 function question_is_top_category($categoryid) {
124 debugging('Function question_is_top_category() has been deprecated and moved to qbank_managecategories plugin,
125 Please use qbank_managecategories\helper::question_is_top_category() instead.', DEBUG_DEVELOPER);
126 return \qbank_managecategories\helper::question_is_top_category($categoryid);
130 * Ensures that this user is allowed to delete this category.
132 * @param int $todelete a category id.
133 * @deprecated since Moodle 4.0 MDL-71585
134 * @see qbank_managecategories\helper
135 * @todo Final deprecation on Moodle 4.4 MDL-72438
137 function question_can_delete_cat($todelete) {
138 debugging('Function question_can_delete_cat() has been deprecated and moved to qbank_managecategories plugin,
139 Please use qbank_managecategories\helper::question_can_delete_cat() instead.', DEBUG_DEVELOPER);
140 \qbank_managecategories\helper::question_can_delete_cat($todelete);
144 * Common setup for all pages for editing questions.
145 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
146 * @param string $edittab code for this edit tab
147 * @param bool $requirecmid require cmid? default false
148 * @param bool $unused no longer used, do no pass
149 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
151 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $unused = null) {
152 global $PAGE;
154 if ($unused !== null) {
155 debugging('Deprecated argument passed to question_edit_setup()', DEBUG_DEVELOPER);
158 $params = [];
160 if ($requirecmid) {
161 $params['cmid'] = required_param('cmid', PARAM_INT);
162 } else {
163 $params['cmid'] = optional_param('cmid', null, PARAM_INT);
166 if (!$params['cmid']) {
167 $params['courseid'] = required_param('courseid', PARAM_INT);
170 $params['qpage'] = optional_param('qpage', null, PARAM_INT);
172 // Pass 'cat' from page to page and when 'category' comes from a drop down menu
173 // then we also reset the qpage so we go to page 1 of
174 // a new cat.
175 $params['cat'] = optional_param('cat', null, PARAM_SEQUENCE); // If empty will be set up later.
176 $params['category'] = optional_param('category', null, PARAM_SEQUENCE);
177 $params['qperpage'] = optional_param('qperpage', null, PARAM_INT);
179 // Question table sorting options.
180 for ($i = 1; $i <= core_question\local\bank\view::MAX_SORTS; $i++) {
181 $param = 'qbs' . $i;
182 if ($sort = optional_param($param, '', PARAM_TEXT)) {
183 $params[$param] = $sort;
184 } else {
185 break;
189 // Display options.
190 $params['recurse'] = optional_param('recurse', null, PARAM_BOOL);
191 $params['showhidden'] = optional_param('showhidden', null, PARAM_BOOL);
192 $params['qbshowtext'] = optional_param('qbshowtext', null, PARAM_BOOL);
193 // Category list page.
194 $params['cpage'] = optional_param('cpage', null, PARAM_INT);
195 $params['qtagids'] = optional_param_array('qtagids', null, PARAM_INT);
197 $PAGE->set_pagelayout('admin');
199 return question_build_edit_resources($edittab, $baseurl, $params);
203 * Common function for building the generic resources required by the
204 * editing questions pages.
206 * Either a cmid or a course id must be provided as keys in $params or
207 * an exception will be thrown. All other params are optional and will have
208 * sane default applied if not provided.
210 * The acceptable keys for $params are:
212 * 'cmid' => PARAM_INT,
213 * 'courseid' => PARAM_INT,
214 * 'qpage' => PARAM_INT,
215 * 'cat' => PARAM_SEQUENCE,
216 * 'category' => PARAM_SEQUENCE,
217 * 'qperpage' => PARAM_INT,
218 * 'recurse' => PARAM_INT,
219 * 'showhidden' => PARAM_INT,
220 * 'qbshowtext' => PARAM_INT,
221 * 'cpage' => PARAM_INT,
222 * 'recurse' => PARAM_BOOL,
223 * 'showhidden' => PARAM_BOOL,
224 * 'qbshowtext' => PARAM_BOOL,
225 * 'qtagids' => [PARAM_INT], (array of integers)
226 * 'qbs1' => PARAM_TEXT,
227 * 'qbs2' => PARAM_TEXT,
228 * 'qbs3' => PARAM_TEXT,
229 * ... and more qbs keys up to core_question\local\bank\view::MAX_SORTS ...
230 * ];
232 * @param string $edittab Code for this edit tab
233 * @param string $baseurl The name of the script calling this funciton. For examle 'qusetion/edit.php'.
234 * @param array $params The provided parameters to construct the resources with.
235 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
237 function question_build_edit_resources($edittab, $baseurl, $params) {
238 global $DB, $PAGE, $CFG;
240 $thispageurl = new moodle_url($baseurl);
241 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
243 $cleanparams = [
244 'qsorts' => [],
245 'qtagids' => []
247 $paramtypes = [
248 'cmid' => PARAM_INT,
249 'courseid' => PARAM_INT,
250 'qpage' => PARAM_INT,
251 'cat' => PARAM_SEQUENCE,
252 'category' => PARAM_SEQUENCE,
253 'qperpage' => PARAM_INT,
254 'recurse' => PARAM_INT,
255 'showhidden' => PARAM_INT,
256 'qbshowtext' => PARAM_INT,
257 'cpage' => PARAM_INT,
258 'recurse' => PARAM_BOOL,
259 'showhidden' => PARAM_BOOL,
260 'qbshowtext' => PARAM_BOOL
263 foreach ($paramtypes as $name => $type) {
264 if (isset($params[$name])) {
265 $cleanparams[$name] = clean_param($params[$name], $type);
266 } else {
267 $cleanparams[$name] = null;
271 if (!empty($params['qtagids'])) {
272 $cleanparams['qtagids'] = clean_param_array($params['qtagids'], PARAM_INT);
275 $cmid = $cleanparams['cmid'];
276 $courseid = $cleanparams['courseid'];
277 $qpage = $cleanparams['qpage'] ?: -1;
278 $cat = $cleanparams['cat'] ?: 0;
279 $category = $cleanparams['category'] ?: 0;
280 $qperpage = $cleanparams['qperpage'];
281 $recurse = $cleanparams['recurse'];
282 $showhidden = $cleanparams['showhidden'];
283 $qbshowtext = $cleanparams['qbshowtext'];
284 $cpage = $cleanparams['cpage'] ?: 1;
285 $recurse = $cleanparams['recurse'];
286 $showhidden = $cleanparams['showhidden'];
287 $qbshowtext = $cleanparams['qbshowtext'];
288 $qsorts = $cleanparams['qsorts'];
289 $qtagids = $cleanparams['qtagids'];
291 if (is_null($cmid) && is_null($courseid)) {
292 throw new \moodle_exception('Must provide a cmid or courseid');
295 if ($cmid) {
296 list($module, $cm) = get_module_from_cmid($cmid);
297 $courseid = $cm->course;
298 $thispageurl->params(compact('cmid'));
299 require_login($courseid, false, $cm);
300 $thiscontext = context_module::instance($cmid);
301 } else {
302 $module = null;
303 $cm = null;
304 $thispageurl->params(compact('courseid'));
305 require_login($courseid, false);
306 $thiscontext = context_course::instance($courseid);
309 if ($thiscontext){
310 $contexts = new question_edit_contexts($thiscontext);
311 $contexts->require_one_edit_tab_cap($edittab);
312 } else {
313 $contexts = null;
316 $pagevars['qpage'] = $qpage;
318 // Pass 'cat' from page to page and when 'category' comes from a drop down menu
319 // then we also reset the qpage so we go to page 1 of
320 // a new cat.
321 if ($category && $category != $cat) { // Is this a move to a new category?
322 $pagevars['cat'] = $category;
323 $pagevars['qpage'] = 0;
324 } else {
325 $pagevars['cat'] = $cat; // If empty will be set up later.
328 if ($pagevars['cat']){
329 $thispageurl->param('cat', $pagevars['cat']);
332 if (strpos($baseurl, '/question/') === 0) {
333 navigation_node::override_active_url($thispageurl);
336 // This need to occur after the override_active_url call above because
337 // these values change on the page request causing the URLs to mismatch
338 // when trying to work out the active node.
339 for ($i = 1; $i <= core_question\local\bank\view::MAX_SORTS; $i++) {
340 $param = 'qbs' . $i;
341 if (isset($params[$param])) {
342 $value = clean_param($params[$param], PARAM_TEXT);
343 } else {
344 break;
346 $thispageurl->param($param, $value);
349 if ($pagevars['qpage'] > -1) {
350 $thispageurl->param('qpage', $pagevars['qpage']);
351 } else {
352 $pagevars['qpage'] = 0;
355 $pagevars['qperpage'] = question_set_or_get_user_preference(
356 'qperpage', $qperpage, DEFAULT_QUESTIONS_PER_PAGE, $thispageurl);
358 $defaultcategory = question_make_default_categories($contexts->all());
360 $contextlistarr = [];
361 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
362 $contextlistarr[] = "'{$context->id}'";
364 $contextlist = join(' ,', $contextlistarr);
365 if (!empty($pagevars['cat'])){
366 $catparts = explode(',', $pagevars['cat']);
367 if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
368 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
369 print_error('invalidcategory', 'question');
371 } else {
372 $category = $defaultcategory;
373 $pagevars['cat'] = "{$category->id},{$category->contextid}";
376 // Display options.
377 $pagevars['recurse'] = question_set_or_get_user_preference('recurse', $recurse, 1, $thispageurl);
378 $pagevars['showhidden'] = question_set_or_get_user_preference('showhidden', $showhidden, 0, $thispageurl);
379 $pagevars['qbshowtext'] = question_set_or_get_user_preference('qbshowtext', $qbshowtext, 0, $thispageurl);
381 // Category list page.
382 $pagevars['cpage'] = $cpage;
383 if ($pagevars['cpage'] != 1){
384 $thispageurl->param('cpage', $pagevars['cpage']);
387 $pagevars['qtagids'] = $qtagids;
388 foreach ($pagevars['qtagids'] as $index => $qtagid) {
389 $thispageurl->param("qtagids[{$index}]", $qtagid);
392 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
396 * Get the category id from $pagevars.
397 * @param array $pagevars from {@link question_edit_setup()}.
398 * @return int the category id.
400 function question_get_category_id_from_pagevars(array $pagevars) {
401 list($questioncategoryid) = explode(',', $pagevars['cat']);
402 return $questioncategoryid;
406 * Get a particular question preference that is also stored as a user preference.
407 * If the the value is given in the GET/POST request, then that value is used,
408 * and the user preference is updated to that value. Otherwise, the last set
409 * value of the user preference is used, or if it has never been set the default
410 * passed to this function.
412 * @param string $param the param name. The URL parameter set, and the GET/POST
413 * parameter read. The user_preference name is 'question_bank_' . $param.
414 * @param mixed $default The default value to use, if not otherwise set.
415 * @param int $type one of the PARAM_... constants.
416 * @param moodle_url $thispageurl if the value has been explicitly set, we add
417 * it to this URL.
418 * @return mixed the parameter value to use.
420 function question_get_display_preference($param, $default, $type, $thispageurl) {
421 $submittedvalue = optional_param($param, null, $type);
422 return question_set_or_get_user_preference($param, $submittedvalue, $default, $thispageurl);
426 * Get a user preference by name or set the user preference to a given value.
428 * If $value is null then the function will only attempt to retrieve the
429 * user preference requested by $name. If no user preference is found then the
430 * $default value will be returned. In this case the user preferences are not
431 * modified and nor are the params on $thispageurl.
433 * If $value is anything other than null then the function will set the user
434 * preference $name to the provided $value and will also set it as a param
435 * on $thispageurl.
437 * @param string $name The user_preference name is 'question_bank_' . $name.
438 * @param mixed $value The preference value.
439 * @param mixed $default The default value to use, if not otherwise set.
440 * @param moodle_url $thispageurl if the value has been explicitly set, we add
441 * it to this URL.
442 * @return mixed the parameter value to use.
444 function question_set_or_get_user_preference($name, $value, $default, $thispageurl) {
445 if (is_null($value)) {
446 return get_user_preferences('question_bank_' . $name, $default);
449 set_user_preference('question_bank_' . $name, $value);
450 $thispageurl->param($name, $value);
451 return $value;
455 * Make sure user is logged in as required in this context.
457 function require_login_in_context($contextorid = null){
458 global $DB, $CFG;
459 if (!is_object($contextorid)){
460 $context = context::instance_by_id($contextorid, IGNORE_MISSING);
461 } else {
462 $context = $contextorid;
464 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
465 require_login($context->instanceid);
466 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
467 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
468 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
469 print_error('invalidcourseid');
471 require_course_login($course, true, $cm);
473 } else {
474 print_error('invalidcoursemodule');
476 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
477 if (!empty($CFG->forcelogin)) {
478 require_login();
481 } else {
482 require_login();
487 * Print a form to let the user choose which question type to add.
488 * When the form is submitted, it goes to the question.php script.
489 * @param $hiddenparams hidden parameters to add to the form, in addition to
490 * the qtype radio buttons.
491 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
492 * those qtypes will be shown. Example value array('description', 'multichoice').
493 * @deprecated since Moodle 4.0
494 * @see \qbank_editquestion\editquestion_helper::print_choose_qtype_to_add_form()
495 * @todo Final deprecation of this class in moodle 4.4 MDL-72438
497 function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null, $enablejs = true) {
498 debugging('Function print_choose_qtype_to_add_form() is deprecated,
499 please use \qbank_editquestion\editquestion_helper::print_choose_qtype_to_add_form() instead.', DEBUG_DEVELOPER);
500 global $CFG, $PAGE, $OUTPUT;
502 $chooser = \qbank_editquestion\qbank_chooser::get($PAGE->course, $hiddenparams, $allowedqtypes);
503 $renderer = $PAGE->get_renderer('question', 'bank');
505 return $renderer->render($chooser);
509 * Print a button for creating a new question. This will open question/addquestion.php,
510 * which in turn goes to question/question.php before getting back to $params['returnurl']
511 * (by default the question bank screen).
513 * @param int $categoryid The id of the category that the new question should be added to.
514 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
515 * $params['courseid'], and you should probably set $params['returnurl']
516 * @param string $caption the text to display on the button.
517 * @param string $tooltip a tooltip to add to the button (optional).
518 * @param bool $disabled if true, the button will be disabled.
519 * @deprecated since Moodle 4.0
520 * @see \qbank_editquestion\editquestion_helper::create_new_question_button()
521 * @todo Final deprecation of this class in moodle 4.4 MDL-72438
523 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
524 debugging('Function create_new_question_button() has been deprecated and moved to bank/editquestion,
525 please use qbank_editquestion\editquestion_helper::create_new_question_button() instead.', DEBUG_DEVELOPER);
526 global $CFG, $PAGE, $OUTPUT;
527 static $choiceformprinted = false;
528 $params['category'] = $categoryid;
529 $url = new moodle_url('/question/bank/editquestion/addquestion.php', $params);
530 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
532 if (!$choiceformprinted) {
533 echo '<div id="qtypechoicecontainer">';
534 echo print_choose_qtype_to_add_form(array());
535 echo "</div>\n";
536 $choiceformprinted = true;