Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 and 403]

   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  /**
  18   * Defines the custom question bank view used on the Edit quiz page.
  19   *
  20   * @package   mod_quiz
  21   * @category  question
  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
  24   */
  25  
  26  namespace mod_quiz\question\bank;
  27  
  28  use core_question\local\bank\question_version_status;
  29  use mod_quiz\question\bank\filter\custom_category_condition;
  30  
  31  /**
  32   * Subclass to customise the view of the question bank for the quiz editing screen.
  33   *
  34   * @copyright  2009 Tim Hunt
  35   * @author     2021 Safat Shahin <safatshahin@catalyst-au.net>
  36   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class custom_view extends \core_question\local\bank\view {
  39      /** @var int number of questions per page to show in the add from question bank modal. */
  40      const DEFAULT_PAGE_SIZE = 20;
  41  
  42      /** @var bool $quizhasattempts whether the quiz this is used by has been attemptd. */
  43      protected $quizhasattempts = false;
  44  
  45      /** @var \stdClass $quiz the quiz settings. */
  46      protected $quiz = false;
  47  
  48      /** @var int The maximum displayed length of the category info. */
  49      const MAX_TEXT_LENGTH = 200;
  50  
  51      /**
  52       * Constructor.
  53       * @param \core_question\local\bank\question_edit_contexts $contexts
  54       * @param \moodle_url $pageurl
  55       * @param \stdClass $course course settings
  56       * @param \stdClass $cm activity settings.
  57       * @param \stdClass $quiz quiz settings.
  58       */
  59      public function __construct($contexts, $pageurl, $course, $cm, $quiz) {
  60          parent::__construct($contexts, $pageurl, $course, $cm);
  61          $this->quiz = $quiz;
  62          $this->pagesize = self::DEFAULT_PAGE_SIZE;
  63      }
  64  
  65      protected function get_question_bank_plugins(): array {
  66          $questionbankclasscolumns = [];
  67          $corequestionbankcolumns = [
  68              'add_action_column',
  69              'checkbox_column',
  70              'question_type_column',
  71              'question_name_text_column',
  72              'preview_action_column'
  73          ];
  74  
  75          if (question_get_display_preference('qbshowtext', 0, PARAM_INT, new \moodle_url(''))) {
  76              $corequestionbankcolumns[] = 'question_text_row';
  77          }
  78  
  79          foreach ($corequestionbankcolumns as $fullname) {
  80              $shortname = $fullname;
  81              if (class_exists('mod_quiz\\question\\bank\\' . $fullname)) {
  82                  $fullname = 'mod_quiz\\question\\bank\\' . $fullname;
  83                  $questionbankclasscolumns[$shortname] = new $fullname($this);
  84              } else if (class_exists('core_question\\local\\bank\\' . $fullname)) {
  85                  $fullname = 'core_question\\local\\bank\\' . $fullname;
  86                  $questionbankclasscolumns[$shortname] = new $fullname($this);
  87              } else {
  88                  $questionbankclasscolumns[$shortname] = '';
  89              }
  90          }
  91          $plugins = \core_component::get_plugin_list_with_class('qbank', 'plugin_feature', 'plugin_feature.php');
  92          foreach ($plugins as $componentname => $plugin) {
  93              $pluginentrypointobject = new $plugin();
  94              $plugincolumnobjects = $pluginentrypointobject->get_question_columns($this);
  95              // Don't need the plugins without column objects.
  96              if (empty($plugincolumnobjects)) {
  97                  unset($plugins[$componentname]);
  98                  continue;
  99              }
 100              foreach ($plugincolumnobjects as $columnobject) {
 101                  $columnname = $columnobject->get_column_name();
 102                  foreach ($corequestionbankcolumns as $key => $corequestionbankcolumn) {
 103                      if (!\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
 104                          unset($questionbankclasscolumns[$columnname]);
 105                          continue;
 106                      }
 107                      // Check if it has custom preference selector to view/hide.
 108                      if ($columnobject->has_preference() && !$columnobject->get_preference()) {
 109                          continue;
 110                      }
 111                      if ($corequestionbankcolumn === $columnname) {
 112                          $questionbankclasscolumns[$columnname] = $columnobject;
 113                      }
 114                  }
 115              }
 116          }
 117  
 118          // Mitigate the error in case of any regression.
 119          foreach ($questionbankclasscolumns as $shortname => $questionbankclasscolumn) {
 120              if (empty($questionbankclasscolumn)) {
 121                  unset($questionbankclasscolumns[$shortname]);
 122              }
 123          }
 124  
 125          return $questionbankclasscolumns;
 126      }
 127  
 128      protected function heading_column(): string {
 129          return 'mod_quiz\\question\\bank\\question_name_text_column';
 130      }
 131  
 132      protected function default_sort(): array {
 133          // Using the extended class for quiz specific sort.
 134          return [
 135              'qbank_viewquestiontype\\question_type_column' => 1,
 136              'mod_quiz\\question\\bank\\question_name_text_column' => 1,
 137          ];
 138      }
 139  
 140      /**
 141       * Let the question bank display know whether the quiz has been attempted,
 142       * hence whether some bits of UI, like the add this question to the quiz icon,
 143       * should be displayed.
 144       *
 145       * @param bool $quizhasattempts whether the quiz has attempts.
 146       */
 147      public function set_quiz_has_attempts($quizhasattempts): void {
 148          $this->quizhasattempts = $quizhasattempts;
 149          if ($quizhasattempts && isset($this->visiblecolumns['addtoquizaction'])) {
 150              unset($this->visiblecolumns['addtoquizaction']);
 151          }
 152      }
 153  
 154      /**
 155       * Question preview url.
 156       *
 157       * @param \stdClass $question
 158       * @return \moodle_url
 159       */
 160      public function preview_question_url($question) {
 161          return quiz_question_preview_url($this->quiz, $question);
 162      }
 163  
 164      /**
 165       * URL of add to quiz.
 166       *
 167       * @param $questionid
 168       * @return \moodle_url
 169       */
 170      public function add_to_quiz_url($questionid) {
 171          $params = $this->baseurl->params();
 172          $params['addquestion'] = $questionid;
 173          $params['sesskey'] = sesskey();
 174          return new \moodle_url('/mod/quiz/edit.php', $params);
 175      }
 176  
 177      /**
 178       * Renders the html question bank (same as display, but returns the result).
 179       *
 180       * Note that you can only output this rendered result once per page, as
 181       * it contains IDs which must be unique.
 182       *
 183       * @param array $pagevars
 184       * @param string $tabname
 185       * @return string HTML code for the form
 186       */
 187      public function render($pagevars, $tabname): string {
 188          ob_start();
 189          $this->display($pagevars, $tabname);
 190          $out = ob_get_contents();
 191          ob_end_clean();
 192          return $out;
 193      }
 194  
 195      protected function display_bottom_controls(\context $catcontext): void {
 196          $cmoptions = new \stdClass();
 197          $cmoptions->hasattempts = !empty($this->quizhasattempts);
 198  
 199          $canuseall = has_capability('moodle/question:useall', $catcontext);
 200  
 201          echo \html_writer::start_tag('div', ['class' => 'pt-2']);
 202          if ($canuseall) {
 203              // Add selected questions to the quiz.
 204              $params = [
 205                  'type' => 'submit',
 206                  'name' => 'add',
 207                  'class' => 'btn btn-primary',
 208                  'value' => get_string('addselectedquestionstoquiz', 'quiz'),
 209                  'data-action' => 'toggle',
 210                  'data-togglegroup' => 'qbank',
 211                  'data-toggle' => 'action',
 212                  'disabled' => true,
 213              ];
 214              echo \html_writer::empty_tag('input', $params);
 215          }
 216          echo \html_writer::end_tag('div');
 217      }
 218  
 219      protected function create_new_question_form($category, $canadd): void {
 220          // Don't display this.
 221      }
 222  
 223      /**
 224       * Override the base implementation in \core_question\local\bank\view
 225       * because we don't want to print the headers in the fragment
 226       * for the modal.
 227       */
 228      protected function display_question_bank_header(): void {
 229      }
 230  
 231      /**
 232       * Override the base implementation in \core_question\bank\view
 233       * because we don't want it to read from the $_POST global variables
 234       * for the sort parameters since they are not present in a fragment.
 235       *
 236       * Unfortunately the best we can do is to look at the URL for
 237       * those parameters (only marginally better really).
 238       */
 239      protected function init_sort_from_params(): void {
 240          $this->sort = [];
 241          for ($i = 1; $i <= self::MAX_SORTS; $i++) {
 242              if (!$sort = $this->baseurl->param('qbs' . $i)) {
 243                  break;
 244              }
 245              // Work out the appropriate order.
 246              $order = 1;
 247              if ($sort[0] == '-') {
 248                  $order = -1;
 249                  $sort = substr($sort, 1);
 250                  if (!$sort) {
 251                      break;
 252                  }
 253              }
 254              // Deal with subsorts.
 255              list($colname) = $this->parse_subsort($sort);
 256              $this->get_column_type($colname);
 257              $this->sort[$sort] = $order;
 258          }
 259      }
 260  
 261      protected function build_query(): void {
 262          // Get the required tables and fields.
 263          $joins = [];
 264          $fields = ['qv.status', 'qc.id as categoryid', 'qv.version', 'qv.id as versionid', 'qbe.id as questionbankentryid'];
 265          if (!empty($this->requiredcolumns)) {
 266              foreach ($this->requiredcolumns as $column) {
 267                  $extrajoins = $column->get_extra_joins();
 268                  foreach ($extrajoins as $prefix => $join) {
 269                      if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
 270                          throw new \coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
 271                      }
 272                      $joins[$prefix] = $join;
 273                  }
 274                  $fields = array_merge($fields, $column->get_required_fields());
 275              }
 276          }
 277          $fields = array_unique($fields);
 278  
 279          // Build the order by clause.
 280          $sorts = [];
 281          foreach ($this->sort as $sort => $order) {
 282              list($colname, $subsort) = $this->parse_subsort($sort);
 283              $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
 284          }
 285  
 286          // Build the where clause.
 287          $latestversion = 'qv.version = (SELECT MAX(v.version)
 288                                            FROM {question_versions} v
 289                                            JOIN {question_bank_entries} be
 290                                              ON be.id = v.questionbankentryid
 291                                           WHERE be.id = qbe.id)';
 292          $readyonly = "qv.status = '" . question_version_status::QUESTION_STATUS_READY . "' ";
 293          $tests = ['q.parent = 0', $latestversion, $readyonly];
 294          $this->sqlparams = [];
 295          foreach ($this->searchconditions as $searchcondition) {
 296              if ($searchcondition->where()) {
 297                  $tests[] = '((' . $searchcondition->where() .'))';
 298              }
 299              if ($searchcondition->params()) {
 300                  $this->sqlparams = array_merge($this->sqlparams, $searchcondition->params());
 301              }
 302          }
 303          // Build the SQL.
 304          $sql = ' FROM {question} q ' . implode(' ', $joins);
 305          $sql .= ' WHERE ' . implode(' AND ', $tests);
 306          $this->countsql = 'SELECT count(1)' . $sql;
 307          $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
 308      }
 309  
 310      public function wanted_filters($cat, $tagids, $showhidden, $recurse, $editcontexts, $showquestiontext): void {
 311          global $CFG;
 312          list(, $contextid) = explode(',', $cat);
 313          $catcontext = \context::instance_by_id($contextid);
 314          $thiscontext = $this->get_most_specific_context();
 315          // Category selection form.
 316          $this->display_question_bank_header();
 317  
 318          // Display tag filter if usetags setting is enabled/enablefilters is true.
 319          if ($this->enablefilters) {
 320              if (is_array($this->customfilterobjects)) {
 321                  foreach ($this->customfilterobjects as $filterobjects) {
 322                      $this->searchconditions[] = $filterobjects;
 323                  }
 324              } else {
 325                  if ($CFG->usetags) {
 326                      array_unshift($this->searchconditions,
 327                          new \core_question\bank\search\tag_condition([$catcontext, $thiscontext], $tagids));
 328                  }
 329  
 330                  array_unshift($this->searchconditions, new \core_question\bank\search\hidden_condition(!$showhidden));
 331                  array_unshift($this->searchconditions, new custom_category_condition(
 332                      $cat, $recurse, $editcontexts, $this->baseurl, $this->course));
 333              }
 334          }
 335          $this->display_options_form($showquestiontext);
 336      }
 337  }