Proyectos de Subversion Moodle

Rev

Rev 1 | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

Rev 1 Rev 1441
Línea 14... Línea 14...
14
// You should have received a copy of the GNU General Public License
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/>.
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
Línea 16... Línea 16...
16
 
16
 
Línea -... Línea 17...
-
 
17
namespace qbank_managecategories;
-
 
18
 
-
 
19
defined('MOODLE_INTERNAL') || die();
-
 
20
 
17
namespace qbank_managecategories;
21
require_once($CFG->libdir . "/questionlib.php");
-
 
22
 
18
 
23
use context;
-
 
24
use core_question\category_manager;
19
use context;
25
use core_question\local\bank\question_version_status;
20
use core_question\local\bank\question_version_status;
26
use core_question\output\question_category_selector;
Línea 21... Línea 27...
21
use moodle_exception;
27
use moodle_exception;
22
use html_writer;
28
use html_writer;
Línea 31... Línea 37...
31
 * @copyright  2021 Catalyst IT Australia Pty Ltd
37
 * @copyright  2021 Catalyst IT Australia Pty Ltd
32
 * @author     Guillermo Gomez Arias <guillermogomez@catalyst-au.net>
38
 * @author     Guillermo Gomez Arias <guillermogomez@catalyst-au.net>
33
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34
 */
40
 */
35
class helper {
41
class helper {
36
 
-
 
37
    /**
42
    /**
38
     * Name of this plugin.
43
     * Name of this plugin.
39
     */
44
     */
40
    const PLUGINNAME = 'qbank_managecategories';
45
    const PLUGINNAME = 'qbank_managecategories';
Línea 41... Línea 46...
41
 
46
 
42
    /**
47
    /**
43
     * Remove stale questions from a category.
48
     * Remove stale questions from a category.
44
     *
49
     *
45
     * While questions should not be left behind when they are not used any more,
50
     * This finds and removes any old-style random questions (qtype = random),
-
 
51
     * or any questions that were deleted while they were in use by a quiz (status = hidden),
-
 
52
     * but those usages have since been removed.
46
     * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
53
     *
47
     * this happens, the users are unable to delete the question category unless
54
     * If a category only contains stale questions, the users are unable to delete the question
48
     * they move those stale questions to another one category, but to them the
55
     * category unless they move those stale questions to another one category, but to them the
49
     * category is empty as it does not contain anything. The purpose of this function
56
     * category may appear empty. The purpose of this function is to detect the questions that
50
     * is to detect the questions that may have gone stale and remove them.
57
     * may have gone stale and remove them.
51
     *
58
     *
52
     * You will typically use this prior to checking if the category contains questions.
59
     * You will typically use this prior to checking if the category contains questions.
53
     *
-
 
54
     * The stale questions (unused and hidden to the user) handled are:
-
 
55
     * - hidden questions
-
 
56
     * - random questions
-
 
57
     *
60
     *
58
     * @param int $categoryid The category ID.
61
     * @param int $categoryid The category ID.
59
     * @throws \dml_exception
62
     * @throws \dml_exception
60
     */
63
     */
61
    public static function question_remove_stale_questions_from_category(int $categoryid): void {
64
    public static function question_remove_stale_questions_from_category(int $categoryid): void {
Línea 80... Línea 83...
80
     * Checks whether this is the only child of a top category in a context.
83
     * Checks whether this is the only child of a top category in a context.
81
     *
84
     *
82
     * @param int $categoryid a category id.
85
     * @param int $categoryid a category id.
83
     * @return bool
86
     * @return bool
84
     * @throws \dml_exception
87
     * @throws \dml_exception
-
 
88
     * @deprecated Since Moodle 4.5. Use core_question\category_manager::is_only_child_of_top_category_in_context instead.
-
 
89
     * @todo Final removal in Moodle 6.0 MDL-80804
85
     */
90
     */
-
 
91
    #[\core\attribute\deprecated(
-
 
92
        'core_question\category_manager::is_only_child_of_top_category_in_context',
-
 
93
        since: 4.5,
-
 
94
        reason: 'Moved to core namespace',
-
 
95
        mdl: 'MDL-72397'
-
 
96
    )]
86
    public static function question_is_only_child_of_top_category_in_context(int $categoryid): bool {
97
    public static function question_is_only_child_of_top_category_in_context(int $categoryid): bool {
87
        global $DB;
-
 
88
        return 1 == $DB->count_records_sql("
98
        \core\deprecation::emit_deprecation([__CLASS__, __FUNCTION__]);
89
            SELECT count(*)
-
 
90
              FROM {question_categories} c
99
        $manager = new category_manager();
91
              JOIN {question_categories} p ON c.parent = p.id
-
 
92
              JOIN {question_categories} s ON s.parent = c.parent
-
 
93
             WHERE c.id = ? AND p.parent = 0", [$categoryid]);
100
        return $manager->is_only_child_of_top_category_in_context($categoryid);
94
    }
101
    }
Línea 95... Línea 102...
95
 
102
 
96
    /**
103
    /**
97
     * Checks whether the category is a "Top" category (with no parent).
104
     * Checks whether the category is a "Top" category (with no parent).
98
     *
105
     *
99
     * @param int $categoryid a category id.
106
     * @param int $categoryid a category id.
100
     * @return bool
107
     * @return bool
-
 
108
     * @throws \dml_exception
-
 
109
     * @deprecated Since Moodle 4.5. Use core_question\category_manager::is_top_category instead.
101
     * @throws \dml_exception
110
     * @todo Final removal in Moodle 6.0 MDL-80804.
-
 
111
     */
-
 
112
    #[\core\attribute\deprecated(
-
 
113
        'core_question\category_manager::is_top_category',
-
 
114
        since: 4.5,
-
 
115
        reason: 'Moved to core namespace',
-
 
116
        mdl: 'MDL-72397'
102
     */
117
    )]
-
 
118
    public static function question_is_top_category(int $categoryid): bool {
103
    public static function question_is_top_category(int $categoryid): bool {
119
        \core\deprecation::emit_deprecation([__CLASS__, __FUNCTION__]);
104
        global $DB;
120
        $manager = new category_manager();
105
        return 0 == $DB->get_field('question_categories', 'parent', ['id' => $categoryid]);
121
        return $manager->is_top_category($categoryid);
Línea 106... Línea 122...
106
    }
122
    }
107
 
123
 
108
    /**
124
    /**
109
     * Ensures that this user is allowed to delete this category.
125
     * Ensures that this user is allowed to delete this category.
110
     *
126
     *
111
     * @param int $todelete a category id.
127
     * @param int $todelete a category id.
-
 
128
     * @throws \required_capability_exception
-
 
129
     * @throws \dml_exception|moodle_exception
112
     * @throws \required_capability_exception
130
     * @deprecated Since Moodle 4.5. Use core_question\category_manager::can_delete_category instead.
-
 
131
     * @todo Final removal in Moodle 6.0 MDL-80804.
-
 
132
     */
-
 
133
    #[\core\attribute\deprecated(
-
 
134
        'core_question\category_manager::can_delete_category',
-
 
135
        since: 4.5,
-
 
136
        reason: 'Moved to core namespace',
113
     * @throws \dml_exception|moodle_exception
137
        mdl: 'MDL-72397'
114
     */
-
 
115
    public static function question_can_delete_cat(int $todelete): void {
138
    )]
116
        global $DB;
139
    public static function question_can_delete_cat(int $todelete): void {
117
        if (self::question_is_top_category($todelete)) {
140
        \core\deprecation::emit_deprecation([__CLASS__, __FUNCTION__]);
118
            throw new moodle_exception('cannotdeletetopcat', 'question');
-
 
119
        } else if (self::question_is_only_child_of_top_category_in_context($todelete)) {
-
 
120
            throw new moodle_exception('cannotdeletecate', 'question');
-
 
121
        } else {
-
 
122
            $contextid = $DB->get_field('question_categories', 'contextid', ['id' => $todelete]);
-
 
123
            require_capability('moodle/question:managecategory', context::instance_by_id($contextid));
141
        $manager = new category_manager();
Línea 124... Línea 142...
124
        }
142
        $manager->require_can_delete_category($todelete);
125
    }
143
    }
126
 
144
 
Línea 149... Línea 167...
149
 
167
 
150
        // Recursively indent the children.
168
        // Recursively indent the children.
151
        foreach ($categories[$id]->childids as $childid) {
169
        foreach ($categories[$id]->childids as $childid) {
152
            if ($childid != $nochildrenof) {
170
            if ($childid != $nochildrenof) {
-
 
171
                $newcategories = $newcategories + self::flatten_category_tree(
-
 
172
                    $categories,
-
 
173
                    $childid,
153
                $newcategories = $newcategories + self::flatten_category_tree(
174
                    $depth + 1,
-
 
175
                    $nochildrenof,
154
                        $categories, $childid, $depth + 1, $nochildrenof);
176
                );
155
            }
177
            }
Línea 156... Línea 178...
156
        }
178
        }
157
 
179
 
Línea 180... Línea 202...
180
        // Build the tree structure, and record which categories are top-level.
202
        // Build the tree structure, and record which categories are top-level.
181
        // We have to be careful, because the categories array may include published
203
        // We have to be careful, because the categories array may include published
182
        // categories from other courses, but not their parents.
204
        // categories from other courses, but not their parents.
183
        $toplevelcategoryids = [];
205
        $toplevelcategoryids = [];
184
        foreach (array_keys($categories) as $id) {
206
        foreach (array_keys($categories) as $id) {
-
 
207
            if (
185
            if (!empty($categories[$id]->parent) &&
208
                !empty($categories[$id]->parent) &&
186
                array_key_exists($categories[$id]->parent, $categories)) {
209
                array_key_exists($categories[$id]->parent, $categories)
-
 
210
            ) {
187
                $categories[$categories[$id]->parent]->childids[] = $id;
211
                $categories[$categories[$id]->parent]->childids[] = $id;
188
            } else {
212
            } else {
189
                $toplevelcategoryids[] = $id;
213
                $toplevelcategoryids[] = $id;
190
            }
214
            }
191
        }
215
        }
Línea 192... Línea 216...
192
 
216
 
193
        // Flatten the tree to and add the indents.
217
        // Flatten the tree to and add the indents.
194
        $newcategories = [];
218
        $newcategories = [];
195
        foreach ($toplevelcategoryids as $id) {
219
        foreach ($toplevelcategoryids as $id) {
-
 
220
            $newcategories = $newcategories + self::flatten_category_tree(
-
 
221
                $categories,
-
 
222
                $id,
196
            $newcategories = $newcategories + self::flatten_category_tree(
223
                0,
-
 
224
                $nochildrenof,
197
                    $categories, $id, 0, $nochildrenof);
225
            );
Línea 198... Línea 226...
198
        }
226
        }
199
 
227
 
Línea 211... Línea 239...
211
     * @param int $currentcat
239
     * @param int $currentcat
212
     * @param string $selected optionally, the id of a category to be selected by
240
     * @param string $selected optionally, the id of a category to be selected by
213
     *      default in the dropdown.
241
     *      default in the dropdown.
214
     * @param int $nochildrenof
242
     * @param int $nochildrenof
215
     * @param bool $return to return the string of the select menu or echo that from the method
243
     * @param bool $return to return the string of the select menu or echo that from the method
-
 
244
     * @return ?string The HTML, or null if the $return is false.
216
     * @throws \coding_exception|\dml_exception
245
     * @throws \coding_exception|\dml_exception
217
     */
246
     */
218
    public static function question_category_select_menu(array $contexts, bool $top = false, int $currentcat = 0,
247
    public static function question_category_select_menu(
-
 
248
        array $contexts,
-
 
249
        bool $top = false,
-
 
250
        int $currentcat = 0,
-
 
251
        string $selected = "",
219
                                           string $selected = "", int $nochildrenof = -1, bool $return = false) {
252
        int $nochildrenof = -1,
-
 
253
        bool $return = false,
-
 
254
    ): ?string {
220
        $categoriesarray = self::question_category_options($contexts, $top, $currentcat,
255
        $categoriesarray = self::question_category_options(
-
 
256
            $contexts,
-
 
257
            $top,
-
 
258
            $currentcat,
-
 
259
            false,
221
            false, $nochildrenof, false);
260
            $nochildrenof,
-
 
261
            false,
-
 
262
        );
222
        $choose = '';
263
        $choose = '';
223
        $options = [];
264
        $options = [];
224
        foreach ($categoriesarray as $group => $opts) {
265
        foreach ($categoriesarray as $group => $opts) {
225
            $options[] = [$group => $opts];
266
            $options[] = [$group => $opts];
226
        }
267
        }
-
 
268
        $outputhtml = html_writer::label(
227
        $outputhtml = html_writer::label(get_string('questioncategory', 'core_question'),
269
            get_string('questioncategory', 'core_question'),
-
 
270
            'id_movetocategory',
-
 
271
            false,
228
            'id_movetocategory', false, ['class' => 'accesshide']);
272
            ['class' => 'accesshide'],
-
 
273
        );
229
        $attrs = [
274
        $attrs = [
230
            'id' => 'id_movetocategory',
275
            'id' => 'id_movetocategory',
231
            'class' => 'custom-select',
276
            'class' => 'form-select',
232
            'data-action' => 'toggle',
277
            'data-action' => 'toggle',
233
            'data-togglegroup' => 'qbank',
278
            'data-togglegroup' => 'qbank',
234
            'data-toggle' => 'action',
279
            'data-toggle' => 'action',
235
            'disabled' => false,
280
            'disabled' => false,
236
        ];
281
        ];
237
        $outputhtml .= html_writer::select($options, 'category', $selected, $choose, $attrs);
282
        $outputhtml .= html_writer::select($options, 'category', $selected, $choose, $attrs);
238
        if ($return) {
283
        if ($return) {
239
            return $outputhtml;
284
            return $outputhtml;
240
        } else {
285
        } else {
241
            echo $outputhtml;
286
            echo $outputhtml;
-
 
287
            return null;
242
        }
288
        }
243
    }
289
    }
Línea 244... Línea 290...
244
 
290
 
245
    /**
291
    /**
246
     * Get all the category objects, including a count of the number of questions in that category,
292
     * Get all the category objects, including a count of the number of questions in that category,
247
     * for all the categories in the lists $contexts.
293
     * for all the categories in the lists $contexts.
248
     *
294
     *
249
     * @param context $contexts
295
     * @param string $contexts comma separated list of contextids
250
     * @param string $sortorder used as the ORDER BY clause in the select statement.
296
     * @param string $sortorder used as the ORDER BY clause in the select statement.
251
     * @param bool $top Whether to return the top categories or not.
297
     * @param bool $top Whether to return the top categories or not.
252
     * @param int $showallversions 1 to show all versions not only the latest.
298
     * @param int $showallversions 1 to show all versions not only the latest.
253
     * @return array of category objects.
299
     * @return array of category objects.
254
     * @throws \dml_exception
300
     * @throws \dml_exception
255
     */
301
     */
256
    public static function get_categories_for_contexts($contexts, string $sortorder = 'parent, sortorder, name ASC',
-
 
257
                                                       bool $top = false, int $showallversions = 0): array {
302
    public static function get_categories_for_contexts(
258
        global $DB;
303
        string $contexts,
259
        $topwhere = $top ? '' : 'AND c.parent <> 0';
-
 
260
        $statuscondition = "AND (qv.status = '". question_version_status::QUESTION_STATUS_READY . "' " .
-
 
261
            " OR qv.status = '" . question_version_status::QUESTION_STATUS_DRAFT . "' )";
-
 
262
 
304
        string $sortorder = 'parent, sortorder, name ASC',
263
        $sql = "SELECT c.*,
-
 
264
                    (SELECT COUNT(1)
-
 
265
                       FROM {question} q
-
 
266
                       JOIN {question_versions} qv ON qv.questionid = q.id
-
 
267
                       JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
-
 
268
                      WHERE q.parent = '0'
-
 
269
                        $statuscondition
-
 
270
                            AND c.id = qbe.questioncategoryid
305
        bool $top = false,
271
                            AND ($showallversions = 1
-
 
272
                                OR (qv.version = (SELECT MAX(v.version)
-
 
273
                                                    FROM {question_versions} v
-
 
274
                                                    JOIN {question_bank_entries} be ON be.id = v.questionbankentryid
-
 
275
                                                   WHERE be.id = qbe.id)
-
 
276
                                   )
306
        int $showallversions = 0,
277
                                )
-
 
278
                            ) AS questioncount
-
 
279
                  FROM {question_categories} c
307
    ): array {
280
                 WHERE c.contextid IN ($contexts) $topwhere
-
 
281
              ORDER BY $sortorder";
-
 
282
 
-
 
283
        return $DB->get_records_sql($sql);
308
        return (new question_category_selector())->get_categories_for_contexts($contexts, $sortorder, $top, $showallversions);
Línea 284... Línea 309...
284
    }
309
    }
285
 
310
 
286
    /**
311
    /**
Línea 293... Línea 318...
293
     * @param int $nochildrenof
318
     * @param int $nochildrenof
294
     * @param bool $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
319
     * @param bool $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
295
     * @return array
320
     * @return array
296
     * @throws \coding_exception|\dml_exception
321
     * @throws \coding_exception|\dml_exception
297
     */
322
     */
298
    public static function question_category_options(array $contexts, bool $top = false, int $currentcat = 0,
323
    public static function question_category_options(
299
                                                     bool $popupform = false, int $nochildrenof = -1,
-
 
300
                                                     bool $escapecontextnames = true): array {
-
 
301
        global $CFG;
324
        array $contexts,
302
        $pcontexts = [];
325
        bool $top = false,
303
        foreach ($contexts as $context) {
326
        int $currentcat = 0,
304
            $pcontexts[] = $context->id;
327
        bool $popupform = false,
305
        }
-
 
306
        $contextslist = join(', ', $pcontexts);
-
 
307
 
-
 
308
        $categories = self::get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
-
 
309
 
-
 
310
        if ($top) {
-
 
311
            $categories = self::question_fix_top_names($categories);
-
 
312
        }
-
 
313
 
-
 
314
        $categories = self::question_add_context_in_key($categories);
-
 
315
        $categories = self::add_indented_names($categories, $nochildrenof);
-
 
316
 
-
 
317
        // Sort cats out into different contexts.
-
 
318
        $categoriesarray = [];
328
        int $nochildrenof = -1,
319
        foreach ($pcontexts as $contextid) {
329
        bool $escapecontextnames = true,
320
            $context = \context::instance_by_id($contextid);
-
 
321
            $contextstring = $context->get_context_name(true, true, $escapecontextnames);
-
 
322
            foreach ($categories as $category) {
-
 
323
                if ($category->contextid == $contextid) {
-
 
324
                    $cid = $category->id;
-
 
325
                    if ($currentcat != $cid || $currentcat == 0) {
-
 
326
                        $a = new \stdClass;
-
 
327
                        $a->name = format_string($category->indentedname, true,
-
 
328
                            ['context' => $context]);
-
 
329
                        if ($category->idnumber !== null && $category->idnumber !== '') {
-
 
330
                            $a->idnumber = s($category->idnumber);
-
 
331
                        }
330
    ): array {
332
                        if (!empty($category->questioncount)) {
331
        return (new question_category_selector())->question_category_options(
333
                            $a->questioncount = $category->questioncount;
-
 
334
                        }
-
 
335
                        if (isset($a->idnumber) && isset($a->questioncount)) {
-
 
336
                            $formattedname = get_string('categorynamewithidnumberandcount', 'question', $a);
-
 
337
                        } else if (isset($a->idnumber)) {
-
 
338
                            $formattedname = get_string('categorynamewithidnumber', 'question', $a);
-
 
339
                        } else if (isset($a->questioncount)) {
-
 
340
                            $formattedname = get_string('categorynamewithcount', 'question', $a);
-
 
341
                        } else {
-
 
342
                            $formattedname = $a->name;
-
 
343
                        }
-
 
344
                        $categoriesarray[$contextstring][$cid] = $formattedname;
-
 
345
                    }
332
            $contexts,
346
                }
333
            $top,
347
            }
334
            $currentcat,
348
        }
-
 
349
        if ($popupform) {
335
            $popupform,
350
            $popupcats = [];
336
            $nochildrenof,
351
            foreach ($categoriesarray as $contextstring => $optgroup) {
-
 
352
                $group = [];
-
 
353
                foreach ($optgroup as $key => $value) {
-
 
354
                    $key = str_replace($CFG->wwwroot, '', $key);
-
 
355
                    $group[$key] = $value;
-
 
356
                }
-
 
357
                $popupcats[] = [$contextstring => $group];
-
 
358
            }
-
 
359
            return $popupcats;
337
            $escapecontextnames,
360
        } else {
-
 
361
            return $categoriesarray;
-
 
362
        }
338
        );
363
    }
339
    }
Línea 364... Línea 340...
364
 
340
 
365
    /**
341
    /**
366
     * Add context in categories key.
342
     * Add context in categories key.
367
     *
343
     *
368
     * @param array $categories The list of categories.
344
     * @param array $categories The list of categories.
369
     * @return array
345
     * @return array
370
     */
346
     */
371
    public static function question_add_context_in_key(array $categories): array {
-
 
372
        $newcatarray = [];
-
 
373
        foreach ($categories as $id => $category) {
-
 
374
            $category->parent = "$category->parent,$category->contextid";
-
 
375
            $category->id = "$category->id,$category->contextid";
347
    public static function question_add_context_in_key(array $categories): array {
376
            $newcatarray["$id,$category->contextid"] = $category;
-
 
377
        }
-
 
378
        return $newcatarray;
348
        return (new question_category_selector())->question_add_context_in_key($categories);
Línea 379... Línea 349...
379
    }
349
    }
380
 
350
 
381
    /**
351
    /**
Línea 385... Línea 355...
385
     * @param bool $escape Whether the returned name of the thing is to be HTML escaped or not.
355
     * @param bool $escape Whether the returned name of the thing is to be HTML escaped or not.
386
     * @return array The same question category list given to the function, with the top category names being translated.
356
     * @return array The same question category list given to the function, with the top category names being translated.
387
     * @throws \coding_exception
357
     * @throws \coding_exception
388
     */
358
     */
389
    public static function question_fix_top_names(array $categories, bool $escape = true): array {
359
    public static function question_fix_top_names(array $categories, bool $escape = true): array {
-
 
360
        return (new question_category_selector())->question_fix_top_names($categories, $escape);
-
 
361
    }
Línea -... Línea 362...
-
 
362
 
390
 
363
    /**
391
        foreach ($categories as $id => $category) {
364
     * Combine id and context id for a question category
392
            if ($category->parent == 0) {
365
     *
393
                $context = \context::instance_by_id($category->contextid);
-
 
394
                $categories[$id]->name = get_string('topfor', 'question', $context->get_context_name(false, false, $escape));
366
     * @param \stdClass $category a category to extract its id and context id
395
            }
367
     * @return string the combined string
396
        }
-
 
-
 
368
     */
397
 
369
    public static function combine_id_context(\stdClass $category): string {
398
        return $categories;
370
        return $category->id . ',' . $category->contextid;
399
    }
371
    }