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
 * Functions used to show question editing interface
19
 *
20
 * @package    moodlecore
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
24
 */
25
 
26
use core\output\datafilter;
27
 
28
defined('MOODLE_INTERNAL') || die();
29
 
30
require_once($CFG->libdir . '/questionlib.php');
31
 
32
define('DEFAULT_QUESTIONS_PER_PAGE', 100);
33
define('MAXIMUM_QUESTIONS_PER_PAGE', 4000);
34
 
35
function get_module_from_cmid($cmid) {
36
    global $CFG, $DB;
37
    if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
38
                               FROM {course_modules} cm,
39
                                    {modules} md
40
                               WHERE cm.id = ? AND
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');
45
    }
46
    $modrec->instance = $modrec->id;
47
    $modrec->cmid = $cmrec->id;
48
    $cmrec->name = $modrec->name;
49
 
50
    return array($modrec, $cmrec);
51
}
52
 
53
/**
54
 * Function to read all questions for category into big array
55
 *
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
61
 * @return array
62
 */
63
function get_questions_category(object $category, bool $noparent, bool $recurse = true, bool $export = true,
64
        bool $latestversion = false): array {
65
    global $DB;
66
 
67
    // Build sql bit for $noparent.
68
    $npsql = '';
69
    if ($noparent) {
70
        $npsql = " and q.parent='0' ";
71
    }
72
 
73
    // Get list of categories.
74
    if ($recurse) {
75
        $categorylist = question_categorylist($category->id);
76
    } else {
77
        $categorylist = [$category->id];
78
    }
79
 
80
    // Get the list of questions for the category.
81
    list($usql, $params) = $DB->get_in_or_equal($categorylist);
82
 
83
    // Get the latest version of a question.
84
    $version = '';
85
    if ($latestversion) {
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)';
91
    }
92
    $questions = $DB->get_records_sql("SELECT q.*, qv.status, qc.id AS category
93
                                         FROM {question} q
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);
99
 
100
    // Iterate through questions, getting stuff we need.
101
    $qresults = [];
1441 ariadna 102
    foreach ($questions as $question) {
1 efrain 103
        $question->export_process = $export;
1441 ariadna 104
        $question->categoryobject = $category;
1 efrain 105
        $qtype = question_bank::get_qtype($question->qtype, false);
106
        if ($export && $qtype->name() === 'missingtype') {
107
            // Unrecognised question type. Skip this question when exporting.
108
            continue;
109
        }
110
        $qtype->get_question_options($question);
111
        $qresults[] = $question;
112
    }
113
 
114
    return $qresults;
115
}
116
 
117
/**
118
 * Common setup for all pages for editing questions.
119
 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
120
 * @param string $edittab code for this edit tab
1441 ariadna 121
 * @param bool $requirecmid This parameter has been deprecated since 4.5 and should not be used anymore.
1 efrain 122
 * @param bool $unused no longer used, do no pass
123
 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
124
 */
1441 ariadna 125
function question_edit_setup($edittab, $baseurl, $requirecmid = null, $unused = null) {
1 efrain 126
    global $PAGE;
127
 
1441 ariadna 128
    if ($unused !== null || $requirecmid !== null) {
1 efrain 129
        debugging('Deprecated argument passed to question_edit_setup()', DEBUG_DEVELOPER);
130
    }
131
 
132
    $params = [];
133
 
1441 ariadna 134
    $params['cmid'] = required_param('cmid', PARAM_INT);
1 efrain 135
    $params['qpage'] = optional_param('qpage', null, PARAM_INT);
136
 
137
    // Pass 'cat' from page to page and when 'category' comes from a drop down menu
138
    // then we also reset the qpage so we go to page 1 of
139
    // a new cat.
140
    $params['cat'] = optional_param('cat', null, PARAM_SEQUENCE); // If empty will be set up later.
141
    $params['category'] = optional_param('category', null, PARAM_SEQUENCE);
142
    $params['qperpage'] = optional_param('qperpage', null, PARAM_INT);
143
 
144
    // Display options.
145
    $params['filter'] = optional_param('filter',    null, PARAM_RAW);
146
 
147
    // Category list page.
148
    $params['cpage'] = optional_param('cpage', null, PARAM_INT);
149
 
150
    // Sort data.
151
    $params['sortdata'] = optional_param_array('sortdata', [], PARAM_INT);
152
 
153
    $PAGE->set_pagelayout('admin');
154
 
155
    return question_build_edit_resources($edittab, $baseurl, $params);
156
}
157
 
158
/**
159
 * Common function for building the generic resources required by the
160
 * editing questions pages.
161
 *
1441 ariadna 162
 * A cmid must be provided as a key in $params or an exception will be thrown.
163
 * All other params are optional and will have sane default applied if not provided.
1 efrain 164
 *
165
 * The acceptable keys for $params are:
166
 * [
167
 *      'cmid' => PARAM_INT,
168
 *      'qpage' => PARAM_INT,
169
 *      'cat' => PARAM_SEQUENCE,
170
 *      'category' => PARAM_SEQUENCE,
171
 *      'qperpage' => PARAM_INT,
172
 *      'cpage' => PARAM_INT,
173
 *      'recurse' => PARAM_BOOL,
174
 *      'showhidden' => PARAM_BOOL,
175
 *      'qbshowtext' => PARAM_INT,
176
 *      'qtagids' => [PARAM_INT], (array of integers)
177
 *      'qbs1' => PARAM_TEXT,
178
 *      'qbs2' => PARAM_TEXT,
179
 *      'qbs3' => PARAM_TEXT,
180
 *      ... and more qbs keys up to core_question\local\bank\view::MAX_SORTS ...
181
 *  ];
182
 *
183
 * @param string $edittab Code for this edit tab
184
 * @param string $baseurl The name of the script calling this funciton. For examle 'qusetion/edit.php'.
185
 * @param array $params The provided parameters to construct the resources with.
186
 * @param int $defaultquestionsperpage number of questions per page, if not given in the URL.
187
 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
188
 */
189
function question_build_edit_resources($edittab, $baseurl, $params,
190
        $defaultquestionsperpage = DEFAULT_QUESTIONS_PER_PAGE) {
191
    global $DB;
192
 
193
    $thispageurl = new moodle_url($baseurl);
194
    $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
195
 
196
    $cleanparams = [
197
        'sortdata' => [],
198
        'filter' => null
199
    ];
200
    $paramtypes = [
201
        'cmid' => PARAM_INT,
202
        'qpage' => PARAM_INT,
203
        'cat' => PARAM_SEQUENCE,
204
        'category' => PARAM_SEQUENCE,
205
        'qperpage' => PARAM_INT,
206
        'cpage' => PARAM_INT,
207
    ];
208
 
209
    foreach ($paramtypes as $name => $type) {
210
        if (isset($params[$name])) {
211
            $cleanparams[$name] = clean_param($params[$name], $type);
212
        } else {
213
            $cleanparams[$name] = null;
214
        }
215
    }
216
 
217
    if (!empty($params['filter'])) {
218
        if (!is_array($params['filter'])) {
219
            $params['filter'] = json_decode($params['filter'], true);
220
        }
1441 ariadna 221
        $cleanparams['filter'] = [];
222
        foreach ($params['filter'] as $filterkey => $filtervalue) {
223
            if ($filterkey == 'jointype') {
224
                $cleanparams['filter']['jointype'] = clean_param($filtervalue, PARAM_INT);
225
            } else {
226
                if (!array_key_exists('name', $filtervalue)) {
227
                    $filtervalue['name'] = $filterkey;
228
                }
229
                $cleanfilter = [
230
                    'name' => clean_param($filtervalue['name'], PARAM_ALPHANUM),
231
                    'jointype' => clean_param($filtervalue['jointype'], PARAM_INT),
232
                    'values' => $filtervalue['values'],
233
                    'filteroptions' => $filtervalue['filteroptions'] ?? [],
234
                ];
235
                $cleanparams['filter'][$filterkey] = $cleanfilter;
236
            }
237
        }
1 efrain 238
    }
239
 
240
    if (isset($params['sortdata'])) {
241
        $cleanparams['sortdata'] = clean_param_array($params['sortdata'], PARAM_INT);
242
    }
243
 
244
    $cmid = $cleanparams['cmid'];
245
    $qpage = $cleanparams['qpage'] ?: -1;
246
    $cat = $cleanparams['cat'] ?: 0;
247
    $category = $cleanparams['category'] ?: 0;
248
    $qperpage = $cleanparams['qperpage'];
249
    $cpage = $cleanparams['cpage'] ?: 1;
250
 
1441 ariadna 251
    if (is_null($cmid)) {
252
        throw new \moodle_exception('Must provide a cmid');
1 efrain 253
    }
254
 
1441 ariadna 255
    list($module, $cm) = get_module_from_cmid($cmid);
256
    $courseid = $cm->course;
257
    $thispageurl->params(compact('cmid'));
258
    $thiscontext = context_module::instance($cmid);
1 efrain 259
 
260
    if (defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
261
        // For AJAX, we don't need to set up the course page for output.
262
        require_login();
263
    } else {
264
        require_login($courseid, false, $cm);
265
    }
266
 
267
    if ($thiscontext){
268
        $contexts = new core_question\local\bank\question_edit_contexts($thiscontext);
269
        $contexts->require_one_edit_tab_cap($edittab);
270
    } else {
271
        $contexts = null;
272
    }
273
 
274
    $pagevars['qpage'] = $qpage;
275
 
276
    // Pass 'cat' from page to page and when 'category' comes from a drop down menu
277
    // then we also reset the qpage so we go to page 1 of
278
    // a new cat.
279
    if ($category && $category != $cat) { // Is this a move to a new category?
280
        $pagevars['cat'] = $category;
281
        $pagevars['qpage'] = 0;
282
    } else {
283
        $pagevars['cat'] = $cat; // If empty will be set up later.
284
    }
285
 
286
    if ($pagevars['cat']){
287
        $thispageurl->param('cat', $pagevars['cat']);
288
    }
289
 
290
    if (strpos($baseurl, '/question/') === 0) {
291
        navigation_node::override_active_url($thispageurl);
292
    }
293
 
294
    if ($pagevars['qpage'] > -1) {
295
        $thispageurl->param('qpage', $pagevars['qpage']);
296
    } else {
297
        $pagevars['qpage'] = 0;
298
    }
299
 
300
    if ($defaultquestionsperpage == DEFAULT_QUESTIONS_PER_PAGE) {
301
        $pagevars['qperpage'] = question_set_or_get_user_preference(
302
                'qperpage', $qperpage, DEFAULT_QUESTIONS_PER_PAGE, $thispageurl);
303
    } else {
304
        $pagevars['qperpage'] = $qperpage ?? $defaultquestionsperpage;
305
    }
306
 
1441 ariadna 307
    $defaultcategory = question_get_default_category($contexts->lowest()->id, true);
1 efrain 308
 
309
    $contextlistarr = [];
310
    foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
311
        $contextlistarr[] = "'{$context->id}'";
312
    }
313
    $contextlist = join(' ,', $contextlistarr);
314
    if (!empty($pagevars['cat'])){
315
        $catparts = explode(',', $pagevars['cat']);
316
        if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
317
                !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
318
            throw new \moodle_exception('invalidcategory', 'question');
319
        }
320
    } else {
321
        $category = $defaultcategory;
322
        $pagevars['cat'] = "{$category->id},{$category->contextid}";
323
    }
324
 
325
    // Category list page.
326
    $pagevars['cpage'] = $cpage;
327
    if ($pagevars['cpage'] != 1){
328
        $thispageurl->param('cpage', $pagevars['cpage']);
329
    }
330
 
331
    if ($cleanparams['filter']) {
332
        $pagevars['filter'] = $cleanparams['filter'];
333
        $thispageurl->param('filter', json_encode($cleanparams['filter']));
334
    }
335
    $pagevars['tabname'] = $edittab;
336
 
337
    // Sort parameters.
338
    $pagevars['sortdata'] = $cleanparams['sortdata'];
339
    foreach ($pagevars['sortdata'] as $sortname => $sortorder) {
340
        $thispageurl->param('sortdata[' . $sortname . ']', $sortorder);
341
    }
342
 
343
    // Enforce ALL as the only allowed top-level join type, so we can't bypass filtering by category.
344
    $pagevars['jointype'] = datafilter::JOINTYPE_ALL;
345
 
346
    return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
347
}
348
 
349
/**
350
 * Get the category id from $pagevars.
351
 * @param array $pagevars from {@link question_edit_setup()}.
352
 * @return int the category id.
353
 */
354
function question_get_category_id_from_pagevars(array $pagevars) {
355
    list($questioncategoryid) = explode(',', $pagevars['cat']);
356
    return $questioncategoryid;
357
}
358
 
359
/**
360
 * Get a particular question preference that is also stored as a user preference.
361
 * If the the value is given in the GET/POST request, then that value is used,
362
 * and the user preference is updated to that value. Otherwise, the last set
363
 * value of the user preference is used, or if it has never been set the default
364
 * passed to this function.
365
 *
366
 * @param string $param the param name. The URL parameter set, and the GET/POST
367
 *      parameter read. The user_preference name is 'question_bank_' . $param.
368
 * @param mixed $default The default value to use, if not otherwise set.
369
 * @param int $type one of the PARAM_... constants.
370
 * @param moodle_url $thispageurl if the value has been explicitly set, we add
371
 *      it to this URL.
372
 * @return mixed the parameter value to use.
373
 */
374
function question_get_display_preference($param, $default, $type, $thispageurl) {
375
    $submittedvalue = optional_param($param, null, $type);
376
    return question_set_or_get_user_preference($param, $submittedvalue, $default, $thispageurl);
377
}
378
 
379
/**
380
 * Get a user preference by name or set the user preference to a given value.
381
 *
382
 * If $value is null then the function will only attempt to retrieve the
383
 * user preference requested by $name. If no user preference is found then the
384
 * $default value will be returned. In this case the user preferences are not
385
 * modified and nor are the params on $thispageurl.
386
 *
387
 * If $value is anything other than null then the function will set the user
388
 * preference $name to the provided $value and will also set it as a param
389
 * on $thispageurl.
390
 *
391
 * @param string $name The user_preference name is 'question_bank_' . $name.
392
 * @param mixed $value The preference value.
393
 * @param mixed $default The default value to use, if not otherwise set.
394
 * @param moodle_url $thispageurl if the value has been explicitly set, we add
395
 *      it to this URL.
396
 * @return mixed the parameter value to use.
397
 */
398
function question_set_or_get_user_preference($name, $value, $default, $thispageurl) {
399
    if (is_null($value)) {
400
        return get_user_preferences('question_bank_' . $name, $default);
401
    }
402
 
403
    set_user_preference('question_bank_' . $name, $value);
404
    $thispageurl->param($name, $value);
405
    return $value;
406
}
407
 
408
/**
409
 * Make sure user is logged in as required in this context.
410
 */
411
function require_login_in_context($contextorid = null){
412
    global $DB, $CFG;
413
    if (!is_object($contextorid)){
414
        $context = context::instance_by_id($contextorid, IGNORE_MISSING);
415
    } else {
416
        $context = $contextorid;
417
    }
418
    if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
419
        require_login($context->instanceid);
420
    } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
421
        if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
422
            if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
423
                throw new \moodle_exception('invalidcourseid');
424
            }
425
            require_course_login($course, true, $cm);
426
 
427
        } else {
428
            throw new \moodle_exception('invalidcoursemodule');
429
        }
430
    } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
431
        if (!empty($CFG->forcelogin)) {
432
            require_login();
433
        }
434
 
435
    } else {
436
        require_login();
437
    }
438
}