on-demand release 4.5dev+
[moodle.git] / question / bank / managecategories / classes / helper.php
blobcbe0bfc4545bbac05f09d010fb9d788a781bc9de
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.
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");
23 use context;
24 use core_question\category_manager;
25 use core_question\local\bank\question_version_status;
26 use moodle_exception;
27 use html_writer;
29 /**
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
40 class helper {
41 /**
42 * Name of this plugin.
44 const PLUGINNAME = 'qbank_managecategories';
46 /**
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:
59 * - hidden questions
60 * - random questions
62 * @param int $categoryid The category ID.
63 * @throws \dml_exception
65 public static function question_remove_stale_questions_from_category(int $categoryid): void {
66 global $DB;
68 $sql = "SELECT q.id
69 FROM {question} q
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);
83 /**
84 * Checks whether this is the only child of a top category in a context.
86 * @param int $categoryid a category id.
87 * @return bool
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',
94 since: 4.5,
95 reason: 'Moved to core namespace',
96 mdl: 'MDL-72397'
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.
108 * @return bool
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',
115 since: 4.5,
116 reason: 'Moved to core namespace',
117 mdl: 'MDL-72397'
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',
136 since: 4.5,
137 reason: 'Moved to core namespace',
138 mdl: 'MDL-72397'
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.
164 $newcategories = [];
165 $newcategories[$id] = $categories[$id];
166 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $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(
173 $categories,
174 $childid,
175 $depth + 1,
176 $nochildrenof,
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) {
208 if (
209 !empty($categories[$id]->parent) &&
210 array_key_exists($categories[$id]->parent, $categories)
212 $categories[$categories[$id]->parent]->childids[] = $id;
213 } else {
214 $toplevelcategoryids[] = $id;
218 // Flatten the tree to and add the indents.
219 $newcategories = [];
220 foreach ($toplevelcategoryids as $id) {
221 $newcategories = $newcategories + self::flatten_category_tree(
222 $categories,
223 $id,
225 $nochildrenof,
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
239 * @param bool $top
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(
249 array $contexts,
250 bool $top = false,
251 int $currentcat = 0,
252 string $selected = "",
253 int $nochildrenof = -1,
254 bool $return = false,
255 ): ?string {
256 $categoriesarray = self::question_category_options(
257 $contexts,
258 $top,
259 $currentcat,
260 false,
261 $nochildrenof,
262 false,
264 $choose = '';
265 $options = [];
266 foreach ($categoriesarray as $group => $opts) {
267 $options[] = [$group => $opts];
269 $outputhtml = html_writer::label(
270 get_string('questioncategory', 'core_question'),
271 'id_movetocategory',
272 false,
273 ['class' => 'accesshide'],
275 $attrs = [
276 'id' => 'id_movetocategory',
277 'class' => 'custom-select',
278 'data-action' => 'toggle',
279 'data-togglegroup' => 'qbank',
280 'data-toggle' => 'action',
281 'disabled' => false,
283 $outputhtml .= html_writer::select($options, 'category', $selected, $choose, $attrs);
284 if ($return) {
285 return $outputhtml;
286 } else {
287 echo $outputhtml;
288 return null;
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(
304 string $contexts,
305 string $sortorder = 'parent, sortorder, name ASC',
306 bool $top = false,
307 int $showallversions = 0,
308 ): array {
309 global $DB;
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 . "' )";
314 $sql = "SELECT c.*,
315 (SELECT COUNT(1)
316 FROM {question} q
317 JOIN {question_versions} qv ON qv.questionid = q.id
318 JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
319 WHERE q.parent = '0'
320 $statuscondition
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)
329 ) AS questioncount
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.
346 * @return array
347 * @throws \coding_exception|\dml_exception
349 public static function question_category_options(
350 array $contexts,
351 bool $top = false,
352 int $currentcat = 0,
353 bool $popupform = false,
354 int $nochildrenof = -1,
355 bool $escapecontextnames = true,
356 ): array {
357 global $CFG;
358 $pcontexts = [];
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);
366 if ($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,
385 true,
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);
400 } else {
401 $formattedname = $a->name;
403 $categoriesarray[$contextstring][$cid] = $formattedname;
408 if ($popupform) {
409 $popupcats = [];
410 foreach ($categoriesarray as $contextstring => $optgroup) {
411 $group = [];
412 foreach ($optgroup as $key => $value) {
413 $key = str_replace($CFG->wwwroot, '', $key);
414 $group[$key] = $value;
416 $popupcats[] = [$contextstring => $group];
418 return $popupcats;
419 } else {
420 return $categoriesarray;
425 * Add context in categories key.
427 * @param array $categories The list of categories.
428 * @return array
430 public static function question_add_context_in_key(array $categories): array {
431 $newcatarray = [];
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;
437 return $newcatarray;
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));
457 return $categories;
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;