Proyectos de Subversion Moodle

Rev

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