PageRenderTime 66ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/question/editlib.php

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