Search moodle.org's
Developer Documentation

See Release Notes

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

Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403] [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  defined('MOODLE_INTERNAL') || die();
  29  
  30  use core\output\datafilter;
  31  use core_question\local\bank\column_base;
  32  use core_question\local\bank\condition;
  33  use core_question\local\bank\column_manager_base;
  34  use core_question\local\bank\question_version_status;
  35  use mod_quiz\question\bank\filter\custom_category_condition;
  36  use qbank_managecategories\category_condition;
  37  
  38  require_once($CFG->dirroot . '/mod/quiz/locallib.php');
  39  /**
  40   * Subclass to customise the view of the question bank for the quiz editing screen.
  41   *
  42   * @copyright  2009 Tim Hunt
  43   * @author     2021 Safat Shahin <safatshahin@catalyst-au.net>
  44   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  45   */
  46  class custom_view extends \core_question\local\bank\view {
  47      /** @var int number of questions per page to show in the add from question bank modal. */
  48      const DEFAULT_PAGE_SIZE = 20;
  49  
  50      /** @var bool $quizhasattempts whether the quiz this is used by has been attemptd. */
  51      protected $quizhasattempts = false;
  52  
  53      /** @var \stdClass $quiz the quiz settings. */
  54      protected $quiz = false;
  55  
  56      /**
  57       * @var string $component the component the api is used from.
  58       */
  59      public $component = 'mod_quiz';
  60  
  61      /**
  62       * Constructor.
  63       * @param \core_question\local\bank\question_edit_contexts $contexts
  64       * @param \moodle_url $pageurl
  65       * @param \stdClass $course course settings
  66       * @param \stdClass $cm activity settings.
  67       * @param \stdClass $quiz quiz settings.
  68       */
  69      public function __construct($contexts, $pageurl, $course, $cm, $params, $extraparams) {
  70          // Default filter condition.
  71          if (!isset($params['filter'])) {
  72              $params['filter']  = [];
  73              [$categoryid, $contextid] = custom_category_condition::validate_category_param($params['cat']);
  74              if (!is_null($categoryid)) {
  75                  $category = custom_category_condition::get_category_record($categoryid, $contextid);
  76                  $params['filter']['category'] = [
  77                      'jointype' => custom_category_condition::JOINTYPE_DEFAULT,
  78                      'values' => [$category->id],
  79                      'filteroptions' => ['includesubcategories' => false],
  80                  ];
  81              }
  82          }
  83  
  84          $this->init_columns($this->wanted_columns(), $this->heading_column());
  85          parent::__construct($contexts, $pageurl, $course, $cm, $params, $extraparams);
  86          [$this->quiz, ] = get_module_from_cmid($cm->id);
  87          $this->set_quiz_has_attempts(quiz_has_attempts($this->quiz->id));
  88          $this->pagesize = self::DEFAULT_PAGE_SIZE;
  89      }
  90  
  91      /**
  92       * Just use the base column manager in this view.
  93       *
  94       * @return void
  95       */
  96      protected function init_column_manager(): void {
  97          $this->columnmanager = new column_manager_base();
  98      }
  99  
 100      /**
 101       * Don't display plugin controls.
 102       *
 103       * @param \core\context $context
 104       * @param int $categoryid
 105       * @return string
 106       */
 107      protected function get_plugin_controls(\core\context $context, int $categoryid): string {
 108          return '';
 109      }
 110  
 111      protected function get_question_bank_plugins(): array {
 112          $questionbankclasscolumns = [];
 113          $customviewcolumns = [
 114              'mod_quiz\question\bank\add_action_column' . column_base::ID_SEPARATOR  . 'add_action_column',
 115              'core_question\local\bank\checkbox_column' . column_base::ID_SEPARATOR . 'checkbox_column',
 116              'qbank_viewquestiontype\question_type_column' . column_base::ID_SEPARATOR . 'question_type_column',
 117              'mod_quiz\question\bank\question_name_text_column' . column_base::ID_SEPARATOR . 'question_name_text_column',
 118              'mod_quiz\question\bank\preview_action_column'  . column_base::ID_SEPARATOR  . 'preview_action_column',
 119          ];
 120  
 121          foreach ($customviewcolumns as $columnid) {
 122              [$columnclass, $columnname] = explode(column_base::ID_SEPARATOR, $columnid, 2);
 123              if (class_exists($columnclass)) {
 124                  $questionbankclasscolumns[$columnid] = $columnclass::from_column_name($this, $columnname);
 125              }
 126          }
 127  
 128          return $questionbankclasscolumns;
 129      }
 130  
 131      protected function heading_column(): string {
 132          return 'mod_quiz\\question\\bank\\question_name_text_column';
 133      }
 134  
 135      protected function default_sort(): array {
 136          // Using the extended class for quiz specific sort.
 137          return [
 138              'qbank_viewquestiontype__question_type_column' => SORT_ASC,
 139              'mod_quiz__question__bank__question_name_text_column' => SORT_ASC,
 140          ];
 141      }
 142  
 143      /**
 144       * Let the question bank display know whether the quiz has been attempted,
 145       * hence whether some bits of UI, like the add this question to the quiz icon,
 146       * should be displayed.
 147       *
 148       * @param bool $quizhasattempts whether the quiz has attempts.
 149       */
 150      private function set_quiz_has_attempts($quizhasattempts): void {
 151          $this->quizhasattempts = $quizhasattempts;
 152          if ($quizhasattempts && isset($this->visiblecolumns['addtoquizaction'])) {
 153              unset($this->visiblecolumns['addtoquizaction']);
 154          }
 155      }
 156  
 157      /**
 158       * URL of add to quiz.
 159       *
 160       * @param $questionid
 161       * @return \moodle_url
 162       */
 163      public function add_to_quiz_url($questionid) {
 164          $params = $this->baseurl->params();
 165          $params['addquestion'] = $questionid;
 166          $params['sesskey'] = sesskey();
 167          $params['cmid'] = $this->cm->id;
 168          return new \moodle_url('/mod/quiz/edit.php', $params);
 169      }
 170  
 171      /**
 172       * Renders the html question bank (same as display, but returns the result).
 173       *
 174       * Note that you can only output this rendered result once per page, as
 175       * it contains IDs which must be unique.
 176       *
 177       * @param array $pagevars
 178       * @param string $tabname
 179       * @return string HTML code for the form
 180       */
 181      public function render($pagevars, $tabname): string {
 182          ob_start();
 183          $this->display();
 184          $out = ob_get_contents();
 185          ob_end_clean();
 186          return $out;
 187      }
 188  
 189      protected function display_bottom_controls(\context $catcontext): void {
 190          $cmoptions = new \stdClass();
 191          $cmoptions->hasattempts = !empty($this->quizhasattempts);
 192  
 193          $canuseall = has_capability('moodle/question:useall', $catcontext);
 194  
 195          echo \html_writer::start_tag('div', ['class' => 'pt-2']);
 196          if ($canuseall) {
 197              // Add selected questions to the quiz.
 198              $params = [
 199                  'type' => 'submit',
 200                  'name' => 'add',
 201                  'class' => 'btn btn-primary',
 202                  'value' => get_string('addselectedquestionstoquiz', 'quiz'),
 203                  'data-action' => 'toggle',
 204                  'data-togglegroup' => 'qbank',
 205                  'data-toggle' => 'action',
 206                  'disabled' => true,
 207              ];
 208              echo \html_writer::empty_tag('input', $params);
 209          }
 210          echo \html_writer::end_tag('div');
 211      }
 212  
 213      /**
 214       * Override the base implementation in \core_question\local\bank\view
 215       * because we don't want to print new question form in the fragment
 216       * for the modal.
 217       *
 218       * @param false|mixed|\stdClass $category
 219       * @param bool $canadd
 220       */
 221      protected function create_new_question_form($category, $canadd): void {
 222      }
 223  
 224      /**
 225       * Override the base implementation in \core_question\local\bank\view
 226       * because we don't want to print the headers in the fragment
 227       * for the modal.
 228       */
 229      protected function display_question_bank_header(): void {
 230      }
 231  
 232      protected function build_query(): void {
 233          // Get the required tables and fields.
 234          [$fields, $joins] = $this->get_component_requirements(array_merge($this->requiredcolumns, $this->questionactions));
 235  
 236          // Build the order by clause.
 237          $sorts = [];
 238          foreach ($this->sort as $sortname => $sortorder) {
 239              [$colname, $subsort] = $this->parse_subsort($sortname);
 240              $sorts[] = $this->requiredcolumns[$colname]->sort_expression($sortorder == SORT_DESC, $subsort);
 241          }
 242  
 243          // Build the where clause.
 244          $latestversion = 'qv.version = (SELECT MAX(v.version)
 245                                            FROM {question_versions} v
 246                                            JOIN {question_bank_entries} be
 247                                              ON be.id = v.questionbankentryid
 248                                           WHERE be.id = qbe.id)';
 249          $onlyready = '((' . "qv.status = '" . question_version_status::QUESTION_STATUS_READY . "'" .'))';
 250          $this->sqlparams = [];
 251          $conditions = [];
 252          foreach ($this->searchconditions as $searchcondition) {
 253              if ($searchcondition->where()) {
 254                  $conditions[] = '((' . $searchcondition->where() .'))';
 255              }
 256              if ($searchcondition->params()) {
 257                  $this->sqlparams = array_merge($this->sqlparams, $searchcondition->params());
 258              }
 259          }
 260          $majorconditions = ['q.parent = 0', $latestversion, $onlyready];
 261          // Get higher level filter condition.
 262          $jointype = isset($this->pagevars['jointype']) ? (int)$this->pagevars['jointype'] : condition::JOINTYPE_DEFAULT;
 263          $nonecondition = ($jointype === datafilter::JOINTYPE_NONE) ? ' NOT ' : '';
 264          $separator = ($jointype === datafilter::JOINTYPE_ALL) ? ' AND ' : ' OR ';
 265          // Build the SQL.
 266          $sql = ' FROM {question} q ' . implode(' ', $joins);
 267          $sql .= ' WHERE ' . implode(' AND ', $majorconditions);
 268          if (!empty($conditions)) {
 269              $sql .= ' AND ' . $nonecondition . ' ( ';
 270              $sql .= implode($separator, $conditions);
 271              $sql .= ' ) ';
 272          }
 273          $this->countsql = 'SELECT count(1)' . $sql;
 274          $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
 275      }
 276  
 277      public function add_standard_search_conditions(): void {
 278          foreach ($this->plugins as $componentname => $plugin) {
 279              if (\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
 280                  $pluginentrypointobject = new $plugin();
 281                  if ($componentname === 'qbank_managecategories') {
 282                      $pluginentrypointobject = new quiz_managecategories_feature();
 283                  }
 284                  if ($componentname === 'qbank_viewquestiontext' || $componentname === 'qbank_deletequestion') {
 285                      continue;
 286                  }
 287                  $pluginobjects = $pluginentrypointobject->get_question_filters($this);
 288                  foreach ($pluginobjects as $pluginobject) {
 289                      $this->add_searchcondition($pluginobject, $pluginobject->get_condition_key());
 290                  }
 291              }
 292          }
 293      }
 294  
 295      /**
 296       * Return the quiz settings for the quiz this question bank is displayed in.
 297       *
 298       * @return bool|\stdClass
 299       */
 300      public function get_quiz() {
 301          return $this->quiz;
 302      }
 303  }