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 * Functions used to show question editing interface
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
26 use core\output\datafilter
;
28 defined('MOODLE_INTERNAL') ||
die();
30 require_once($CFG->libdir
. '/questionlib.php');
32 define('DEFAULT_QUESTIONS_PER_PAGE', 100);
33 define('MAXIMUM_QUESTIONS_PER_PAGE', 4000);
35 function get_module_from_cmid($cmid) {
37 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
38 FROM {course_modules} cm,
41 md.id = cm.module", array($cmid))){
42 throw new \
moodle_exception('invalidcoursemodule');
43 } elseif (!$modrec =$DB->get_record($cmrec->modname
, array('id' => $cmrec->instance
))) {
44 throw new \
moodle_exception('invalidcoursemodule');
46 $modrec->instance
= $modrec->id
;
47 $modrec->cmid
= $cmrec->id
;
48 $cmrec->name
= $modrec->name
;
50 return array($modrec, $cmrec);
54 * Function to read all questions for category into big array
56 * @param object $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
60 * @param bool $latestversion if only the latest versions needed
63 function get_questions_category(object $category, bool $noparent, bool $recurse = true, bool $export = true,
64 bool $latestversion = false): array {
67 // Build sql bit for $noparent.
70 $npsql = " and q.parent='0' ";
73 // Get list of categories.
75 $categorylist = question_categorylist($category->id
);
77 $categorylist = [$category->id
];
80 // Get the list of questions for the category.
81 list($usql, $params) = $DB->get_in_or_equal($categorylist);
83 // Get the latest version of a question.
86 $version = 'AND (qv.version = (SELECT MAX(v.version)
87 FROM {question_versions} v
88 JOIN {question_bank_entries} be
89 ON be.id = v.questionbankentryid
90 WHERE be.id = qbe.id) OR qv.version is null)';
92 $questions = $DB->get_records_sql("SELECT q.*, qv.status, qc.id AS category
94 JOIN {question_versions} qv ON qv.questionid = q.id
95 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
96 JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
97 WHERE qc.id {$usql} {$npsql} {$version}
98 ORDER BY qc.id, q.qtype, q.name", $params);
100 // Iterate through questions, getting stuff we need.
102 foreach($questions as $key => $question) {
103 $question->export_process
= $export;
104 $qtype = question_bank
::get_qtype($question->qtype
, false);
105 if ($export && $qtype->name() === 'missingtype') {
106 // Unrecognised question type. Skip this question when exporting.
109 $qtype->get_question_options($question);
110 $qresults[] = $question;
117 * Checks whether this is the only child of a top category in a context.
119 * @param int $categoryid a category id.
121 * @deprecated since Moodle 4.0 MDL-71585
122 * @see qbank_managecategories\helper
123 * @todo Final deprecation on Moodle 4.4 MDL-72438
125 function question_is_only_child_of_top_category_in_context($categoryid) {
126 debugging('Function question_is_only_child_of_top_category_in_context()
127 has been deprecated and moved to qbank_managecategories plugin,
128 Please use qbank_managecategories\helper::question_is_only_child_of_top_category_in_context() instead.',
130 return \qbank_managecategories\helper
::question_is_only_child_of_top_category_in_context($categoryid);
134 * Checks whether the category is a "Top" category (with no parent).
136 * @param int $categoryid a category id.
138 * @deprecated since Moodle 4.0 MDL-71585
139 * @see qbank_managecategories\helper
140 * @todo Final deprecation on Moodle 4.4 MDL-72438
142 function question_is_top_category($categoryid) {
143 debugging('Function question_is_top_category() has been deprecated and moved to qbank_managecategories plugin,
144 Please use qbank_managecategories\helper::question_is_top_category() instead.', DEBUG_DEVELOPER
);
145 return \qbank_managecategories\helper
::question_is_top_category($categoryid);
149 * Ensures that this user is allowed to delete this category.
151 * @param int $todelete a category id.
152 * @deprecated since Moodle 4.0 MDL-71585
153 * @see qbank_managecategories\helper
154 * @todo Final deprecation on Moodle 4.4 MDL-72438
156 function question_can_delete_cat($todelete) {
157 debugging('Function question_can_delete_cat() has been deprecated and moved to qbank_managecategories plugin,
158 Please use qbank_managecategories\helper::question_can_delete_cat() instead.', DEBUG_DEVELOPER
);
159 \qbank_managecategories\helper
::question_can_delete_cat($todelete);
163 * Common setup for all pages for editing questions.
164 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
165 * @param string $edittab code for this edit tab
166 * @param bool $requirecmid require cmid? default false
167 * @param bool $unused no longer used, do no pass
168 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
170 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $unused = null) {
173 if ($unused !== null) {
174 debugging('Deprecated argument passed to question_edit_setup()', DEBUG_DEVELOPER
);
180 $params['cmid'] = required_param('cmid', PARAM_INT
);
182 $params['cmid'] = optional_param('cmid', null, PARAM_INT
);
185 if (!$params['cmid']) {
186 $params['courseid'] = required_param('courseid', PARAM_INT
);
189 $params['qpage'] = optional_param('qpage', null, PARAM_INT
);
191 // Pass 'cat' from page to page and when 'category' comes from a drop down menu
192 // then we also reset the qpage so we go to page 1 of
194 $params['cat'] = optional_param('cat', null, PARAM_SEQUENCE
); // If empty will be set up later.
195 $params['category'] = optional_param('category', null, PARAM_SEQUENCE
);
196 $params['qperpage'] = optional_param('qperpage', null, PARAM_INT
);
199 $params['filter'] = optional_param('filter', null, PARAM_RAW
);
201 // Category list page.
202 $params['cpage'] = optional_param('cpage', null, PARAM_INT
);
205 $params['sortdata'] = optional_param_array('sortdata', [], PARAM_INT
);
207 $PAGE->set_pagelayout('admin');
209 return question_build_edit_resources($edittab, $baseurl, $params);
213 * Common function for building the generic resources required by the
214 * editing questions pages.
216 * Either a cmid or a course id must be provided as keys in $params or
217 * an exception will be thrown. All other params are optional and will have
218 * sane default applied if not provided.
220 * The acceptable keys for $params are:
222 * 'cmid' => PARAM_INT,
223 * 'courseid' => PARAM_INT,
224 * 'qpage' => PARAM_INT,
225 * 'cat' => PARAM_SEQUENCE,
226 * 'category' => PARAM_SEQUENCE,
227 * 'qperpage' => PARAM_INT,
228 * 'cpage' => PARAM_INT,
229 * 'recurse' => PARAM_BOOL,
230 * 'showhidden' => PARAM_BOOL,
231 * 'qbshowtext' => PARAM_INT,
232 * 'qtagids' => [PARAM_INT], (array of integers)
233 * 'qbs1' => PARAM_TEXT,
234 * 'qbs2' => PARAM_TEXT,
235 * 'qbs3' => PARAM_TEXT,
236 * ... and more qbs keys up to core_question\local\bank\view::MAX_SORTS ...
239 * @param string $edittab Code for this edit tab
240 * @param string $baseurl The name of the script calling this funciton. For examle 'qusetion/edit.php'.
241 * @param array $params The provided parameters to construct the resources with.
242 * @param int $defaultquestionsperpage number of questions per page, if not given in the URL.
243 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
245 function question_build_edit_resources($edittab, $baseurl, $params,
246 $defaultquestionsperpage = DEFAULT_QUESTIONS_PER_PAGE
) {
249 $thispageurl = new moodle_url($baseurl);
250 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
258 'courseid' => PARAM_INT
,
259 'qpage' => PARAM_INT
,
260 'cat' => PARAM_SEQUENCE
,
261 'category' => PARAM_SEQUENCE
,
262 'qperpage' => PARAM_INT
,
263 'cpage' => PARAM_INT
,
266 foreach ($paramtypes as $name => $type) {
267 if (isset($params[$name])) {
268 $cleanparams[$name] = clean_param($params[$name], $type);
270 $cleanparams[$name] = null;
274 if (!empty($params['filter'])) {
275 if (!is_array($params['filter'])) {
276 $params['filter'] = json_decode($params['filter'], true);
278 $cleanparams['filter'] = $params['filter'];
281 if (isset($params['sortdata'])) {
282 $cleanparams['sortdata'] = clean_param_array($params['sortdata'], PARAM_INT
);
285 $cmid = $cleanparams['cmid'];
286 $courseid = $cleanparams['courseid'];
287 $qpage = $cleanparams['qpage'] ?
: -1;
288 $cat = $cleanparams['cat'] ?
: 0;
289 $category = $cleanparams['category'] ?
: 0;
290 $qperpage = $cleanparams['qperpage'];
291 $cpage = $cleanparams['cpage'] ?
: 1;
293 if (is_null($cmid) && is_null($courseid)) {
294 throw new \
moodle_exception('Must provide a cmid or courseid');
298 list($module, $cm) = get_module_from_cmid($cmid);
299 $courseid = $cm->course
;
300 $thispageurl->params(compact('cmid'));
301 $thiscontext = context_module
::instance($cmid);
305 $thispageurl->params(compact('courseid'));
306 $thiscontext = context_course
::instance($courseid);
309 if (defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
310 // For AJAX, we don't need to set up the course page for output.
313 require_login($courseid, false, $cm);
317 $contexts = new core_question\local\bank\
question_edit_contexts($thiscontext);
318 $contexts->require_one_edit_tab_cap($edittab);
323 $pagevars['qpage'] = $qpage;
325 // Pass 'cat' from page to page and when 'category' comes from a drop down menu
326 // then we also reset the qpage so we go to page 1 of
328 if ($category && $category != $cat) { // Is this a move to a new category?
329 $pagevars['cat'] = $category;
330 $pagevars['qpage'] = 0;
332 $pagevars['cat'] = $cat; // If empty will be set up later.
335 if ($pagevars['cat']){
336 $thispageurl->param('cat', $pagevars['cat']);
339 if (strpos($baseurl, '/question/') === 0) {
340 navigation_node
::override_active_url($thispageurl);
343 if ($pagevars['qpage'] > -1) {
344 $thispageurl->param('qpage', $pagevars['qpage']);
346 $pagevars['qpage'] = 0;
349 if ($defaultquestionsperpage == DEFAULT_QUESTIONS_PER_PAGE
) {
350 $pagevars['qperpage'] = question_set_or_get_user_preference(
351 'qperpage', $qperpage, DEFAULT_QUESTIONS_PER_PAGE
, $thispageurl);
353 $pagevars['qperpage'] = $qperpage ??
$defaultquestionsperpage;
356 $defaultcategory = question_make_default_categories($contexts->all());
358 $contextlistarr = [];
359 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
360 $contextlistarr[] = "'{$context->id}'";
362 $contextlist = join(' ,', $contextlistarr);
363 if (!empty($pagevars['cat'])){
364 $catparts = explode(',', $pagevars['cat']);
365 if (!$catparts[0] ||
(false !== array_search($catparts[1], $contextlistarr)) ||
366 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
367 throw new \
moodle_exception('invalidcategory', 'question');
370 $category = $defaultcategory;
371 $pagevars['cat'] = "{$category->id},{$category->contextid}";
374 // Category list page.
375 $pagevars['cpage'] = $cpage;
376 if ($pagevars['cpage'] != 1){
377 $thispageurl->param('cpage', $pagevars['cpage']);
380 if ($cleanparams['filter']) {
381 $pagevars['filter'] = $cleanparams['filter'];
382 $thispageurl->param('filter', json_encode($cleanparams['filter']));
384 $pagevars['tabname'] = $edittab;
387 $pagevars['sortdata'] = $cleanparams['sortdata'];
388 foreach ($pagevars['sortdata'] as $sortname => $sortorder) {
389 $thispageurl->param('sortdata[' . $sortname . ']', $sortorder);
392 // Enforce ALL as the only allowed top-level join type, so we can't bypass filtering by category.
393 $pagevars['jointype'] = datafilter
::JOINTYPE_ALL
;
395 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
399 * Get the category id from $pagevars.
400 * @param array $pagevars from {@link question_edit_setup()}.
401 * @return int the category id.
403 function question_get_category_id_from_pagevars(array $pagevars) {
404 list($questioncategoryid) = explode(',', $pagevars['cat']);
405 return $questioncategoryid;
409 * Get a particular question preference that is also stored as a user preference.
410 * If the the value is given in the GET/POST request, then that value is used,
411 * and the user preference is updated to that value. Otherwise, the last set
412 * value of the user preference is used, or if it has never been set the default
413 * passed to this function.
415 * @param string $param the param name. The URL parameter set, and the GET/POST
416 * parameter read. The user_preference name is 'question_bank_' . $param.
417 * @param mixed $default The default value to use, if not otherwise set.
418 * @param int $type one of the PARAM_... constants.
419 * @param moodle_url $thispageurl if the value has been explicitly set, we add
421 * @return mixed the parameter value to use.
423 function question_get_display_preference($param, $default, $type, $thispageurl) {
424 $submittedvalue = optional_param($param, null, $type);
425 return question_set_or_get_user_preference($param, $submittedvalue, $default, $thispageurl);
429 * Get a user preference by name or set the user preference to a given value.
431 * If $value is null then the function will only attempt to retrieve the
432 * user preference requested by $name. If no user preference is found then the
433 * $default value will be returned. In this case the user preferences are not
434 * modified and nor are the params on $thispageurl.
436 * If $value is anything other than null then the function will set the user
437 * preference $name to the provided $value and will also set it as a param
440 * @param string $name The user_preference name is 'question_bank_' . $name.
441 * @param mixed $value The preference value.
442 * @param mixed $default The default value to use, if not otherwise set.
443 * @param moodle_url $thispageurl if the value has been explicitly set, we add
445 * @return mixed the parameter value to use.
447 function question_set_or_get_user_preference($name, $value, $default, $thispageurl) {
448 if (is_null($value)) {
449 return get_user_preferences('question_bank_' . $name, $default);
452 set_user_preference('question_bank_' . $name, $value);
453 $thispageurl->param($name, $value);
458 * Make sure user is logged in as required in this context.
460 function require_login_in_context($contextorid = null){
462 if (!is_object($contextorid)){
463 $context = context
::instance_by_id($contextorid, IGNORE_MISSING
);
465 $context = $contextorid;
467 if ($context && ($context->contextlevel
== CONTEXT_COURSE
)) {
468 require_login($context->instanceid
);
469 } else if ($context && ($context->contextlevel
== CONTEXT_MODULE
)) {
470 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid
))) {
471 if (!$course = $DB->get_record('course', array('id' => $cm->course
))) {
472 throw new \
moodle_exception('invalidcourseid');
474 require_course_login($course, true, $cm);
477 throw new \
moodle_exception('invalidcoursemodule');
479 } else if ($context && ($context->contextlevel
== CONTEXT_SYSTEM
)) {
480 if (!empty($CFG->forcelogin
)) {
490 * Print a form to let the user choose which question type to add.
491 * When the form is submitted, it goes to the question.php script.
492 * @param $hiddenparams hidden parameters to add to the form, in addition to
493 * the qtype radio buttons.
494 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
495 * those qtypes will be shown. Example value array('description', 'multichoice').
496 * @deprecated since Moodle 4.0
497 * @see \qbank_editquestion\editquestion_helper::print_choose_qtype_to_add_form()
498 * @todo Final deprecation of this class in moodle 4.4 MDL-72438
500 function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null, $enablejs = true) {
501 debugging('Function print_choose_qtype_to_add_form() is deprecated,
502 please use \qbank_editquestion\editquestion_helper::print_choose_qtype_to_add_form() instead.', DEBUG_DEVELOPER
);
503 global $CFG, $PAGE, $OUTPUT;
505 $chooser = \qbank_editquestion\qbank_chooser
::get($PAGE->course
, $hiddenparams, $allowedqtypes);
506 $renderer = $PAGE->get_renderer('question', 'bank');
508 return $renderer->render($chooser);
512 * Print a button for creating a new question. This will open question/addquestion.php,
513 * which in turn goes to question/question.php before getting back to $params['returnurl']
514 * (by default the question bank screen).
516 * @param int $categoryid The id of the category that the new question should be added to.
517 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
518 * $params['courseid'], and you should probably set $params['returnurl']
519 * @param string $caption the text to display on the button.
520 * @param string $tooltip a tooltip to add to the button (optional).
521 * @param bool $disabled if true, the button will be disabled.
522 * @deprecated since Moodle 4.0
523 * @see \qbank_editquestion\editquestion_helper::create_new_question_button()
524 * @todo Final deprecation of this class in moodle 4.4 MDL-72438
526 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
527 debugging('Function create_new_question_button() has been deprecated and moved to bank/editquestion,
528 please use qbank_editquestion\editquestion_helper::create_new_question_button() instead.', DEBUG_DEVELOPER
);
529 global $CFG, $PAGE, $OUTPUT;
530 static $choiceformprinted = false;
531 $params['category'] = $categoryid;
532 $url = new moodle_url('/question/bank/editquestion/addquestion.php', $params);
533 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
535 if (!$choiceformprinted) {
536 echo '<div id="qtypechoicecontainer">';
537 echo print_choose_qtype_to_add_form(array());
539 $choiceformprinted = true;