Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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;
1441 ariadna 31
use core\output\html_writer;
1 efrain 32
use core_question\local\bank\column_base;
33
use core_question\local\bank\condition;
34
use core_question\local\bank\column_manager_base;
1441 ariadna 35
use core_question\local\bank\filter_condition_manager;
1 efrain 36
use core_question\local\bank\question_version_status;
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
    /**
1441 ariadna 62
     * Determine if the 'switch question bank' button must be displayed.
63
     *
64
     * @var bool
65
     */
66
    protected bool $requirebankswitch;
67
 
68
    /**
1 efrain 69
     * Constructor.
70
     * @param \core_question\local\bank\question_edit_contexts $contexts
71
     * @param \moodle_url $pageurl
72
     * @param \stdClass $course course settings
73
     * @param \stdClass $cm activity settings.
74
     * @param \stdClass $quiz quiz settings.
75
     */
76
    public function __construct($contexts, $pageurl, $course, $cm, $params, $extraparams) {
77
        // Default filter condition.
78
        if (!isset($params['filter'])) {
1441 ariadna 79
            $params['filter']  = filter_condition_manager::get_default_filter($params['cat']);
80
            // The quiz question bank modal doesn't include a hidden filter option.
81
            // Therefore, the default filter hidden condition is unnecessary.
82
            unset($params['filter']['hidden']);
1 efrain 83
        }
84
 
85
        $this->init_columns($this->wanted_columns(), $this->heading_column());
1441 ariadna 86
        $this->pagesize = self::DEFAULT_PAGE_SIZE;
1 efrain 87
        parent::__construct($contexts, $pageurl, $course, $cm, $params, $extraparams);
1441 ariadna 88
        [$this->quiz, ] = get_module_from_cmid($extraparams['quizcmid']);
1 efrain 89
        $this->set_quiz_has_attempts(quiz_has_attempts($this->quiz->id));
1441 ariadna 90
        $this->requirebankswitch = $extraparams['requirebankswitch'] ?? true;
1 efrain 91
    }
92
 
93
    /**
94
     * Just use the base column manager in this view.
95
     *
96
     * @return void
97
     */
98
    protected function init_column_manager(): void {
99
        $this->columnmanager = new column_manager_base();
100
    }
101
 
102
    /**
103
     * Don't display plugin controls.
104
     *
105
     * @param \core\context $context
106
     * @param int $categoryid
107
     * @return string
108
     */
109
    protected function get_plugin_controls(\core\context $context, int $categoryid): string {
110
        return '';
111
    }
112
 
113
    protected function get_question_bank_plugins(): array {
114
        $questionbankclasscolumns = [];
115
        $customviewcolumns = [
116
            'mod_quiz\question\bank\add_action_column' . column_base::ID_SEPARATOR  . 'add_action_column',
117
            'core_question\local\bank\checkbox_column' . column_base::ID_SEPARATOR . 'checkbox_column',
118
            'qbank_viewquestiontype\question_type_column' . column_base::ID_SEPARATOR . 'question_type_column',
119
            'mod_quiz\question\bank\question_name_text_column' . column_base::ID_SEPARATOR . 'question_name_text_column',
120
            'mod_quiz\question\bank\preview_action_column'  . column_base::ID_SEPARATOR  . 'preview_action_column',
121
        ];
122
 
123
        foreach ($customviewcolumns as $columnid) {
124
            [$columnclass, $columnname] = explode(column_base::ID_SEPARATOR, $columnid, 2);
125
            if (class_exists($columnclass)) {
126
                $questionbankclasscolumns[$columnid] = $columnclass::from_column_name($this, $columnname);
127
            }
128
        }
129
 
130
        return $questionbankclasscolumns;
131
    }
132
 
133
    protected function heading_column(): string {
134
        return 'mod_quiz\\question\\bank\\question_name_text_column';
135
    }
136
 
137
    protected function default_sort(): array {
138
        // Using the extended class for quiz specific sort.
139
        return [
140
            'qbank_viewquestiontype__question_type_column' => SORT_ASC,
141
            'mod_quiz__question__bank__question_name_text_column' => SORT_ASC,
142
        ];
143
    }
144
 
145
    /**
146
     * Let the question bank display know whether the quiz has been attempted,
147
     * hence whether some bits of UI, like the add this question to the quiz icon,
148
     * should be displayed.
149
     *
150
     * @param bool $quizhasattempts whether the quiz has attempts.
151
     */
152
    private function set_quiz_has_attempts($quizhasattempts): void {
153
        $this->quizhasattempts = $quizhasattempts;
154
        if ($quizhasattempts && isset($this->visiblecolumns['addtoquizaction'])) {
155
            unset($this->visiblecolumns['addtoquizaction']);
156
        }
157
    }
158
 
159
    /**
160
     * URL of add to quiz.
161
     *
162
     * @param $questionid
163
     * @return \moodle_url
164
     */
165
    public function add_to_quiz_url($questionid) {
166
        $params = $this->baseurl->params();
167
        $params['addquestion'] = $questionid;
168
        $params['sesskey'] = sesskey();
169
        $params['cmid'] = $this->cm->id;
170
        return new \moodle_url('/mod/quiz/edit.php', $params);
171
    }
172
 
173
    /**
174
     * Renders the html question bank (same as display, but returns the result).
175
     *
176
     * Note that you can only output this rendered result once per page, as
177
     * it contains IDs which must be unique.
178
     *
179
     * @param array $pagevars
180
     * @param string $tabname
181
     * @return string HTML code for the form
182
     */
183
    public function render($pagevars, $tabname): string {
184
        ob_start();
185
        $this->display();
186
        $out = ob_get_contents();
187
        ob_end_clean();
188
        return $out;
189
    }
190
 
191
    protected function display_bottom_controls(\context $catcontext): void {
192
        $cmoptions = new \stdClass();
193
        $cmoptions->hasattempts = !empty($this->quizhasattempts);
194
 
195
        $canuseall = has_capability('moodle/question:useall', $catcontext);
196
 
197
        echo \html_writer::start_tag('div', ['class' => 'pt-2']);
198
        if ($canuseall) {
199
            // Add selected questions to the quiz.
200
            $params = [
201
                'type' => 'submit',
202
                'name' => 'add',
203
                'class' => 'btn btn-primary',
204
                'value' => get_string('addselectedquestionstoquiz', 'quiz'),
205
                'data-action' => 'toggle',
206
                'data-togglegroup' => 'qbank',
207
                'data-toggle' => 'action',
208
                'disabled' => true,
209
            ];
210
            echo \html_writer::empty_tag('input', $params);
211
        }
212
        echo \html_writer::end_tag('div');
213
    }
214
 
215
    /**
216
     * Override the base implementation in \core_question\local\bank\view
217
     * because we don't want to print new question form in the fragment
218
     * for the modal.
219
     *
220
     * @param false|mixed|\stdClass $category
221
     * @param bool $canadd
222
     */
223
    protected function create_new_question_form($category, $canadd): void {
224
    }
225
 
226
    /**
227
     * Override the base implementation in \core_question\local\bank\view
228
     * because we don't want to print the headers in the fragment
229
     * for the modal.
230
     */
231
    protected function display_question_bank_header(): void {
232
    }
233
 
234
    protected function build_query(): void {
235
        // Get the required tables and fields.
236
        [$fields, $joins] = $this->get_component_requirements(array_merge($this->requiredcolumns, $this->questionactions));
237
 
238
        // Build the order by clause.
239
        $sorts = [];
240
        foreach ($this->sort as $sortname => $sortorder) {
241
            [$colname, $subsort] = $this->parse_subsort($sortname);
242
            $sorts[] = $this->requiredcolumns[$colname]->sort_expression($sortorder == SORT_DESC, $subsort);
243
        }
244
 
245
        // Build the where clause.
246
        $latestversion = 'qv.version = (SELECT MAX(v.version)
247
                                          FROM {question_versions} v
248
                                          JOIN {question_bank_entries} be
249
                                            ON be.id = v.questionbankentryid
1441 ariadna 250
                                         WHERE be.id = qbe.id AND v.status <> :substatus)';
251
 
252
        // An additional condition is required in the subquery to account for scenarios
253
        // where the latest version is hidden. This ensures we retrieve the previous
254
        // "Ready" version instead of the hidden latest version.
255
        $onlyready = '((qv.status = :status))';
256
        $this->sqlparams = [
257
            'status' => question_version_status::QUESTION_STATUS_READY,
258
            'substatus' => question_version_status::QUESTION_STATUS_HIDDEN,
259
        ];
1 efrain 260
        $conditions = [];
261
        foreach ($this->searchconditions as $searchcondition) {
262
            if ($searchcondition->where()) {
263
                $conditions[] = '((' . $searchcondition->where() .'))';
264
            }
265
            if ($searchcondition->params()) {
266
                $this->sqlparams = array_merge($this->sqlparams, $searchcondition->params());
267
            }
268
        }
269
        $majorconditions = ['q.parent = 0', $latestversion, $onlyready];
270
        // Get higher level filter condition.
271
        $jointype = isset($this->pagevars['jointype']) ? (int)$this->pagevars['jointype'] : condition::JOINTYPE_DEFAULT;
272
        $nonecondition = ($jointype === datafilter::JOINTYPE_NONE) ? ' NOT ' : '';
273
        $separator = ($jointype === datafilter::JOINTYPE_ALL) ? ' AND ' : ' OR ';
274
        // Build the SQL.
275
        $sql = ' FROM {question} q ' . implode(' ', $joins);
276
        $sql .= ' WHERE ' . implode(' AND ', $majorconditions);
277
        if (!empty($conditions)) {
278
            $sql .= ' AND ' . $nonecondition . ' ( ';
279
            $sql .= implode($separator, $conditions);
280
            $sql .= ' ) ';
281
        }
282
        $this->countsql = 'SELECT count(1)' . $sql;
283
        $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
284
    }
285
 
286
    public function add_standard_search_conditions(): void {
287
        foreach ($this->plugins as $componentname => $plugin) {
288
            if (\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
289
                $pluginentrypointobject = new $plugin();
290
                if ($componentname === 'qbank_managecategories') {
291
                    $pluginentrypointobject = new quiz_managecategories_feature();
292
                }
293
                if ($componentname === 'qbank_viewquestiontext' || $componentname === 'qbank_deletequestion') {
294
                    continue;
295
                }
296
                $pluginobjects = $pluginentrypointobject->get_question_filters($this);
297
                foreach ($pluginobjects as $pluginobject) {
298
                    $this->add_searchcondition($pluginobject, $pluginobject->get_condition_key());
299
                }
300
            }
301
        }
302
    }
303
 
304
    /**
305
     * Return the quiz settings for the quiz this question bank is displayed in.
306
     *
307
     * @return bool|\stdClass
308
     */
309
    public function get_quiz() {
310
        return $this->quiz;
311
    }
1441 ariadna 312
 
313
    /**
314
     * Shows the question bank interface.
315
     *
316
     * @return void
317
     */
318
    public function display(): void {
319
 
320
        echo \html_writer::start_div('questionbankwindow boxwidthwide boxaligncenter', [
321
            'data-component' => 'core_question',
322
            'data-callback' => 'display_question_bank',
323
            'data-contextid' => $this->contexts->lowest()->id,
324
        ]);
325
 
326
        // Show the 'switch question bank' button.
327
        echo $this->display_bank_switch();
328
 
329
        // Show the filters and search options.
330
        $this->wanted_filters();
331
        // Continues with list of questions.
332
        $this->display_question_list();
333
        echo \html_writer::end_div();
334
    }
335
 
336
    /**
337
     * Get the current bank header and bank switch button.
338
     *
339
     * @return string
340
     */
341
    protected function display_bank_switch(): string {
342
        global $OUTPUT;
343
 
344
        if (!$this->requirebankswitch) {
345
            return '';
346
        }
347
 
348
        $cminfo = \cm_info::create($this->cm);
349
 
350
        return $OUTPUT->render_from_template('mod_quiz/switch_bank_header', ['currentbank' => $cminfo->get_formatted_name()]);
351
    }
1 efrain 352
}