2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
17 namespace qbank_managecategories
;
19 defined('MOODLE_INTERNAL') ||
die();
21 require_once($CFG->libdir
. "/questionlib.php");
24 use core_question\category_manager
;
25 use core_question\local\bank\question_version_status
;
30 * Class helper contains all the library functions.
32 * Library functions used by qbank_managecategories.
33 * This code is based on lib/questionlib.php by Martin Dougiamas.
35 * @package qbank_managecategories
36 * @copyright 2021 Catalyst IT Australia Pty Ltd
37 * @author Guillermo Gomez Arias <guillermogomez@catalyst-au.net>
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 * Name of this plugin.
44 const PLUGINNAME
= 'qbank_managecategories';
47 * Remove stale questions from a category.
49 * While questions should not be left behind when they are not used any more,
50 * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
51 * this happens, the users are unable to delete the question category unless
52 * they move those stale questions to another one category, but to them the
53 * category is empty as it does not contain anything. The purpose of this function
54 * is to detect the questions that may have gone stale and remove them.
56 * You will typically use this prior to checking if the category contains questions.
58 * The stale questions (unused and hidden to the user) handled are:
62 * @param int $categoryid The category ID.
63 * @throws \dml_exception
65 public static function question_remove_stale_questions_from_category(int $categoryid): void
{
70 JOIN {question_versions} qv ON qv.questionid = q.id
71 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
72 WHERE qbe.questioncategoryid = :categoryid
73 AND (q.qtype = :qtype OR qv.status = :status)";
75 $params = ['categoryid' => $categoryid, 'qtype' => 'random', 'status' => question_version_status
::QUESTION_STATUS_HIDDEN
];
76 $questions = $DB->get_records_sql($sql, $params);
77 foreach ($questions as $question) {
78 // The function question_delete_question does not delete questions in use.
79 question_delete_question($question->id
);
84 * Checks whether this is the only child of a top category in a context.
86 * @param int $categoryid a category id.
88 * @throws \dml_exception
89 * @deprecated Since Moodle 4.5. Use core_question\category_manager::is_only_child_of_top_category_in_context instead.
90 * @todo Final removal in Moodle 6.0 MDL-80804
92 #[\core\attribute\deprecated(
93 'core_question\category_manager::is_only_child_of_top_category_in_context',
95 reason
: 'Moved to core namespace',
98 public static function question_is_only_child_of_top_category_in_context(int $categoryid): bool {
99 \core\deprecation
::emit_deprecation_if_present([__CLASS__
, __FUNCTION__
]);
100 $manager = new category_manager();
101 return $manager->is_only_child_of_top_category_in_context($categoryid);
105 * Checks whether the category is a "Top" category (with no parent).
107 * @param int $categoryid a category id.
109 * @throws \dml_exception
110 * @deprecated Since Moodle 4.5. Use core_question\category_manager::is_top_category instead.
111 * @todo Final removal in Moodle 6.0 MDL-80804.
113 #[\core\attribute\deprecated(
114 'core_question\category_manager::is_top_category',
116 reason
: 'Moved to core namespace',
119 public static function question_is_top_category(int $categoryid): bool {
120 \core\deprecation
::emit_deprecation_if_present([__CLASS__
, __FUNCTION__
]);
121 $manager = new category_manager();
122 return $manager->is_top_category($categoryid);
126 * Ensures that this user is allowed to delete this category.
128 * @param int $todelete a category id.
129 * @throws \required_capability_exception
130 * @throws \dml_exception|moodle_exception
131 * @deprecated Since Moodle 4.5. Use core_question\category_manager::can_delete_category instead.
132 * @todo Final removal in Moodle 6.0 MDL-80804.
134 #[\core\attribute\deprecated(
135 'core_question\category_manager::can_delete_category',
137 reason
: 'Moved to core namespace',
140 public static function question_can_delete_cat(int $todelete): void
{
141 \core\deprecation
::emit_deprecation_if_present([__CLASS__
, __FUNCTION__
]);
142 $manager = new category_manager();
143 $manager->require_can_delete_category($todelete);
147 * Only for the use of add_indented_names().
149 * Recursively adds an indentedname field to each category, starting with the category
150 * with id $id, and dealing with that category and all its children, and
151 * return a new array, with those categories in the right order.
153 * @param array $categories an array of categories which has had childids
154 * fields added by flatten_category_tree(). Passed by reference for
155 * performance only. It is not modfied.
156 * @param int $id the category to start the indenting process from.
157 * @param int $depth the indent depth. Used in recursive calls.
158 * @param int $nochildrenof
159 * @return array a new array of categories, in the right order for the tree.
161 public static function flatten_category_tree(array &$categories, $id, int $depth = 0, int $nochildrenof = -1): array {
163 // Indent the name of this category.
165 $newcategories[$id] = $categories[$id];
166 $newcategories[$id]->indentedname
= str_repeat(' ', $depth) .
167 $categories[$id]->name
;
169 // Recursively indent the children.
170 foreach ($categories[$id]->childids
as $childid) {
171 if ($childid != $nochildrenof) {
172 $newcategories = $newcategories + self
::flatten_category_tree(
181 // Remove the childids array that were temporarily added.
182 unset($newcategories[$id]->childids
);
184 return $newcategories;
188 * Format categories into an indented list reflecting the tree structure.
190 * @param array $categories An array of category objects, for example from the.
191 * @param int $nochildrenof
192 * @return array The formatted list of categories.
194 public static function add_indented_names(array $categories, int $nochildrenof = -1): array {
196 // Add an array to each category to hold the child category ids. This array
197 // will be removed again by flatten_category_tree(). It should not be used
198 // outside these two functions.
199 foreach (array_keys($categories) as $id) {
200 $categories[$id]->childids
= [];
203 // Build the tree structure, and record which categories are top-level.
204 // We have to be careful, because the categories array may include published
205 // categories from other courses, but not their parents.
206 $toplevelcategoryids = [];
207 foreach (array_keys($categories) as $id) {
209 !empty($categories[$id]->parent
) &&
210 array_key_exists($categories[$id]->parent
, $categories)
212 $categories[$categories[$id]->parent
]->childids
[] = $id;
214 $toplevelcategoryids[] = $id;
218 // Flatten the tree to and add the indents.
220 foreach ($toplevelcategoryids as $id) {
221 $newcategories = $newcategories + self
::flatten_category_tree(
229 return $newcategories;
233 * Output a select menu of question categories.
235 * Categories from this course and (optionally) published categories from other courses
236 * are included. Optionally, only categories the current user may edit can be included.
238 * @param array $contexts
240 * @param int $currentcat
241 * @param string $selected optionally, the id of a category to be selected by
242 * default in the dropdown.
243 * @param int $nochildrenof
244 * @param bool $return to return the string of the select menu or echo that from the method
245 * @return ?string The HTML, or null if the $return is false.
246 * @throws \coding_exception|\dml_exception
248 public static function question_category_select_menu(
252 string $selected = "",
253 int $nochildrenof = -1,
254 bool $return = false,
256 $categoriesarray = self
::question_category_options(
266 foreach ($categoriesarray as $group => $opts) {
267 $options[] = [$group => $opts];
269 $outputhtml = html_writer
::label(
270 get_string('questioncategory', 'core_question'),
273 ['class' => 'accesshide'],
276 'id' => 'id_movetocategory',
277 'class' => 'custom-select',
278 'data-action' => 'toggle',
279 'data-togglegroup' => 'qbank',
280 'data-toggle' => 'action',
283 $outputhtml .= html_writer
::select($options, 'category', $selected, $choose, $attrs);
293 * Get all the category objects, including a count of the number of questions in that category,
294 * for all the categories in the lists $contexts.
296 * @param string $contexts
297 * @param string $sortorder used as the ORDER BY clause in the select statement.
298 * @param bool $top Whether to return the top categories or not.
299 * @param int $showallversions 1 to show all versions not only the latest.
300 * @return array of category objects.
301 * @throws \dml_exception
303 public static function get_categories_for_contexts(
305 string $sortorder = 'parent, sortorder, name ASC',
307 int $showallversions = 0,
310 $topwhere = $top ?
'' : 'AND c.parent <> 0';
311 $statuscondition = "AND (qv.status = '" . question_version_status
::QUESTION_STATUS_READY
. "' " .
312 " OR qv.status = '" . question_version_status
::QUESTION_STATUS_DRAFT
. "' )";
317 JOIN {question_versions} qv ON qv.questionid = q.id
318 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
321 AND c.id = qbe.questioncategoryid
322 AND ($showallversions = 1
323 OR (qv.version = (SELECT MAX(v.version)
324 FROM {question_versions} v
325 JOIN {question_bank_entries} be ON be.id = v.questionbankentryid
326 WHERE be.id = qbe.id)
330 FROM {question_categories} c
331 WHERE c.contextid IN ($contexts) $topwhere
332 ORDER BY $sortorder";
334 return $DB->get_records_sql($sql);
338 * Output an array of question categories.
340 * @param array $contexts The list of contexts.
341 * @param bool $top Whether to return the top categories or not.
342 * @param int $currentcat
343 * @param bool $popupform
344 * @param int $nochildrenof
345 * @param bool $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
347 * @throws \coding_exception|\dml_exception
349 public static function question_category_options(
353 bool $popupform = false,
354 int $nochildrenof = -1,
355 bool $escapecontextnames = true,
359 foreach ($contexts as $context) {
360 $pcontexts[] = $context->id
;
362 $contextslist = join(', ', $pcontexts);
364 $categories = self
::get_categories_for_contexts($contextslist, 'parent, sortorder, name ASC', $top);
367 $categories = self
::question_fix_top_names($categories);
370 $categories = self
::question_add_context_in_key($categories);
371 $categories = self
::add_indented_names($categories, $nochildrenof);
373 // Sort cats out into different contexts.
374 $categoriesarray = [];
375 foreach ($pcontexts as $contextid) {
376 $context = \context
::instance_by_id($contextid);
377 $contextstring = $context->get_context_name(true, true, $escapecontextnames);
378 foreach ($categories as $category) {
379 if ($category->contextid
== $contextid) {
380 $cid = $category->id
;
381 if ($currentcat != $cid ||
$currentcat == 0) {
382 $a = new \
stdClass();
383 $a->name
= format_string(
384 $category->indentedname
,
386 ['context' => $context]
388 if ($category->idnumber
!== null && $category->idnumber
!== '') {
389 $a->idnumber
= s($category->idnumber
);
391 if (!empty($category->questioncount
)) {
392 $a->questioncount
= $category->questioncount
;
394 if (isset($a->idnumber
) && isset($a->questioncount
)) {
395 $formattedname = get_string('categorynamewithidnumberandcount', 'question', $a);
396 } else if (isset($a->idnumber
)) {
397 $formattedname = get_string('categorynamewithidnumber', 'question', $a);
398 } else if (isset($a->questioncount
)) {
399 $formattedname = get_string('categorynamewithcount', 'question', $a);
401 $formattedname = $a->name
;
403 $categoriesarray[$contextstring][$cid] = $formattedname;
410 foreach ($categoriesarray as $contextstring => $optgroup) {
412 foreach ($optgroup as $key => $value) {
413 $key = str_replace($CFG->wwwroot
, '', $key);
414 $group[$key] = $value;
416 $popupcats[] = [$contextstring => $group];
420 return $categoriesarray;
425 * Add context in categories key.
427 * @param array $categories The list of categories.
430 public static function question_add_context_in_key(array $categories): array {
432 foreach ($categories as $id => $category) {
433 $category->parent
= "$category->parent,$category->contextid";
434 $category->id
= "$category->id,$category->contextid";
435 $newcatarray["$id,$category->contextid"] = $category;
441 * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
443 * @param array $categories An array of question categories.
444 * @param bool $escape Whether the returned name of the thing is to be HTML escaped or not.
445 * @return array The same question category list given to the function, with the top category names being translated.
446 * @throws \coding_exception
448 public static function question_fix_top_names(array $categories, bool $escape = true): array {
450 foreach ($categories as $id => $category) {
451 if ($category->parent
== 0) {
452 $context = \context
::instance_by_id($category->contextid
);
453 $categories[$id]->name
= get_string('topfor', 'question', $context->get_context_name(false, false, $escape));
461 * Combine id and context id for a question category
463 * @param \stdClass $category a category to extract its id and context id
464 * @return string the combined string
466 public static function combine_id_context(\stdClass
$category): string {
467 return $category->id
. ',' . $category->contextid
;