MDL-67548 core_course: Reflect content move category in deleted event.
[moodle.git] / course / classes / category.php
CommitLineData
442f12f8
MG
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 * Contains class core_course_category responsible for course category operations
19 *
20 * @package core
21 * @subpackage course
22 * @copyright 2013 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28/**
29 * Class to store, cache, render and manage course category
30 *
31 * @property-read int $id
32 * @property-read string $name
33 * @property-read string $idnumber
34 * @property-read string $description
35 * @property-read int $descriptionformat
36 * @property-read int $parent
37 * @property-read int $sortorder
38 * @property-read int $coursecount
39 * @property-read int $visible
40 * @property-read int $visibleold
41 * @property-read int $timemodified
42 * @property-read int $depth
43 * @property-read string $path
44 * @property-read string $theme
45 *
46 * @package core
47 * @subpackage course
48 * @copyright 2013 Marina Glancy
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 */
51class core_course_category implements renderable, cacheable_object, IteratorAggregate {
52 /** @var core_course_category stores pseudo category with id=0. Use core_course_category::get(0) to retrieve */
53 protected static $coursecat0;
54
55 /** @var array list of all fields and their short name and default value for caching */
56 protected static $coursecatfields = array(
57 'id' => array('id', 0),
58 'name' => array('na', ''),
59 'idnumber' => array('in', null),
60 'description' => null, // Not cached.
61 'descriptionformat' => null, // Not cached.
62 'parent' => array('pa', 0),
63 'sortorder' => array('so', 0),
64 'coursecount' => array('cc', 0),
65 'visible' => array('vi', 1),
66 'visibleold' => null, // Not cached.
67 'timemodified' => null, // Not cached.
68 'depth' => array('dh', 1),
69 'path' => array('ph', null),
70 'theme' => null, // Not cached.
71 );
72
73 /** @var int */
74 protected $id;
75
76 /** @var string */
77 protected $name = '';
78
79 /** @var string */
80 protected $idnumber = null;
81
82 /** @var string */
83 protected $description = false;
84
85 /** @var int */
86 protected $descriptionformat = false;
87
88 /** @var int */
89 protected $parent = 0;
90
91 /** @var int */
92 protected $sortorder = 0;
93
94 /** @var int */
95 protected $coursecount = false;
96
97 /** @var int */
98 protected $visible = 1;
99
100 /** @var int */
101 protected $visibleold = false;
102
103 /** @var int */
104 protected $timemodified = false;
105
106 /** @var int */
107 protected $depth = 0;
108
109 /** @var string */
110 protected $path = '';
111
112 /** @var string */
113 protected $theme = false;
114
115 /** @var bool */
beff3806 116 protected $fromcache = false;
442f12f8
MG
117
118 /**
119 * Magic setter method, we do not want anybody to modify properties from the outside
120 *
121 * @param string $name
122 * @param mixed $value
123 */
124 public function __set($name, $value) {
125 debugging('Can not change core_course_category instance properties!', DEBUG_DEVELOPER);
126 }
127
128 /**
129 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
130 *
131 * @param string $name
132 * @return mixed
133 */
134 public function __get($name) {
135 global $DB;
136 if (array_key_exists($name, self::$coursecatfields)) {
137 if ($this->$name === false) {
138 // Property was not retrieved from DB, retrieve all not retrieved fields.
139 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
140 $record = $DB->get_record('course_categories', array('id' => $this->id),
141 join(',', array_keys($notretrievedfields)), MUST_EXIST);
142 foreach ($record as $key => $value) {
143 $this->$key = $value;
144 }
145 }
146 return $this->$name;
147 }
148 debugging('Invalid core_course_category property accessed! '.$name, DEBUG_DEVELOPER);
149 return null;
150 }
151
152 /**
153 * Full support for isset on our magic read only properties.
154 *
155 * @param string $name
156 * @return bool
157 */
158 public function __isset($name) {
159 if (array_key_exists($name, self::$coursecatfields)) {
160 return isset($this->$name);
161 }
162 return false;
163 }
164
165 /**
166 * All properties are read only, sorry.
167 *
168 * @param string $name
169 */
170 public function __unset($name) {
171 debugging('Can not unset core_course_category instance properties!', DEBUG_DEVELOPER);
172 }
173
174 /**
175 * Create an iterator because magic vars can't be seen by 'foreach'.
176 *
177 * implementing method from interface IteratorAggregate
178 *
179 * @return ArrayIterator
180 */
181 public function getIterator() {
182 $ret = array();
183 foreach (self::$coursecatfields as $property => $unused) {
184 if ($this->$property !== false) {
185 $ret[$property] = $this->$property;
186 }
187 }
188 return new ArrayIterator($ret);
189 }
190
191 /**
192 * Constructor
193 *
194 * Constructor is protected, use core_course_category::get($id) to retrieve category
195 *
196 * @param stdClass $record record from DB (may not contain all fields)
197 * @param bool $fromcache whether it is being restored from cache
198 */
199 protected function __construct(stdClass $record, $fromcache = false) {
200 context_helper::preload_from_record($record);
201 foreach ($record as $key => $val) {
202 if (array_key_exists($key, self::$coursecatfields)) {
203 $this->$key = $val;
204 }
205 }
206 $this->fromcache = $fromcache;
207 }
208
209 /**
210 * Returns coursecat object for requested category
211 *
212 * If category is not visible to the given user, it is treated as non existing
213 * unless $alwaysreturnhidden is set to true
214 *
215 * If id is 0, the pseudo object for root category is returned (convenient
216 * for calling other functions such as get_children())
217 *
218 * @param int $id category id
219 * @param int $strictness whether to throw an exception (MUST_EXIST) or
220 * return null (IGNORE_MISSING) in case the category is not found or
221 * not visible to current user
222 * @param bool $alwaysreturnhidden set to true if you want an object to be
223 * returned even if this category is not visible to the current user
224 * (category is hidden and user does not have
225 * 'moodle/category:viewhiddencategories' capability). Use with care!
226 * @param int|stdClass $user The user id or object. By default (null) checks the visibility to the current user.
227 * @return null|self
228 * @throws moodle_exception
229 */
230 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false, $user = null) {
231 if (!$id) {
beff3806
MG
232 // Top-level category.
233 if ($alwaysreturnhidden || self::top()->is_uservisible()) {
234 return self::top();
442f12f8 235 }
beff3806
MG
236 if ($strictness == MUST_EXIST) {
237 throw new moodle_exception('cannotviewcategory');
238 }
239 return null;
442f12f8 240 }
beff3806
MG
241
242 // Try to get category from cache or retrieve from the DB.
442f12f8
MG
243 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
244 $coursecat = $coursecatrecordcache->get($id);
245 if ($coursecat === false) {
246 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
247 $record = reset($records);
248 $coursecat = new self($record);
249 // Store in cache.
250 $coursecatrecordcache->set($id, $coursecat);
251 }
252 }
beff3806
MG
253
254 if (!$coursecat) {
255 // Course category not found.
442f12f8
MG
256 if ($strictness == MUST_EXIST) {
257 throw new moodle_exception('unknowncategory');
258 }
beff3806
MG
259 $coursecat = null;
260 } else if (!$alwaysreturnhidden && !$coursecat->is_uservisible($user)) {
261 // Course category is found but user can not access it.
262 if ($strictness == MUST_EXIST) {
263 throw new moodle_exception('cannotviewcategory');
264 }
265 $coursecat = null;
442f12f8 266 }
beff3806
MG
267 return $coursecat;
268 }
269
270 /**
271 * Returns the pseudo-category representing the whole system (id=0, context_system)
272 *
273 * @return core_course_category
274 */
275 public static function top() {
276 if (!isset(self::$coursecat0)) {
277 $record = new stdClass();
278 $record->id = 0;
279 $record->visible = 1;
280 $record->depth = 0;
281 $record->path = '';
282 $record->locked = 0;
283 self::$coursecat0 = new self($record);
284 }
285 return self::$coursecat0;
286 }
287
288 /**
289 * Returns the top-most category for the current user
290 *
291 * Examples:
292 * 1. User can browse courses everywhere - return self::top() - pseudo-category with id=0
293 * 2. User does not have capability to browse courses on the system level but
294 * has it in ONE course category - return this course category
295 * 3. User has capability to browse courses in two course categories - return self::top()
296 *
297 * @return core_course_category|null
298 */
299 public static function user_top() {
300 $children = self::top()->get_children();
301 if (count($children) == 1) {
302 // User has access to only one category on the top level. Return this category as "user top category".
303 return reset($children);
304 }
305 if (count($children) > 1) {
306 // User has access to more than one category on the top level. Return the top as "user top category".
3bc57350 307 // In this case user actually may not have capability 'moodle/category:viewcourselist' on the top level.
beff3806
MG
308 return self::top();
309 }
310 // User can not access any categories on the top level.
311 // TODO MDL-10965 find ANY/ALL categories in the tree where user has access to.
312 return self::get(0, IGNORE_MISSING);
442f12f8
MG
313 }
314
315 /**
316 * Load many core_course_category objects.
317 *
318 * @param array $ids An array of category ID's to load.
319 * @return core_course_category[]
320 */
321 public static function get_many(array $ids) {
322 global $DB;
323 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
324 $categories = $coursecatrecordcache->get_many($ids);
325 $toload = array();
326 foreach ($categories as $id => $result) {
327 if ($result === false) {
328 $toload[] = $id;
329 }
330 }
331 if (!empty($toload)) {
332 list($where, $params) = $DB->get_in_or_equal($toload, SQL_PARAMS_NAMED);
333 $records = self::get_records('cc.id '.$where, $params);
334 $toset = array();
335 foreach ($records as $record) {
336 $categories[$record->id] = new self($record);
337 $toset[$record->id] = $categories[$record->id];
338 }
339 $coursecatrecordcache->set_many($toset);
340 }
341 return $categories;
342 }
343
344 /**
345 * Load all core_course_category objects.
346 *
347 * @param array $options Options:
348 * - returnhidden Return categories even if they are hidden
349 * @return core_course_category[]
350 */
351 public static function get_all($options = []) {
352 global $DB;
353
354 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
355
356 $catcontextsql = \context_helper::get_preload_record_columns_sql('ctx');
357 $catsql = "SELECT cc.*, {$catcontextsql}
358 FROM {course_categories} cc
359 JOIN {context} ctx ON cc.id = ctx.instanceid";
360 $catsqlwhere = "WHERE ctx.contextlevel = :contextlevel";
361 $catsqlorder = "ORDER BY cc.depth ASC, cc.sortorder ASC";
362
363 $catrs = $DB->get_recordset_sql("{$catsql} {$catsqlwhere} {$catsqlorder}", [
364 'contextlevel' => CONTEXT_COURSECAT,
365 ]);
366
367 $types['categories'] = [];
368 $categories = [];
369 $toset = [];
370 foreach ($catrs as $record) {
371 $category = new self($record);
372 $toset[$category->id] = $category;
373
374 if (!empty($options['returnhidden']) || $category->is_uservisible()) {
375 $categories[$record->id] = $category;
376 }
377 }
378 $catrs->close();
379
380 $coursecatrecordcache->set_many($toset);
381
382 return $categories;
383
384 }
385
386 /**
387 * Returns the first found category
388 *
389 * Note that if there are no categories visible to the current user on the first level,
390 * the invisible category may be returned
391 *
392 * @return core_course_category
393 */
394 public static function get_default() {
beff3806 395 if ($visiblechildren = self::top()->get_children()) {
442f12f8
MG
396 $defcategory = reset($visiblechildren);
397 } else {
398 $toplevelcategories = self::get_tree(0);
399 $defcategoryid = $toplevelcategories[0];
400 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
401 }
402 return $defcategory;
403 }
404
405 /**
406 * Restores the object after it has been externally modified in DB for example
407 * during {@link fix_course_sortorder()}
408 */
409 protected function restore() {
beff3806
MG
410 if (!$this->id) {
411 return;
412 }
442f12f8
MG
413 // Update all fields in the current object.
414 $newrecord = self::get($this->id, MUST_EXIST, true);
415 foreach (self::$coursecatfields as $key => $unused) {
416 $this->$key = $newrecord->$key;
417 }
418 }
419
420 /**
421 * Creates a new category either from form data or from raw data
422 *
423 * Please note that this function does not verify access control.
424 *
425 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
426 *
427 * Category visibility is inherited from parent unless $data->visible = 0 is specified
428 *
429 * @param array|stdClass $data
430 * @param array $editoroptions if specified, the data is considered to be
431 * form data and file_postupdate_standard_editor() is being called to
432 * process images in description.
433 * @return core_course_category
434 * @throws moodle_exception
435 */
436 public static function create($data, $editoroptions = null) {
437 global $DB, $CFG;
438 $data = (object)$data;
439 $newcategory = new stdClass();
440
441 $newcategory->descriptionformat = FORMAT_MOODLE;
442 $newcategory->description = '';
443 // Copy all description* fields regardless of whether this is form data or direct field update.
444 foreach ($data as $key => $value) {
445 if (preg_match("/^description/", $key)) {
446 $newcategory->$key = $value;
447 }
448 }
449
450 if (empty($data->name)) {
451 throw new moodle_exception('categorynamerequired');
452 }
453 if (core_text::strlen($data->name) > 255) {
454 throw new moodle_exception('categorytoolong');
455 }
456 $newcategory->name = $data->name;
457
458 // Validate and set idnumber.
459 if (isset($data->idnumber)) {
460 if (core_text::strlen($data->idnumber) > 100) {
461 throw new moodle_exception('idnumbertoolong');
462 }
463 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
464 throw new moodle_exception('categoryidnumbertaken');
465 }
466 $newcategory->idnumber = $data->idnumber;
467 }
468
469 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
470 $newcategory->theme = $data->theme;
471 }
472
473 if (empty($data->parent)) {
beff3806 474 $parent = self::top();
442f12f8
MG
475 } else {
476 $parent = self::get($data->parent, MUST_EXIST, true);
477 }
478 $newcategory->parent = $parent->id;
479 $newcategory->depth = $parent->depth + 1;
480
481 // By default category is visible, unless visible = 0 is specified or parent category is hidden.
482 if (isset($data->visible) && !$data->visible) {
483 // Create a hidden category.
484 $newcategory->visible = $newcategory->visibleold = 0;
485 } else {
486 // Create a category that inherits visibility from parent.
487 $newcategory->visible = $parent->visible;
488 // In case parent is hidden, when it changes visibility this new subcategory will automatically become visible too.
489 $newcategory->visibleold = 1;
490 }
491
492 $newcategory->sortorder = 0;
493 $newcategory->timemodified = time();
494
495 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
496
497 // Update path (only possible after we know the category id.
498 $path = $parent->path . '/' . $newcategory->id;
499 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
500
442f12f8
MG
501 fix_course_sortorder();
502
503 // If this is data from form results, save embedded files and update description.
504 $categorycontext = context_coursecat::instance($newcategory->id);
505 if ($editoroptions) {
506 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
507 'coursecat', 'description', 0);
508
509 // Update only fields description and descriptionformat.
510 $updatedata = new stdClass();
511 $updatedata->id = $newcategory->id;
512 $updatedata->description = $newcategory->description;
513 $updatedata->descriptionformat = $newcategory->descriptionformat;
514 $DB->update_record('course_categories', $updatedata);
515 }
516
517 $event = \core\event\course_category_created::create(array(
518 'objectid' => $newcategory->id,
519 'context' => $categorycontext
520 ));
521 $event->trigger();
522
523 cache_helper::purge_by_event('changesincoursecat');
524
525 return self::get($newcategory->id, MUST_EXIST, true);
526 }
527
528 /**
529 * Updates the record with either form data or raw data
530 *
531 * Please note that this function does not verify access control.
532 *
533 * This function calls core_course_category::change_parent_raw if field 'parent' is updated.
534 * It also calls core_course_category::hide_raw or core_course_category::show_raw if 'visible' is updated.
535 * Visibility is changed first and then parent is changed. This means that
536 * if parent category is hidden, the current category will become hidden
537 * too and it may overwrite whatever was set in field 'visible'.
538 *
539 * Note that fields 'path' and 'depth' can not be updated manually
540 * Also core_course_category::update() can not directly update the field 'sortoder'
541 *
542 * @param array|stdClass $data
543 * @param array $editoroptions if specified, the data is considered to be
544 * form data and file_postupdate_standard_editor() is being called to
545 * process images in description.
546 * @throws moodle_exception
547 */
548 public function update($data, $editoroptions = null) {
549 global $DB, $CFG;
550 if (!$this->id) {
551 // There is no actual DB record associated with root category.
552 return;
553 }
554
555 $data = (object)$data;
556 $newcategory = new stdClass();
557 $newcategory->id = $this->id;
558
559 // Copy all description* fields regardless of whether this is form data or direct field update.
560 foreach ($data as $key => $value) {
561 if (preg_match("/^description/", $key)) {
562 $newcategory->$key = $value;
563 }
564 }
565
566 if (isset($data->name) && empty($data->name)) {
567 throw new moodle_exception('categorynamerequired');
568 }
569
570 if (!empty($data->name) && $data->name !== $this->name) {
571 if (core_text::strlen($data->name) > 255) {
572 throw new moodle_exception('categorytoolong');
573 }
574 $newcategory->name = $data->name;
575 }
576
577 if (isset($data->idnumber) && $data->idnumber !== $this->idnumber) {
578 if (core_text::strlen($data->idnumber) > 100) {
579 throw new moodle_exception('idnumbertoolong');
580 }
581 if (strval($data->idnumber) !== '' && $DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
582 throw new moodle_exception('categoryidnumbertaken');
583 }
584 $newcategory->idnumber = $data->idnumber;
585 }
586
587 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
588 $newcategory->theme = $data->theme;
589 }
590
591 $changes = false;
592 if (isset($data->visible)) {
593 if ($data->visible) {
594 $changes = $this->show_raw();
595 } else {
596 $changes = $this->hide_raw(0);
597 }
598 }
599
600 if (isset($data->parent) && $data->parent != $this->parent) {
601 if ($changes) {
602 cache_helper::purge_by_event('changesincoursecat');
603 }
604 $parentcat = self::get($data->parent, MUST_EXIST, true);
605 $this->change_parent_raw($parentcat);
606 fix_course_sortorder();
607 }
608
609 $newcategory->timemodified = time();
610
611 $categorycontext = $this->get_context();
612 if ($editoroptions) {
613 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext,
614 'coursecat', 'description', 0);
615 }
616 $DB->update_record('course_categories', $newcategory);
617
618 $event = \core\event\course_category_updated::create(array(
619 'objectid' => $newcategory->id,
620 'context' => $categorycontext
621 ));
622 $event->trigger();
623
624 fix_course_sortorder();
625 // Purge cache even if fix_course_sortorder() did not do it.
626 cache_helper::purge_by_event('changesincoursecat');
627
628 // Update all fields in the current object.
629 $this->restore();
630 }
631
632
633 /**
634 * Checks if this course category is visible to a user.
635 *
636 * Please note that methods core_course_category::get (without 3rd argumet),
637 * core_course_category::get_children(), etc. return only visible categories so it is
638 * usually not needed to call this function outside of this class
639 *
640 * @param int|stdClass $user The user id or object. By default (null) checks the visibility to the current user.
641 * @return bool
642 */
643 public function is_uservisible($user = null) {
beff3806
MG
644 return self::can_view_category($this, $user);
645 }
646
647 /**
648 * Checks if current user has access to the category
649 *
650 * @param stdClass|core_course_category $category
651 * @param int|stdClass $user The user id or object. By default (null) checks access for the current user.
652 * @return bool
653 */
654 public static function can_view_category($category, $user = null) {
655 if (!$category->id) {
3bc57350 656 return has_capability('moodle/category:viewcourselist', context_system::instance(), $user);
beff3806
MG
657 }
658 $context = context_coursecat::instance($category->id);
659 if (!$category->visible && !has_capability('moodle/category:viewhiddencategories', $context, $user)) {
660 return false;
661 }
3bc57350 662 return has_capability('moodle/category:viewcourselist', $context, $user);
beff3806
MG
663 }
664
665 /**
666 * Checks if current user can view course information or enrolment page.
667 *
668 * This method does not check if user is already enrolled in the course
669 *
670 * @param stdClass $course course object (must have 'id', 'visible' and 'category' fields)
671 * @param null|stdClass $user The user id or object. By default (null) checks access for the current user.
672 */
673 public static function can_view_course_info($course, $user = null) {
674 if ($course->id == SITEID) {
675 return true;
676 }
677 if (!$course->visible) {
678 $coursecontext = context_course::instance($course->id);
679 if (!has_capability('moodle/course:viewhiddencourses', $coursecontext, $user)) {
680 return false;
681 }
682 }
683 $categorycontext = isset($course->category) ? context_coursecat::instance($course->category) :
684 context_course::instance($course->id)->get_parent_context();
3bc57350 685 return has_capability('moodle/category:viewcourselist', $categorycontext, $user);
442f12f8
MG
686 }
687
688 /**
689 * Returns the complete corresponding record from DB table course_categories
690 *
691 * Mostly used in deprecated functions
692 *
693 * @return stdClass
694 */
695 public function get_db_record() {
696 global $DB;
697 if ($record = $DB->get_record('course_categories', array('id' => $this->id))) {
698 return $record;
699 } else {
700 return (object)convert_to_array($this);
701 }
702 }
703
704 /**
705 * Returns the entry from categories tree and makes sure the application-level tree cache is built
706 *
707 * The following keys can be requested:
708 *
709 * 'countall' - total number of categories in the system (always present)
710 * 0 - array of ids of top-level categories (always present)
711 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
712 * $id (int) - array of ids of categories that are direct children of category with id $id. If
d62ce1d4 713 * category with id $id does not exist, or category has no children, returns empty array
442f12f8
MG
714 * $id.'i' - array of ids of children categories that have visible=0
715 *
716 * @param int|string $id
717 * @return mixed
718 */
719 protected static function get_tree($id) {
d62ce1d4
MJ
720 $all = self::get_cached_cat_tree();
721 if (is_null($all) || !isset($all[$id])) {
722 // Could not get or rebuild the tree, or requested a non-existant ID.
723 return [];
724 } else {
725 return $all[$id];
726 }
727 }
728
729 /**
730 * Return the course category tree.
731 *
732 * Returns the category tree array, from the cache if available or rebuilding the cache
733 * if required. Uses locking to prevent the cache being rebuilt by multiple requests at once.
734 *
735 * @return array|null The tree as an array, or null if rebuilding the tree failed due to a lock timeout.
736 * @throws coding_exception
737 * @throws dml_exception
738 * @throws moodle_exception
739 */
740 private static function get_cached_cat_tree() : ?array {
442f12f8 741 $coursecattreecache = cache::make('core', 'coursecattree');
d62ce1d4
MJ
742 $all = $coursecattreecache->get('all');
743 if ($all !== false) {
744 return $all;
442f12f8 745 }
96e44049
MJ
746 // Might need to rebuild the tree. Put a lock in place to ensure other requests don't try and do this in parallel.
747 $lockfactory = \core\lock\lock_config::get_lock_factory('core_coursecattree');
748 $lock = $lockfactory->get_lock('core_coursecattree_cache',
749 course_modinfo::COURSE_CACHE_LOCK_WAIT, course_modinfo::COURSE_CACHE_LOCK_EXPIRY);
750 if ($lock === false) {
751 // Couldn't get a lock to rebuild the tree.
d62ce1d4 752 return null;
96e44049 753 }
d62ce1d4
MJ
754 $all = $coursecattreecache->get('all');
755 if ($all !== false) {
96e44049
MJ
756 // Tree was built while we were waiting for the lock.
757 $lock->release();
d62ce1d4 758 return $all;
96e44049 759 }
442f12f8 760 // Re-build the tree.
96e44049
MJ
761 try {
762 $all = self::rebuild_coursecattree_cache_contents();
d62ce1d4 763 $coursecattreecache->set('all', $all);
96e44049
MJ
764 } finally {
765 $lock->release();
766 }
d62ce1d4 767 return $all;
96e44049
MJ
768 }
769
770 /**
771 * Rebuild the course category tree as an array, including an extra "countall" field.
772 *
773 * @return array
774 * @throws coding_exception
775 * @throws dml_exception
776 * @throws moodle_exception
777 */
778 private static function rebuild_coursecattree_cache_contents() : array {
779 global $DB;
442f12f8
MG
780 $sql = "SELECT cc.id, cc.parent, cc.visible
781 FROM {course_categories} cc
782 ORDER BY cc.sortorder";
783 $rs = $DB->get_recordset_sql($sql, array());
784 $all = array(0 => array(), '0i' => array());
785 $count = 0;
786 foreach ($rs as $record) {
787 $all[$record->id] = array();
788 $all[$record->id. 'i'] = array();
789 if (array_key_exists($record->parent, $all)) {
790 $all[$record->parent][] = $record->id;
791 if (!$record->visible) {
792 $all[$record->parent. 'i'][] = $record->id;
793 }
794 } else {
795 // Parent not found. This is data consistency error but next fix_course_sortorder() should fix it.
796 $all[0][] = $record->id;
797 if (!$record->visible) {
798 $all['0i'][] = $record->id;
799 }
800 }
801 $count++;
802 }
803 $rs->close();
804 if (!$count) {
805 // No categories found.
806 // This may happen after upgrade of a very old moodle version.
807 // In new versions the default category is created on install.
808 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
809 set_config('defaultrequestcategory', $defcoursecat->id);
810 $all[0] = array($defcoursecat->id);
811 $all[$defcoursecat->id] = array();
812 $count++;
813 }
814 // We must add countall to all in case it was the requested ID.
815 $all['countall'] = $count;
96e44049 816 return $all;
442f12f8
MG
817 }
818
819 /**
820 * Returns number of ALL categories in the system regardless if
821 * they are visible to current user or not
822 *
beff3806 823 * @deprecated since Moodle 3.7
442f12f8
MG
824 * @return int
825 */
826 public static function count_all() {
beff3806
MG
827 debugging('Method core_course_category::count_all() is deprecated. Please use ' .
828 'core_course_category::is_simple_site()', DEBUG_DEVELOPER);
442f12f8
MG
829 return self::get_tree('countall');
830 }
831
beff3806
MG
832 /**
833 * Checks if the site has only one category and it is visible and available.
834 *
835 * In many situations we won't show this category at all
836 * @return bool
837 */
838 public static function is_simple_site() {
839 if (self::get_tree('countall') != 1) {
840 return false;
841 }
842 $default = self::get_default();
843 return $default->visible && $default->is_uservisible();
844 }
845
442f12f8
MG
846 /**
847 * Retrieves number of records from course_categories table
848 *
849 * Only cached fields are retrieved. Records are ready for preloading context
850 *
851 * @param string $whereclause
852 * @param array $params
853 * @return array array of stdClass objects
854 */
855 protected static function get_records($whereclause, $params) {
856 global $DB;
857 // Retrieve from DB only the fields that need to be stored in cache.
858 $fields = array_keys(array_filter(self::$coursecatfields));
859 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
860 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
861 FROM {course_categories} cc
862 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
863 WHERE ". $whereclause." ORDER BY cc.sortorder";
864 return $DB->get_records_sql($sql,
865 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
866 }
867
868 /**
869 * Resets course contact caches when role assignments were changed
870 *
871 * @param int $roleid role id that was given or taken away
872 * @param context $context context where role assignment has been changed
873 */
874 public static function role_assignment_changed($roleid, $context) {
875 global $CFG, $DB;
876
877 if ($context->contextlevel > CONTEXT_COURSE) {
878 // No changes to course contacts if role was assigned on the module/block level.
879 return;
880 }
881
882 // Trigger a purge for all caches listening for changes to category enrolment.
883 cache_helper::purge_by_event('changesincategoryenrolment');
884
885 if (!$CFG->coursecontact || !in_array($roleid, explode(',', $CFG->coursecontact))) {
886 // The role is not one of course contact roles.
887 return;
888 }
889
890 // Remove from cache course contacts of all affected courses.
891 $cache = cache::make('core', 'coursecontacts');
892 if ($context->contextlevel == CONTEXT_COURSE) {
893 $cache->delete($context->instanceid);
894 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
895 $cache->purge();
896 } else {
897 $sql = "SELECT ctx.instanceid
898 FROM {context} ctx
899 WHERE ctx.path LIKE ? AND ctx.contextlevel = ?";
900 $params = array($context->path . '/%', CONTEXT_COURSE);
901 if ($courses = $DB->get_fieldset_sql($sql, $params)) {
902 $cache->delete_many($courses);
903 }
904 }
905 }
906
907 /**
908 * Executed when user enrolment was changed to check if course
909 * contacts cache needs to be cleared
910 *
911 * @param int $courseid course id
912 * @param int $userid user id
913 * @param int $status new enrolment status (0 - active, 1 - suspended)
914 * @param int $timestart new enrolment time start
915 * @param int $timeend new enrolment time end
916 */
917 public static function user_enrolment_changed($courseid, $userid,
918 $status, $timestart = null, $timeend = null) {
919 $cache = cache::make('core', 'coursecontacts');
920 $contacts = $cache->get($courseid);
921 if ($contacts === false) {
922 // The contacts for the affected course were not cached anyway.
923 return;
924 }
925 $enrolmentactive = ($status == 0) &&
926 (!$timestart || $timestart < time()) &&
927 (!$timeend || $timeend > time());
928 if (!$enrolmentactive) {
929 $isincontacts = false;
930 foreach ($contacts as $contact) {
931 if ($contact->id == $userid) {
932 $isincontacts = true;
933 }
934 }
935 if (!$isincontacts) {
936 // Changed user's enrolment does not exist or is not active,
937 // and he is not in cached course contacts, no changes to be made.
938 return;
939 }
940 }
941 // Either enrolment of manager was deleted/suspended
942 // or user enrolment was added or activated.
943 // In order to see if the course contacts for this course need
944 // changing we would need to make additional queries, they will
945 // slow down bulk enrolment changes. It is better just to remove
946 // course contacts cache for this course.
947 $cache->delete($courseid);
948 }
949
950 /**
951 * Given list of DB records from table course populates each record with list of users with course contact roles
952 *
953 * This function fills the courses with raw information as {@link get_role_users()} would do.
954 * See also {@link core_course_list_element::get_course_contacts()} for more readable return
955 *
956 * $courses[$i]->managers = array(
957 * $roleassignmentid => $roleuser,
958 * ...
959 * );
960 *
961 * where $roleuser is an stdClass with the following properties:
962 *
963 * $roleuser->raid - role assignment id
964 * $roleuser->id - user id
965 * $roleuser->username
966 * $roleuser->firstname
967 * $roleuser->lastname
968 * $roleuser->rolecoursealias
969 * $roleuser->rolename
970 * $roleuser->sortorder - role sortorder
971 * $roleuser->roleid
972 * $roleuser->roleshortname
973 *
974 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
975 *
976 * @param array $courses
977 */
978 public static function preload_course_contacts(&$courses) {
979 global $CFG, $DB;
980 if (empty($courses) || empty($CFG->coursecontact)) {
981 return;
982 }
983 $managerroles = explode(',', $CFG->coursecontact);
984 $cache = cache::make('core', 'coursecontacts');
985 $cacheddata = $cache->get_many(array_keys($courses));
986 $courseids = array();
987 foreach (array_keys($courses) as $id) {
988 if ($cacheddata[$id] !== false) {
989 $courses[$id]->managers = $cacheddata[$id];
990 } else {
991 $courseids[] = $id;
992 }
993 }
994
995 // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
996 if (empty($courseids)) {
997 return;
998 }
999
1000 // First build the array of all context ids of the courses and their categories.
1001 $allcontexts = array();
1002 foreach ($courseids as $id) {
1003 $context = context_course::instance($id);
1004 $courses[$id]->managers = array();
1005 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
1006 if (!isset($allcontexts[$ctxid])) {
1007 $allcontexts[$ctxid] = array();
1008 }
1009 $allcontexts[$ctxid][] = $id;
1010 }
1011 }
1012
1013 // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
1014 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
1015 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
1016 list($sort, $sortparams) = users_order_by_sql('u');
1017 $notdeleted = array('notdeleted' => 0);
1018 $allnames = get_all_user_name_fields(true, 'u');
1019 $sql = "SELECT ra.contextid, ra.id AS raid,
1020 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
1021 rn.name AS rolecoursealias, u.id, u.username, $allnames
1022 FROM {role_assignments} ra
1023 JOIN {user} u ON ra.userid = u.id
1024 JOIN {role} r ON ra.roleid = r.id
1025 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
1026 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
1027 ORDER BY r.sortorder, $sort";
1028 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
1029 $checkenrolments = array();
1030 foreach ($rs as $ra) {
1031 foreach ($allcontexts[$ra->contextid] as $id) {
1032 $courses[$id]->managers[$ra->raid] = $ra;
1033 if (!isset($checkenrolments[$id])) {
1034 $checkenrolments[$id] = array();
1035 }
1036 $checkenrolments[$id][] = $ra->id;
1037 }
1038 }
1039 $rs->close();
1040
1041 // Remove from course contacts users who are not enrolled in the course.
1042 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
1043 foreach ($checkenrolments as $id => $userids) {
1044 if (empty($enrolleduserids[$id])) {
1045 $courses[$id]->managers = array();
1046 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
1047 foreach ($courses[$id]->managers as $raid => $ra) {
1048 if (in_array($ra->id, $notenrolled)) {
1049 unset($courses[$id]->managers[$raid]);
1050 }
1051 }
1052 }
1053 }
1054
1055 // Set the cache.
1056 $values = array();
1057 foreach ($courseids as $id) {
1058 $values[$id] = $courses[$id]->managers;
1059 }
1060 $cache->set_many($values);
1061 }
1062
c1e15d20
MG
1063 /**
1064 * Preloads the custom fields values in bulk
1065 *
1066 * @param array $records
1067 */
1068 public static function preload_custom_fields(array &$records) {
1069 $customfields = \core_course\customfield\course_handler::create()->get_instances_data(array_keys($records));
1070 foreach ($customfields as $courseid => $data) {
1071 $records[$courseid]->customfields = $data;
1072 }
1073 }
1074
442f12f8
MG
1075 /**
1076 * Verify user enrollments for multiple course-user combinations
1077 *
1078 * @param array $courseusers array where keys are course ids and values are array
1079 * of users in this course whose enrolment we wish to verify
1080 * @return array same structure as input array but values list only users from input
1081 * who are enrolled in the course
1082 */
1083 protected static function ensure_users_enrolled($courseusers) {
1084 global $DB;
1085 // If the input array is too big, split it into chunks.
1086 $maxcoursesinquery = 20;
1087 if (count($courseusers) > $maxcoursesinquery) {
1088 $rv = array();
1089 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
1090 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
1091 $rv = $rv + self::ensure_users_enrolled($chunk);
1092 }
1093 return $rv;
1094 }
1095
1096 // Create a query verifying valid user enrolments for the number of courses.
1097 $sql = "SELECT DISTINCT e.courseid, ue.userid
1098 FROM {user_enrolments} ue
1099 JOIN {enrol} e ON e.id = ue.enrolid
1100 WHERE ue.status = :active
1101 AND e.status = :enabled
1102 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
1103 $now = round(time(), -2); // Rounding helps caching in DB.
1104 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
1105 'active' => ENROL_USER_ACTIVE,
1106 'now1' => $now, 'now2' => $now);
1107 $cnt = 0;
1108 $subsqls = array();
1109 $enrolled = array();
1110 foreach ($courseusers as $id => $userids) {
1111 $enrolled[$id] = array();
1112 if (count($userids)) {
1113 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
1114 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
1115 $params = $params + array('courseid'.$cnt => $id) + $params2;
1116 $cnt++;
1117 }
1118 }
1119 if (count($subsqls)) {
1120 $sql .= "AND (". join(' OR ', $subsqls).")";
1121 $rs = $DB->get_recordset_sql($sql, $params);
1122 foreach ($rs as $record) {
1123 $enrolled[$record->courseid][] = $record->userid;
1124 }
1125 $rs->close();
1126 }
1127 return $enrolled;
1128 }
1129
1130 /**
1131 * Retrieves number of records from course table
1132 *
1133 * Not all fields are retrieved. Records are ready for preloading context
1134 *
1135 * @param string $whereclause
1136 * @param array $params
beff3806 1137 * @param array $options may indicate that summary needs to be retrieved
442f12f8 1138 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
3bc57350 1139 * on not visible courses and 'moodle/category:viewcourselist' on all courses
442f12f8
MG
1140 * @return array array of stdClass objects
1141 */
1142 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
1143 global $DB;
1144 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1145 $fields = array('c.id', 'c.category', 'c.sortorder',
1146 'c.shortname', 'c.fullname', 'c.idnumber',
1147 'c.startdate', 'c.enddate', 'c.visible', 'c.cacherev');
1148 if (!empty($options['summary'])) {
1149 $fields[] = 'c.summary';
1150 $fields[] = 'c.summaryformat';
1151 } else {
1152 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
1153 }
1154 $sql = "SELECT ". join(',', $fields). ", $ctxselect
1155 FROM {course} c
1156 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
1157 WHERE ". $whereclause." ORDER BY c.sortorder";
1158 $list = $DB->get_records_sql($sql,
1159 array('contextcourse' => CONTEXT_COURSE) + $params);
1160
1161 if ($checkvisibility) {
beff3806 1162 $mycourses = enrol_get_my_courses();
442f12f8
MG
1163 // Loop through all records and make sure we only return the courses accessible by user.
1164 foreach ($list as $course) {
1165 if (isset($list[$course->id]->hassummary)) {
1166 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
1167 }
beff3806
MG
1168 context_helper::preload_from_record($course);
1169 $context = context_course::instance($course->id);
1170 // Check that course is accessible by user.
1171 if (!array_key_exists($course->id, $mycourses) && !self::can_view_course_info($course)) {
1172 unset($list[$course->id]);
442f12f8
MG
1173 }
1174 }
1175 }
1176
442f12f8
MG
1177 return $list;
1178 }
1179
1180 /**
1181 * Returns array of ids of children categories that current user can not see
1182 *
1183 * This data is cached in user session cache
1184 *
1185 * @return array
1186 */
1187 protected function get_not_visible_children_ids() {
1188 global $DB;
1189 $coursecatcache = cache::make('core', 'coursecat');
1190 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
1191 // We never checked visible children before.
1192 $hidden = self::get_tree($this->id.'i');
beff3806 1193 $catids = self::get_tree($this->id);
442f12f8 1194 $invisibleids = array();
beff3806 1195 if ($catids) {
442f12f8 1196 // Preload categories contexts.
beff3806 1197 list($sql, $params) = $DB->get_in_or_equal($catids, SQL_PARAMS_NAMED, 'id');
442f12f8
MG
1198 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1199 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
1200 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
1201 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
1202 foreach ($contexts as $record) {
1203 context_helper::preload_from_record($record);
1204 }
beff3806
MG
1205 // Check access for each category.
1206 foreach ($catids as $id) {
1207 $cat = (object)['id' => $id, 'visible' => in_array($id, $hidden) ? 0 : 1];
1208 if (!self::can_view_category($cat)) {
442f12f8
MG
1209 $invisibleids[] = $id;
1210 }
1211 }
1212 }
1213 $coursecatcache->set('ic'. $this->id, $invisibleids);
1214 }
1215 return $invisibleids;
1216 }
1217
1218 /**
1219 * Sorts list of records by several fields
1220 *
1221 * @param array $records array of stdClass objects
1222 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
1223 * @return int
1224 */
1225 protected static function sort_records(&$records, $sortfields) {
1226 if (empty($records)) {
1227 return;
1228 }
1229 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname).
1230 if (array_key_exists('displayname', $sortfields)) {
1231 foreach ($records as $key => $record) {
1232 if (!isset($record->displayname)) {
1233 $records[$key]->displayname = get_course_display_name_for_list($record);
1234 }
1235 }
1236 }
1237 // Sorting by one field - use core_collator.
1238 if (count($sortfields) == 1) {
1239 $property = key($sortfields);
1240 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
1241 $sortflag = core_collator::SORT_NUMERIC;
1242 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
1243 $sortflag = core_collator::SORT_STRING;
1244 } else {
1245 $sortflag = core_collator::SORT_REGULAR;
1246 }
1247 core_collator::asort_objects_by_property($records, $property, $sortflag);
1248 if ($sortfields[$property] < 0) {
1249 $records = array_reverse($records, true);
1250 }
1251 return;
1252 }
1253
1254 // Sort by multiple fields - use custom sorting.
1255 uasort($records, function($a, $b) use ($sortfields) {
1256 foreach ($sortfields as $field => $mult) {
1257 // Nulls first.
1258 if (is_null($a->$field) && !is_null($b->$field)) {
1259 return -$mult;
1260 }
1261 if (is_null($b->$field) && !is_null($a->$field)) {
1262 return $mult;
1263 }
1264
1265 if (is_string($a->$field) || is_string($b->$field)) {
1266 // String fields.
1267 if ($cmp = strcoll($a->$field, $b->$field)) {
1268 return $mult * $cmp;
1269 }
1270 } else {
1271 // Int fields.
1272 if ($a->$field > $b->$field) {
1273 return $mult;
1274 }
1275 if ($a->$field < $b->$field) {
1276 return -$mult;
1277 }
1278 }
1279 }
1280 return 0;
1281 });
1282 }
1283
1284 /**
1285 * Returns array of children categories visible to the current user
1286 *
1287 * @param array $options options for retrieving children
1288 * - sort - list of fields to sort. Example
1289 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
1290 * will sort by idnumber asc, name asc and id desc.
1291 * Default: array('sortorder' => 1)
1292 * Only cached fields may be used for sorting!
1293 * - offset
1294 * - limit - maximum number of children to return, 0 or null for no limit
1295 * @return core_course_category[] Array of core_course_category objects indexed by category id
1296 */
1297 public function get_children($options = array()) {
1298 global $DB;
1299 $coursecatcache = cache::make('core', 'coursecat');
1300
1301 // Get default values for options.
1302 if (!empty($options['sort']) && is_array($options['sort'])) {
1303 $sortfields = $options['sort'];
1304 } else {
1305 $sortfields = array('sortorder' => 1);
1306 }
1307 $limit = null;
1308 if (!empty($options['limit']) && (int)$options['limit']) {
1309 $limit = (int)$options['limit'];
1310 }
1311 $offset = 0;
1312 if (!empty($options['offset']) && (int)$options['offset']) {
1313 $offset = (int)$options['offset'];
1314 }
1315
1316 // First retrieve list of user-visible and sorted children ids from cache.
1317 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
1318 if ($sortedids === false) {
1319 $sortfieldskeys = array_keys($sortfields);
1320 if ($sortfieldskeys[0] === 'sortorder') {
1321 // No DB requests required to build the list of ids sorted by sortorder.
1322 // We can easily ignore other sort fields because sortorder is always different.
1323 $sortedids = self::get_tree($this->id);
1324 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
1325 $sortedids = array_diff($sortedids, $invisibleids);
1326 if ($sortfields['sortorder'] == -1) {
1327 $sortedids = array_reverse($sortedids, true);
1328 }
1329 }
1330 } else {
1331 // We need to retrieve and sort all children. Good thing that it is done only on first request.
1332 if ($invisibleids = $this->get_not_visible_children_ids()) {
1333 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1334 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1335 array('parent' => $this->id) + $params);
1336 } else {
1337 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1338 }
1339 self::sort_records($records, $sortfields);
1340 $sortedids = array_keys($records);
1341 }
1342 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1343 }
1344
1345 if (empty($sortedids)) {
1346 return array();
1347 }
1348
1349 // Now retrieive and return categories.
1350 if ($offset || $limit) {
1351 $sortedids = array_slice($sortedids, $offset, $limit);
1352 }
1353 if (isset($records)) {
1354 // Easy, we have already retrieved records.
1355 if ($offset || $limit) {
1356 $records = array_slice($records, $offset, $limit, true);
1357 }
1358 } else {
1359 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1360 $records = self::get_records('cc.id '. $sql, array('parent' => $this->id) + $params);
1361 }
1362
1363 $rv = array();
1364 foreach ($sortedids as $id) {
1365 if (isset($records[$id])) {
1366 $rv[$id] = new self($records[$id]);
1367 }
1368 }
1369 return $rv;
1370 }
1371
1372 /**
1373 * Returns an array of ids of categories that are (direct and indirect) children
1374 * of this category.
1375 *
1376 * @return int[]
1377 */
1378 public function get_all_children_ids() {
1379 $children = [];
1380 $walk = [$this->id];
1381 while (count($walk) > 0) {
1382 $catid = array_pop($walk);
1383 $directchildren = self::get_tree($catid);
d62ce1d4 1384 if (count($directchildren) > 0) {
442f12f8
MG
1385 $walk = array_merge($walk, $directchildren);
1386 $children = array_merge($children, $directchildren);
1387 }
1388 }
1389
1390 return $children;
1391 }
1392
1393 /**
1394 * Returns true if the user has the manage capability on any category.
1395 *
1396 * This method uses the coursecat cache and an entry `has_manage_capability` to speed up
1397 * calls to this method.
1398 *
1399 * @return bool
1400 */
1401 public static function has_manage_capability_on_any() {
1402 return self::has_capability_on_any('moodle/category:manage');
1403 }
1404
1405 /**
1406 * Checks if the user has at least one of the given capabilities on any category.
1407 *
1408 * @param array|string $capabilities One or more capabilities to check. Check made is an OR.
1409 * @return bool
1410 */
1411 public static function has_capability_on_any($capabilities) {
1412 global $DB;
1413 if (!isloggedin() || isguestuser()) {
1414 return false;
1415 }
1416
1417 if (!is_array($capabilities)) {
1418 $capabilities = array($capabilities);
1419 }
1420 $keys = array();
1421 foreach ($capabilities as $capability) {
1422 $keys[$capability] = sha1($capability);
1423 }
1424
1425 /** @var cache_session $cache */
1426 $cache = cache::make('core', 'coursecat');
1427 $hascapability = $cache->get_many($keys);
1428 $needtoload = false;
1429 foreach ($hascapability as $capability) {
1430 if ($capability === '1') {
1431 return true;
1432 } else if ($capability === false) {
1433 $needtoload = true;
1434 }
1435 }
1436 if ($needtoload === false) {
1437 // All capabilities were retrieved and the user didn't have any.
1438 return false;
1439 }
1440
1441 $haskey = null;
1442 $fields = context_helper::get_preload_record_columns_sql('ctx');
1443 $sql = "SELECT ctx.instanceid AS categoryid, $fields
1444 FROM {context} ctx
1445 WHERE contextlevel = :contextlevel
1446 ORDER BY depth ASC";
1447 $params = array('contextlevel' => CONTEXT_COURSECAT);
1448 $recordset = $DB->get_recordset_sql($sql, $params);
1449 foreach ($recordset as $context) {
1450 context_helper::preload_from_record($context);
1451 $context = context_coursecat::instance($context->categoryid);
1452 foreach ($capabilities as $capability) {
1453 if (has_capability($capability, $context)) {
1454 $haskey = $capability;
1455 break 2;
1456 }
1457 }
1458 }
1459 $recordset->close();
1460 if ($haskey === null) {
1461 $data = array();
1462 foreach ($keys as $key) {
1463 $data[$key] = '0';
1464 }
1465 $cache->set_many($data);
1466 return false;
1467 } else {
1468 $cache->set($haskey, '1');
1469 return true;
1470 }
1471 }
1472
1473 /**
1474 * Returns true if the user can resort any category.
1475 * @return bool
1476 */
1477 public static function can_resort_any() {
1478 return self::has_manage_capability_on_any();
1479 }
1480
1481 /**
1482 * Returns true if the user can change the parent of any category.
1483 * @return bool
1484 */
1485 public static function can_change_parent_any() {
1486 return self::has_manage_capability_on_any();
1487 }
1488
1489 /**
1490 * Returns number of subcategories visible to the current user
1491 *
1492 * @return int
1493 */
1494 public function get_children_count() {
1495 $sortedids = self::get_tree($this->id);
1496 $invisibleids = $this->get_not_visible_children_ids();
1497 return count($sortedids) - count($invisibleids);
1498 }
1499
1500 /**
1501 * Returns true if the category has ANY children, including those not visible to the user
1502 *
1503 * @return boolean
1504 */
1505 public function has_children() {
1506 $allchildren = self::get_tree($this->id);
1507 return !empty($allchildren);
1508 }
1509
1510 /**
1511 * Returns true if the category has courses in it (count does not include courses
1512 * in child categories)
1513 *
1514 * @return bool
1515 */
1516 public function has_courses() {
1517 global $DB;
1518 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1519 array($this->id));
1520 }
1521
1522 /**
1523 * Get the link used to view this course category.
1524 *
1525 * @return \moodle_url
1526 */
1527 public function get_view_link() {
1528 return new \moodle_url('/course/index.php', [
1529 'categoryid' => $this->id,
1530 ]);
1531 }
1532
1533 /**
1534 * Searches courses
1535 *
1536 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1537 * to this when somebody edits courses or categories, however it is very
1538 * difficult to keep track of all possible changes that may affect list of courses.
1539 *
1540 * @param array $search contains search criterias, such as:
1541 * - search - search string
1542 * - blocklist - id of block (if we are searching for courses containing specific block0
1543 * - modulelist - name of module (if we are searching for courses containing specific module
1544 * - tagid - id of tag
76f2d894 1545 * - onlywithcompletion - set to true if we only need courses with completion enabled
442f12f8
MG
1546 * @param array $options display options, same as in get_courses() except 'recursive' is ignored -
1547 * search is always category-independent
1548 * @param array $requiredcapabilities List of capabilities required to see return course.
1549 * @return core_course_list_element[]
1550 */
1551 public static function search_courses($search, $options = array(), $requiredcapabilities = array()) {
1552 global $DB;
1553 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1554 $limit = !empty($options['limit']) ? $options['limit'] : null;
1555 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1556
1557 $coursecatcache = cache::make('core', 'coursecat');
1558 $cachekey = 's-'. serialize(
1559 $search + array('sort' => $sortfields) + array('requiredcapabilities' => $requiredcapabilities)
1560 );
1561 $cntcachekey = 'scnt-'. serialize($search);
1562
1563 $ids = $coursecatcache->get($cachekey);
1564 if ($ids !== false) {
1565 // We already cached last search result.
1566 $ids = array_slice($ids, $offset, $limit);
1567 $courses = array();
1568 if (!empty($ids)) {
1569 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1570 $records = self::get_course_records("c.id ". $sql, $params, $options);
1571 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1572 if (!empty($options['coursecontacts'])) {
1573 self::preload_course_contacts($records);
1574 }
c1e15d20
MG
1575 // Preload custom fields if necessary - saves DB queries later to do it for each course separately.
1576 if (!empty($options['customfields'])) {
1577 self::preload_custom_fields($records);
1578 }
442f12f8
MG
1579 // If option 'idonly' is specified no further action is needed, just return list of ids.
1580 if (!empty($options['idonly'])) {
1581 return array_keys($records);
1582 }
1583 // Prepare the list of core_course_list_element objects.
1584 foreach ($ids as $id) {
1585 $courses[$id] = new core_course_list_element($records[$id]);
1586 }
1587 }
1588 return $courses;
1589 }
1590
1591 $preloadcoursecontacts = !empty($options['coursecontacts']);
1592 unset($options['coursecontacts']);
1593
1594 // Empty search string will return all results.
1595 if (!isset($search['search'])) {
1596 $search['search'] = '';
1597 }
1598
1599 if (empty($search['blocklist']) && empty($search['modulelist']) && empty($search['tagid'])) {
1600 // Search courses that have specified words in their names/summaries.
1601 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
76f2d894
MG
1602 $searchcond = $searchcondparams = [];
1603 if (!empty($search['onlywithcompletion'])) {
1604 $searchcond = ['c.enablecompletion = :p1'];
1605 $searchcondparams = ['p1' => 1];
1606 }
1607 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount,
1608 $requiredcapabilities, $searchcond, $searchcondparams);
442f12f8
MG
1609 self::sort_records($courselist, $sortfields);
1610 $coursecatcache->set($cachekey, array_keys($courselist));
1611 $coursecatcache->set($cntcachekey, $totalcount);
1612 $records = array_slice($courselist, $offset, $limit, true);
1613 } else {
1614 if (!empty($search['blocklist'])) {
1615 // Search courses that have block with specified id.
1616 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1617 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1618 WHERE bi.blockname = :blockname)';
1619 $params = array('blockname' => $blockname);
1620 } else if (!empty($search['modulelist'])) {
1621 // Search courses that have module with specified name.
1622 $where = "c.id IN (SELECT DISTINCT module.course ".
1623 "FROM {".$search['modulelist']."} module)";
1624 $params = array();
1625 } else if (!empty($search['tagid'])) {
1626 // Search courses that are tagged with the specified tag.
1627 $where = "c.id IN (SELECT t.itemid ".
1628 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype AND t.component = :component)";
1629 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course', 'component' => 'core');
1630 if (!empty($search['ctx'])) {
1631 $rec = isset($search['rec']) ? $search['rec'] : true;
1632 $parentcontext = context::instance_by_id($search['ctx']);
1633 if ($parentcontext->contextlevel == CONTEXT_SYSTEM && $rec) {
1634 // Parent context is system context and recursive is set to yes.
1635 // Nothing to filter - all courses fall into this condition.
1636 } else if ($rec) {
1637 // Filter all courses in the parent context at any level.
1638 $where .= ' AND ctx.path LIKE :contextpath';
1639 $params['contextpath'] = $parentcontext->path . '%';
1640 } else if ($parentcontext->contextlevel == CONTEXT_COURSECAT) {
1641 // All courses in the given course category.
1642 $where .= ' AND c.category = :category';
1643 $params['category'] = $parentcontext->instanceid;
1644 } else {
1645 // No courses will satisfy the context criterion, do not bother searching.
1646 $where = '1=0';
1647 }
1648 }
1649 } else {
1650 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1651 return array();
1652 }
1653 $courselist = self::get_course_records($where, $params, $options, true);
1654 if (!empty($requiredcapabilities)) {
1655 foreach ($courselist as $key => $course) {
1656 context_helper::preload_from_record($course);
1657 $coursecontext = context_course::instance($course->id);
1658 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
1659 unset($courselist[$key]);
1660 }
1661 }
1662 }
1663 self::sort_records($courselist, $sortfields);
1664 $coursecatcache->set($cachekey, array_keys($courselist));
1665 $coursecatcache->set($cntcachekey, count($courselist));
1666 $records = array_slice($courselist, $offset, $limit, true);
1667 }
1668
1669 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1670 if (!empty($preloadcoursecontacts)) {
1671 self::preload_course_contacts($records);
1672 }
c1e15d20
MG
1673 // Preload custom fields if necessary - saves DB queries later to do it for each course separately.
1674 if (!empty($options['customfields'])) {
1675 self::preload_custom_fields($records);
1676 }
442f12f8
MG
1677 // If option 'idonly' is specified no further action is needed, just return list of ids.
1678 if (!empty($options['idonly'])) {
1679 return array_keys($records);
1680 }
1681 // Prepare the list of core_course_list_element objects.
1682 $courses = array();
1683 foreach ($records as $record) {
1684 $courses[$record->id] = new core_course_list_element($record);
1685 }
1686 return $courses;
1687 }
1688
1689 /**
1690 * Returns number of courses in the search results
1691 *
1692 * It is recommended to call this function after {@link core_course_category::search_courses()}
1693 * and not before because only course ids are cached. Otherwise search_courses() may
1694 * perform extra DB queries.
1695 *
1696 * @param array $search search criteria, see method search_courses() for more details
1697 * @param array $options display options. They do not affect the result but
1698 * the 'sort' property is used in cache key for storing list of course ids
1699 * @param array $requiredcapabilities List of capabilities required to see return course.
1700 * @return int
1701 */
1702 public static function search_courses_count($search, $options = array(), $requiredcapabilities = array()) {
1703 $coursecatcache = cache::make('core', 'coursecat');
1704 $cntcachekey = 'scnt-'. serialize($search) . serialize($requiredcapabilities);
1705 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1706 // Cached value not found. Retrieve ALL courses and return their count.
1707 unset($options['offset']);
1708 unset($options['limit']);
1709 unset($options['summary']);
1710 unset($options['coursecontacts']);
1711 $options['idonly'] = true;
1712 $courses = self::search_courses($search, $options, $requiredcapabilities);
1713 $cnt = count($courses);
1714 }
1715 return $cnt;
1716 }
1717
1718 /**
1719 * Retrieves the list of courses accessible by user
1720 *
1721 * Not all information is cached, try to avoid calling this method
1722 * twice in the same request.
1723 *
1724 * The following fields are always retrieved:
1725 * - id, visible, fullname, shortname, idnumber, category, sortorder
1726 *
1727 * If you plan to use properties/methods core_course_list_element::$summary and/or
1728 * core_course_list_element::get_course_contacts()
1729 * you can preload this information using appropriate 'options'. Otherwise
1730 * they will be retrieved from DB on demand and it may end with bigger DB load.
1731 *
1732 * Note that method core_course_list_element::has_summary() will not perform additional
1733 * DB queries even if $options['summary'] is not specified
1734 *
1735 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1736 * to this when somebody edits courses or categories, however it is very
1737 * difficult to keep track of all possible changes that may affect list of courses.
1738 *
1739 * @param array $options options for retrieving children
1740 * - recursive - return courses from subcategories as well. Use with care,
1741 * this may be a huge list!
1742 * - summary - preloads fields 'summary' and 'summaryformat'
1743 * - coursecontacts - preloads course contacts
1744 * - sort - list of fields to sort. Example
1745 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1746 * will sort by idnumber asc, shortname asc and id desc.
1747 * Default: array('sortorder' => 1)
1748 * Only cached fields may be used for sorting!
1749 * - offset
1750 * - limit - maximum number of children to return, 0 or null for no limit
1751 * - idonly - returns the array or course ids instead of array of objects
1752 * used only in get_courses_count()
1753 * @return core_course_list_element[]
1754 */
1755 public function get_courses($options = array()) {
1756 global $DB;
1757 $recursive = !empty($options['recursive']);
1758 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1759 $limit = !empty($options['limit']) ? $options['limit'] : null;
1760 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1761
beff3806
MG
1762 if (!$this->id && !$recursive) {
1763 // There are no courses on system level unless we need recursive list.
1764 return [];
442f12f8
MG
1765 }
1766
1767 $coursecatcache = cache::make('core', 'coursecat');
1768 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1769 '-'. serialize($sortfields);
1770 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1771
1772 // Check if we have already cached results.
1773 $ids = $coursecatcache->get($cachekey);
1774 if ($ids !== false) {
1775 // We already cached last search result and it did not expire yet.
1776 $ids = array_slice($ids, $offset, $limit);
1777 $courses = array();
1778 if (!empty($ids)) {
1779 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1780 $records = self::get_course_records("c.id ". $sql, $params, $options);
1781 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1782 if (!empty($options['coursecontacts'])) {
1783 self::preload_course_contacts($records);
1784 }
1785 // If option 'idonly' is specified no further action is needed, just return list of ids.
1786 if (!empty($options['idonly'])) {
1787 return array_keys($records);
1788 }
c1e15d20
MG
1789 // Preload custom fields if necessary - saves DB queries later to do it for each course separately.
1790 if (!empty($options['customfields'])) {
1791 self::preload_custom_fields($records);
1792 }
442f12f8
MG
1793 // Prepare the list of core_course_list_element objects.
1794 foreach ($ids as $id) {
1795 $courses[$id] = new core_course_list_element($records[$id]);
1796 }
1797 }
1798 return $courses;
1799 }
1800
1801 // Retrieve list of courses in category.
1802 $where = 'c.id <> :siteid';
1803 $params = array('siteid' => SITEID);
1804 if ($recursive) {
1805 if ($this->id) {
1806 $context = context_coursecat::instance($this->id);
1807 $where .= ' AND ctx.path like :path';
1808 $params['path'] = $context->path. '/%';
1809 }
1810 } else {
1811 $where .= ' AND c.category = :categoryid';
1812 $params['categoryid'] = $this->id;
1813 }
1814 // Get list of courses without preloaded coursecontacts because we don't need them for every course.
1815 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1816
1817 // Sort and cache list.
1818 self::sort_records($list, $sortfields);
1819 $coursecatcache->set($cachekey, array_keys($list));
1820 $coursecatcache->set($cntcachekey, count($list));
1821
1822 // Apply offset/limit, convert to core_course_list_element and return.
1823 $courses = array();
1824 if (isset($list)) {
1825 if ($offset || $limit) {
1826 $list = array_slice($list, $offset, $limit, true);
1827 }
1828 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1829 if (!empty($options['coursecontacts'])) {
1830 self::preload_course_contacts($list);
1831 }
c1e15d20
MG
1832 // Preload custom fields if necessary - saves DB queries later to do it for each course separately.
1833 if (!empty($options['customfields'])) {
1834 self::preload_custom_fields($list);
1835 }
442f12f8
MG
1836 // If option 'idonly' is specified no further action is needed, just return list of ids.
1837 if (!empty($options['idonly'])) {
1838 return array_keys($list);
1839 }
1840 // Prepare the list of core_course_list_element objects.
1841 foreach ($list as $record) {
1842 $courses[$record->id] = new core_course_list_element($record);
1843 }
1844 }
1845 return $courses;
1846 }
1847
1848 /**
1849 * Returns number of courses visible to the user
1850 *
1851 * @param array $options similar to get_courses() except some options do not affect
1852 * number of courses (i.e. sort, summary, offset, limit etc.)
1853 * @return int
1854 */
1855 public function get_courses_count($options = array()) {
1856 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1857 $coursecatcache = cache::make('core', 'coursecat');
1858 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1859 // Cached value not found. Retrieve ALL courses and return their count.
1860 unset($options['offset']);
1861 unset($options['limit']);
1862 unset($options['summary']);
1863 unset($options['coursecontacts']);
1864 $options['idonly'] = true;
1865 $courses = $this->get_courses($options);
1866 $cnt = count($courses);
1867 }
1868 return $cnt;
1869 }
1870
1871 /**
1872 * Returns true if the user is able to delete this category.
1873 *
1874 * Note if this category contains any courses this isn't a full check, it will need to be accompanied by a call to either
1875 * {@link core_course_category::can_delete_full()} or {@link core_course_category::can_move_content_to()}
1876 * depending upon what the user wished to do.
1877 *
1878 * @return boolean
1879 */
1880 public function can_delete() {
1881 if (!$this->has_manage_capability()) {
1882 return false;
1883 }
1884 return $this->parent_has_manage_capability();
1885 }
1886
1887 /**
1888 * Returns true if user can delete current category and all its contents
1889 *
1890 * To be able to delete course category the user must have permission
1891 * 'moodle/category:manage' in ALL child course categories AND
1892 * be able to delete all courses
1893 *
1894 * @return bool
1895 */
1896 public function can_delete_full() {
1897 global $DB;
1898 if (!$this->id) {
1899 // Fool-proof.
1900 return false;
1901 }
1902
1903 $context = $this->get_context();
1904 if (!$this->is_uservisible() ||
1905 !has_capability('moodle/category:manage', $context)) {
1906 return false;
1907 }
1908
1909 // Check all child categories (not only direct children).
1910 $sql = context_helper::get_preload_record_columns_sql('ctx');
1911 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1912 ' FROM {context} ctx '.
1913 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1914 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1915 array($context->path. '/%', CONTEXT_COURSECAT));
1916 foreach ($childcategories as $childcat) {
1917 context_helper::preload_from_record($childcat);
1918 $childcontext = context_coursecat::instance($childcat->id);
1919 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1920 !has_capability('moodle/category:manage', $childcontext)) {
1921 return false;
1922 }
1923 }
1924
1925 // Check courses.
1926 $sql = context_helper::get_preload_record_columns_sql('ctx');
1927 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1928 $sql. ' FROM {context} ctx '.
1929 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
1930 array('pathmask' => $context->path. '/%',
1931 'courselevel' => CONTEXT_COURSE));
1932 foreach ($coursescontexts as $ctxrecord) {
1933 context_helper::preload_from_record($ctxrecord);
1934 if (!can_delete_course($ctxrecord->courseid)) {
1935 return false;
1936 }
1937 }
1938
1939 return true;
1940 }
1941
1942 /**
1943 * Recursively delete category including all subcategories and courses
1944 *
1945 * Function {@link core_course_category::can_delete_full()} MUST be called prior
1946 * to calling this function because there is no capability check
1947 * inside this function
1948 *
1949 * @param boolean $showfeedback display some notices
1950 * @return array return deleted courses
1951 * @throws moodle_exception
1952 */
1953 public function delete_full($showfeedback = true) {
1954 global $CFG, $DB;
1955
1956 require_once($CFG->libdir.'/gradelib.php');
1957 require_once($CFG->libdir.'/questionlib.php');
1958 require_once($CFG->dirroot.'/cohort/lib.php');
1959
1960 // Make sure we won't timeout when deleting a lot of courses.
1961 $settimeout = core_php_time_limit::raise();
1962
1963 // Allow plugins to use this category before we completely delete it.
1964 if ($pluginsfunction = get_plugins_with_function('pre_course_category_delete')) {
1965 $category = $this->get_db_record();
1966 foreach ($pluginsfunction as $plugintype => $plugins) {
1967 foreach ($plugins as $pluginfunction) {
1968 $pluginfunction($category);
1969 }
1970 }
1971 }
1972
1973 $deletedcourses = array();
1974
1975 // Get children. Note, we don't want to use cache here because it would be rebuilt too often.
1976 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1977 foreach ($children as $record) {
1978 $coursecat = new self($record);
1979 $deletedcourses += $coursecat->delete_full($showfeedback);
1980 }
1981
1982 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1983 foreach ($courses as $course) {
1984 if (!delete_course($course, false)) {
1985 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1986 }
1987 $deletedcourses[] = $course;
1988 }
1989 }
1990
1991 // Move or delete cohorts in this context.
1992 cohort_delete_category($this);
1993
1994 // Now delete anything that may depend on course category context.
1995 grade_course_category_delete($this->id, 0, $showfeedback);
1996 if (!question_delete_course_category($this, 0, $showfeedback)) {
1997 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1998 }
1999
2000 // Delete all events in the category.
2001 $DB->delete_records('event', array('categoryid' => $this->id));
2002
2003 // Finally delete the category and it's context.
2004 $DB->delete_records('course_categories', array('id' => $this->id));
2005
2006 $coursecatcontext = context_coursecat::instance($this->id);
2007 $coursecatcontext->delete();
2008
2009 cache_helper::purge_by_event('changesincoursecat');
2010
2011 // Trigger a course category deleted event.
2012 /** @var \core\event\course_category_deleted $event */
2013 $event = \core\event\course_category_deleted::create(array(
2014 'objectid' => $this->id,
2015 'context' => $coursecatcontext,
2016 'other' => array('name' => $this->name)
2017 ));
2018 $event->set_coursecat($this);
2019 $event->trigger();
2020
2021 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
2022 if ($this->id == $CFG->defaultrequestcategory) {
2023 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
2024 }
2025 return $deletedcourses;
2026 }
2027
2028 /**
2029 * Checks if user can delete this category and move content (courses, subcategories and questions)
2030 * to another category. If yes returns the array of possible target categories names
2031 *
2032 * If user can not manage this category or it is completely empty - empty array will be returned
2033 *
2034 * @return array
2035 */
2036 public function move_content_targets_list() {
2037 global $CFG;
2038 require_once($CFG->libdir . '/questionlib.php');
2039 $context = $this->get_context();
2040 if (!$this->is_uservisible() ||
2041 !has_capability('moodle/category:manage', $context)) {
2042 // User is not able to manage current category, he is not able to delete it.
2043 // No possible target categories.
2044 return array();
2045 }
2046
2047 $testcaps = array();
2048 // If this category has courses in it, user must have 'course:create' capability in target category.
2049 if ($this->has_courses()) {
2050 $testcaps[] = 'moodle/course:create';
2051 }
2052 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
2053 if ($this->has_children() || question_context_has_any_questions($context)) {
2054 $testcaps[] = 'moodle/category:manage';
2055 }
2056 if (!empty($testcaps)) {
2057 // Return list of categories excluding this one and it's children.
2058 return self::make_categories_list($testcaps, $this->id);
2059 }
2060
2061 // Category is completely empty, no need in target for contents.
2062 return array();
2063 }
2064
2065 /**
2066 * Checks if user has capability to move all category content to the new parent before
2067 * removing this category
2068 *
2069 * @param int $newcatid
2070 * @return bool
2071 */
2072 public function can_move_content_to($newcatid) {
2073 global $CFG;
2074 require_once($CFG->libdir . '/questionlib.php');
2075 $context = $this->get_context();
2076 if (!$this->is_uservisible() ||
2077 !has_capability('moodle/category:manage', $context)) {
2078 return false;
2079 }
2080 $testcaps = array();
2081 // If this category has courses in it, user must have 'course:create' capability in target category.
2082 if ($this->has_courses()) {
2083 $testcaps[] = 'moodle/course:create';
2084 }
2085 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
2086 if ($this->has_children() || question_context_has_any_questions($context)) {
2087 $testcaps[] = 'moodle/category:manage';
2088 }
2089 if (!empty($testcaps)) {
2090 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
2091 }
2092
2093 // There is no content but still return true.
2094 return true;
2095 }
2096
2097 /**
2098 * Deletes a category and moves all content (children, courses and questions) to the new parent
2099 *
2100 * Note that this function does not check capabilities, {@link core_course_category::can_move_content_to()}
2101 * must be called prior
2102 *
2103 * @param int $newparentid
2104 * @param bool $showfeedback
2105 * @return bool
2106 */
2107 public function delete_move($newparentid, $showfeedback = false) {
2108 global $CFG, $DB, $OUTPUT;
2109
2110 require_once($CFG->libdir.'/gradelib.php');
2111 require_once($CFG->libdir.'/questionlib.php');
2112 require_once($CFG->dirroot.'/cohort/lib.php');
2113
2114 // Get all objects and lists because later the caches will be reset so.
2115 // We don't need to make extra queries.
2116 $newparentcat = self::get($newparentid, MUST_EXIST, true);
2117 $catname = $this->get_formatted_name();
2118 $children = $this->get_children();
2119 $params = array('category' => $this->id);
2120 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', $params);
2121 $context = $this->get_context();
2122
2123 if ($children) {
2124 foreach ($children as $childcat) {
2125 $childcat->change_parent_raw($newparentcat);
2126 // Log action.
2127 $event = \core\event\course_category_updated::create(array(
2128 'objectid' => $childcat->id,
2129 'context' => $childcat->get_context()
2130 ));
2131 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $childcat->id,
2132 $childcat->id));
2133 $event->trigger();
2134 }
2135 fix_course_sortorder();
2136 }
2137
2138 if ($coursesids) {
2139 require_once($CFG->dirroot.'/course/lib.php');
2140 if (!move_courses($coursesids, $newparentid)) {
2141 if ($showfeedback) {
2142 echo $OUTPUT->notification("Error moving courses");
2143 }
2144 return false;
2145 }
2146 if ($showfeedback) {
2147 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
2148 }
2149 }
2150
2151 // Move or delete cohorts in this context.
2152 cohort_delete_category($this);
2153
2154 // Now delete anything that may depend on course category context.
2155 grade_course_category_delete($this->id, $newparentid, $showfeedback);
2156 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
2157 if ($showfeedback) {
2158 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
2159 }
2160 return false;
2161 }
2162
2163 // Finally delete the category and it's context.
2164 $DB->delete_records('course_categories', array('id' => $this->id));
2165 $context->delete();
2166
2167 // Trigger a course category deleted event.
2168 /** @var \core\event\course_category_deleted $event */
2169 $event = \core\event\course_category_deleted::create(array(
2170 'objectid' => $this->id,
2171 'context' => $context,
27b29b29 2172 'other' => array('name' => $this->name, 'contentmovedcategoryid' => $newparentid)
442f12f8
MG
2173 ));
2174 $event->set_coursecat($this);
2175 $event->trigger();
2176
2177 cache_helper::purge_by_event('changesincoursecat');
2178
2179 if ($showfeedback) {
2180 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
2181 }
2182
2183 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
2184 if ($this->id == $CFG->defaultrequestcategory) {
2185 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
2186 }
2187 return true;
2188 }
2189
2190 /**
2191 * Checks if user can move current category to the new parent
2192 *
2193 * This checks if new parent category exists, user has manage cap there
2194 * and new parent is not a child of this category
2195 *
2196 * @param int|stdClass|core_course_category $newparentcat
2197 * @return bool
2198 */
2199 public function can_change_parent($newparentcat) {
2200 if (!has_capability('moodle/category:manage', $this->get_context())) {
2201 return false;
2202 }
2203 if (is_object($newparentcat)) {
2204 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
2205 } else {
2206 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
2207 }
2208 if (!$newparentcat) {
2209 return false;
2210 }
2211 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
2212 // Can not move to itself or it's own child.
2213 return false;
2214 }
2215 if ($newparentcat->id) {
2216 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
2217 } else {
2218 return has_capability('moodle/category:manage', context_system::instance());
2219 }
2220 }
2221
2222 /**
2223 * Moves the category under another parent category. All associated contexts are moved as well
2224 *
2225 * This is protected function, use change_parent() or update() from outside of this class
2226 *
2227 * @see core_course_category::change_parent()
2228 * @see core_course_category::update()
2229 *
2230 * @param core_course_category $newparentcat
2231 * @throws moodle_exception
2232 */
2233 protected function change_parent_raw(core_course_category $newparentcat) {
2234 global $DB;
2235
2236 $context = $this->get_context();
2237
2238 $hidecat = false;
2239 if (empty($newparentcat->id)) {
2240 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
2241 $newparent = context_system::instance();
2242 } else {
2243 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
2244 // Can not move to itself or it's own child.
2245 throw new moodle_exception('cannotmovecategory');
2246 }
2247 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
2248 $newparent = context_coursecat::instance($newparentcat->id);
2249
2250 if (!$newparentcat->visible and $this->visible) {
2251 // Better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children
2252 // will be restored properly.
2253 $hidecat = true;
2254 }
2255 }
2256 $this->parent = $newparentcat->id;
2257
2258 $context->update_moved($newparent);
2259
2260 // Now make it last in new category.
2261 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES, ['id' => $this->id]);
2262
2263 if ($hidecat) {
2264 fix_course_sortorder();
2265 $this->restore();
2266 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must
2267 // become visible again.
2268 $this->hide_raw(1);
2269 }
2270 }
2271
2272 /**
2273 * Efficiently moves a category - NOTE that this can have
2274 * a huge impact access-control-wise...
2275 *
2276 * Note that this function does not check capabilities.
2277 *
2278 * Example of usage:
2279 * $coursecat = core_course_category::get($categoryid);
2280 * if ($coursecat->can_change_parent($newparentcatid)) {
2281 * $coursecat->change_parent($newparentcatid);
2282 * }
2283 *
2284 * This function does not update field course_categories.timemodified
2285 * If you want to update timemodified, use
2286 * $coursecat->update(array('parent' => $newparentcat));
2287 *
2288 * @param int|stdClass|core_course_category $newparentcat
2289 */
2290 public function change_parent($newparentcat) {
2291 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
2292 if (is_object($newparentcat)) {
2293 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
2294 } else {
2295 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
2296 }
2297 if ($newparentcat->id != $this->parent) {
2298 $this->change_parent_raw($newparentcat);
2299 fix_course_sortorder();
2300 cache_helper::purge_by_event('changesincoursecat');
2301 $this->restore();
2302
2303 $event = \core\event\course_category_updated::create(array(
2304 'objectid' => $this->id,
2305 'context' => $this->get_context()
2306 ));
2307 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'editcategory.php?id=' . $this->id, $this->id));
2308 $event->trigger();
2309 }
2310 }
2311
2312 /**
2313 * Hide course category and child course and subcategories
2314 *
2315 * If this category has changed the parent and is moved under hidden
2316 * category we will want to store it's current visibility state in
2317 * the field 'visibleold'. If admin clicked 'hide' for this particular
2318 * category, the field 'visibleold' should become 0.
2319 *
2320 * All subcategories and courses will have their current visibility in the field visibleold
2321 *
2322 * This is protected function, use hide() or update() from outside of this class
2323 *
2324 * @see core_course_category::hide()
2325 * @see core_course_category::update()
2326 *
2327 * @param int $visibleold value to set in field $visibleold for this category
2328 * @return bool whether changes have been made and caches need to be purged afterwards
2329 */
2330 protected function hide_raw($visibleold = 0) {
2331 global $DB;
2332 $changes = false;
2333
2334 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing.
2335 if ($this->id && $this->__get('visibleold') != $visibleold) {
2336 $this->visibleold = $visibleold;
2337 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
2338 $changes = true;
2339 }
2340 if (!$this->visible || !$this->id) {
2341 // Already hidden or can not be hidden.
2342 return $changes;
2343 }
2344
2345 $this->visible = 0;
2346 $DB->set_field('course_categories', 'visible', 0, array('id' => $this->id));
2347 // Store visible flag so that we can return to it if we immediately unhide.
2348 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id));
2349 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
2350 // Get all child categories and hide too.
2351 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
2352 foreach ($subcats as $cat) {
2353 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
2354 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
2355 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
2356 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
2357 }
2358 }
2359 return true;
2360 }
2361
2362 /**
2363 * Hide course category and child course and subcategories
2364 *
2365 * Note that there is no capability check inside this function
2366 *
2367 * This function does not update field course_categories.timemodified
2368 * If you want to update timemodified, use
2369 * $coursecat->update(array('visible' => 0));
2370 */
2371 public function hide() {
2372 if ($this->hide_raw(0)) {
2373 cache_helper::purge_by_event('changesincoursecat');
2374
2375 $event = \core\event\course_category_updated::create(array(
2376 'objectid' => $this->id,
2377 'context' => $this->get_context()
2378 ));
2379 $event->set_legacy_logdata(array(SITEID, 'category', 'hide', 'editcategory.php?id=' . $this->id, $this->id));
2380 $event->trigger();
2381 }
2382 }
2383
2384 /**
2385 * Show course category and restores visibility for child course and subcategories
2386 *
2387 * Note that there is no capability check inside this function
2388 *
2389 * This is protected function, use show() or update() from outside of this class
2390 *
2391 * @see core_course_category::show()
2392 * @see core_course_category::update()
2393 *
2394 * @return bool whether changes have been made and caches need to be purged afterwards
2395 */
2396 protected function show_raw() {
2397 global $DB;
2398
2399 if ($this->visible) {
2400 // Already visible.
2401 return false;
2402 }
2403
2404 $this->visible = 1;
2405 $this->visibleold = 1;
2406 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
2407 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
2408 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
2409 // Get all child categories and unhide too.
2410 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
2411 foreach ($subcats as $cat) {
2412 if ($cat->visibleold) {
2413 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
2414 }
2415 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
2416 }
2417 }
2418 return true;
2419 }
2420
2421 /**
2422 * Show course category and restores visibility for child course and subcategories
2423 *
2424 * Note that there is no capability check inside this function
2425 *
2426 * This function does not update field course_categories.timemodified
2427 * If you want to update timemodified, use
2428 * $coursecat->update(array('visible' => 1));
2429 */
2430 public function show() {
2431 if ($this->show_raw()) {
2432 cache_helper::purge_by_event('changesincoursecat');
2433
2434 $event = \core\event\course_category_updated::create(array(
2435 'objectid' => $this->id,
2436 'context' => $this->get_context()
2437 ));
2438 $event->set_legacy_logdata(array(SITEID, 'category', 'show', 'editcategory.php?id=' . $this->id, $this->id));
2439 $event->trigger();
2440 }
2441 }
2442
2443 /**
2444 * Returns name of the category formatted as a string
2445 *
2446 * @param array $options formatting options other than context
2447 * @return string
2448 */
2449 public function get_formatted_name($options = array()) {
2450 if ($this->id) {
2451 $context = $this->get_context();
2452 return format_string($this->name, true, array('context' => $context) + $options);
2453 } else {
2454 return get_string('top');
2455 }
2456 }
2457
2458 /**
2459 * Get the nested name of this category, with all of it's parents.
2460 *
2461 * @param bool $includelinks Whether to wrap each name in the view link for that category.
2462 * @param string $separator The string between each name.
2463 * @param array $options Formatting options.
2464 * @return string
2465 */
2466 public function get_nested_name($includelinks = true, $separator = ' / ', $options = []) {
2467 // Get the name of hierarchical name of this category.
2468 $parents = $this->get_parents();
2469 $categories = static::get_many($parents);
2470 $categories[] = $this;
2471
2472 $names = array_map(function($category) use ($options, $includelinks) {
2473 if ($includelinks) {
2474 return html_writer::link($category->get_view_link(), $category->get_formatted_name($options));
2475 } else {
2476 return $category->get_formatted_name($options);
2477 }
2478
2479 }, $categories);
2480
2481 return implode($separator, $names);
2482 }
2483
2484 /**
2485 * Returns ids of all parents of the category. Last element in the return array is the direct parent
2486 *
2487 * For example, if you have a tree of categories like:
2488 * Miscellaneous (id = 1)
2489 * Subcategory (id = 2)
2490 * Sub-subcategory (id = 4)
2491 * Other category (id = 3)
2492 *
2493 * core_course_category::get(1)->get_parents() == array()
2494 * core_course_category::get(2)->get_parents() == array(1)
2495 * core_course_category::get(4)->get_parents() == array(1, 2);
2496 *
2497 * Note that this method does not check if all parents are accessible by current user
2498 *
2499 * @return array of category ids
2500 */
2501 public function get_parents() {
2502 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
2503 array_pop($parents);
2504 return $parents;
2505 }
2506
2507 /**
2508 * This function returns a nice list representing category tree
2509 * for display or to use in a form <select> element
2510 *
2511 * List is cached for 10 minutes
2512 *
2513 * For example, if you have a tree of categories like:
2514 * Miscellaneous (id = 1)
2515 * Subcategory (id = 2)
2516 * Sub-subcategory (id = 4)
2517 * Other category (id = 3)
2518 * Then after calling this function you will have
2519 * array(1 => 'Miscellaneous',
2520 * 2 => 'Miscellaneous / Subcategory',
2521 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
2522 * 3 => 'Other category');
2523 *
2524 * If you specify $requiredcapability, then only categories where the current
2525 * user has that capability will be added to $list.
2526 * If you only have $requiredcapability in a child category, not the parent,
2527 * then the child catgegory will still be included.
2528 *
2529 * If you specify the option $excludeid, then that category, and all its children,
2530 * are omitted from the tree. This is useful when you are doing something like
2531 * moving categories, where you do not want to allow people to move a category
2532 * to be the child of itself.
2533 *
2534 * See also {@link make_categories_options()}
2535 *
2536 * @param string/array $requiredcapability if given, only categories where the current
2537 * user has this capability will be returned. Can also be an array of capabilities,
2538 * in which case they are all required.
2539 * @param integer $excludeid Exclude this category and its children from the lists built.
2540 * @param string $separator string to use as a separator between parent and child category. Default ' / '
2541 * @return array of strings
2542 */
2543 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
2544 global $DB;
2545 $coursecatcache = cache::make('core', 'coursecat');
2546
2547 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids
2548 // with requried cap ($thislist).
2549 $currentlang = current_language();
2550 $basecachekey = $currentlang . '_catlist';
2551 $baselist = $coursecatcache->get($basecachekey);
2552 $thislist = false;
2553 $thiscachekey = null;
2554 if (!empty($requiredcapability)) {
2555 $requiredcapability = (array)$requiredcapability;
2556 $thiscachekey = 'catlist:'. serialize($requiredcapability);
2557 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
2558 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
2559 }
2560 } else if ($baselist !== false) {
beff3806
MG
2561 $thislist = array_keys(array_filter($baselist, function($el) {
2562 return $el['name'] !== false;
2563 }));
442f12f8
MG
2564 }
2565
2566 if ($baselist === false) {
2567 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
2568 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2569 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
2570 FROM {course_categories} cc
2571 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
2572 ORDER BY cc.sortorder";
2573 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2574 $baselist = array();
2575 $thislist = array();
2576 foreach ($rs as $record) {
beff3806
MG
2577 context_helper::preload_from_record($record);
2578 $context = context_coursecat::instance($record->id);
2579 $canview = self::can_view_category($record);
2580 $baselist[$record->id] = array(
2581 'name' => $canview ? format_string($record->name, true, array('context' => $context)) : false,
2582 'path' => $record->path
2583 );
2584 if (!$canview || (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context))) {
2585 // No required capability, added to $baselist but not to $thislist.
2586 continue;
442f12f8 2587 }
beff3806 2588 $thislist[] = $record->id;
442f12f8
MG
2589 }
2590 $rs->close();
2591 $coursecatcache->set($basecachekey, $baselist);
2592 if (!empty($requiredcapability)) {
2593 $coursecatcache->set($thiscachekey, join(',', $thislist));
2594 }
2595 } else if ($thislist === false) {
2596 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
2597 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
2598 $sql = "SELECT ctx.instanceid AS id, $ctxselect
2599 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
2600 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
2601 $thislist = array();
2602 foreach (array_keys($baselist) as $id) {
beff3806
MG
2603 if ($baselist[$id]['name'] !== false) {
2604 context_helper::preload_from_record($contexts[$id]);
2605 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
2606 $thislist[] = $id;
2607 }
442f12f8
MG
2608 }
2609 }
2610 $coursecatcache->set($thiscachekey, join(',', $thislist));
2611 }
2612
2613 // Now build the array of strings to return, mind $separator and $excludeid.
2614 $names = array();
2615 foreach ($thislist as $id) {
2616 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
2617 if (!$excludeid || !in_array($excludeid, $path)) {
2618 $namechunks = array();
2619 foreach ($path as $parentid) {
beff3806
MG
2620 if (array_key_exists($parentid, $baselist) && $baselist[$parentid]['name'] !== false) {
2621 $namechunks[] = $baselist[$parentid]['name'];
2622 }
442f12f8
MG
2623 }
2624 $names[$id] = join($separator, $namechunks);
2625 }
2626 }
2627 return $names;
2628 }
2629
2630 /**
2631 * Prepares the object for caching. Works like the __sleep method.
2632 *
2633 * implementing method from interface cacheable_object
2634 *
2635 * @return array ready to be cached
2636 */
2637 public function prepare_to_cache() {
2638 $a = array();
2639 foreach (self::$coursecatfields as $property => $cachedirectives) {
2640 if ($cachedirectives !== null) {
2641 list($shortname, $defaultvalue) = $cachedirectives;
2642 if ($this->$property !== $defaultvalue) {
2643 $a[$shortname] = $this->$property;
2644 }
2645 }
2646 }
2647 $context = $this->get_context();
2648 $a['xi'] = $context->id;
2649 $a['xp'] = $context->path;
0616f045 2650 $a['xl'] = $context->locked;
442f12f8
MG
2651 return $a;
2652 }
2653
2654 /**
2655 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2656 *
2657 * implementing method from interface cacheable_object
2658 *
2659 * @param array $a
2660 * @return core_course_category
2661 */
2662 public static function wake_from_cache($a) {
2663 $record = new stdClass;
2664 foreach (self::$coursecatfields as $property => $cachedirectives) {
2665 if ($cachedirectives !== null) {
2666 list($shortname, $defaultvalue) = $cachedirectives;
2667 if (array_key_exists($shortname, $a)) {
2668 $record->$property = $a[$shortname];
2669 } else {
2670 $record->$property = $defaultvalue;
2671 }
2672 }
2673 }
2674 $record->ctxid = $a['xi'];
2675 $record->ctxpath = $a['xp'];
2676 $record->ctxdepth = $record->depth + 1;
2677 $record->ctxlevel = CONTEXT_COURSECAT;
2678 $record->ctxinstance = $record->id;
0616f045 2679 $record->ctxlocked = $a['xl'];
442f12f8
MG
2680 return new self($record, true);
2681 }
2682
2683 /**
2684 * Returns true if the user is able to create a top level category.
2685 * @return bool
2686 */
2687 public static function can_create_top_level_category() {
beff3806 2688 return self::top()->has_manage_capability();
442f12f8
MG
2689 }
2690
2691 /**
2692 * Returns the category context.
2693 * @return context_coursecat
2694 */
2695 public function get_context() {
2696 if ($this->id === 0) {
2697 // This is the special top level category object.
2698 return context_system::instance();
2699 } else {
2700 return context_coursecat::instance($this->id);
2701 }
2702 }
2703
2704 /**
2705 * Returns true if the user is able to manage this category.
2706 * @return bool
2707 */
2708 public function has_manage_capability() {
beff3806
MG
2709 if (!$this->is_uservisible()) {
2710 return false;
442f12f8 2711 }
beff3806 2712 return has_capability('moodle/category:manage', $this->get_context());
442f12f8
MG
2713 }
2714
2715 /**
2716 * Returns true if the user has the manage capability on the parent category.
2717 * @return bool
2718 */
2719 public function parent_has_manage_capability() {
beff3806 2720 return ($parent = $this->get_parent_coursecat()) && $parent->has_manage_capability();
442f12f8
MG
2721 }
2722
2723 /**
2724 * Returns true if the current user can create subcategories of this category.
2725 * @return bool
2726 */
2727 public function can_create_subcategory() {
2728 return $this->has_manage_capability();
2729 }
2730
2731 /**
2732 * Returns true if the user can resort this categories sub categories and courses.
2733 * Must have manage capability and be able to see all subcategories.
2734 * @return bool
2735 */
2736 public function can_resort_subcategories() {
2737 return $this->has_manage_capability() && !$this->get_not_visible_children_ids();
2738 }
2739
2740 /**
2741 * Returns true if the user can resort the courses within this category.
2742 * Must have manage capability and be able to see all courses.
2743 * @return bool
2744 */
2745 public function can_resort_courses() {
2746 return $this->has_manage_capability() && $this->coursecount == $this->get_courses_count();
2747 }
2748
2749 /**
2750 * Returns true of the user can change the sortorder of this category (resort in the parent category)
2751 * @return bool
2752 */
2753 public function can_change_sortorder() {
beff3806 2754 return ($parent = $this->get_parent_coursecat()) && $parent->can_resort_subcategories();
442f12f8
MG
2755 }
2756
2757 /**
2758 * Returns true if the current user can create a course within this category.
2759 * @return bool
2760 */
2761 public function can_create_course() {
beff3806 2762 return $this->is_uservisible() && has_capability('moodle/course:create', $this->get_context());
442f12f8
MG
2763 }
2764
2765 /**
2766 * Returns true if the current user can edit this categories settings.
2767 * @return bool
2768 */
2769 public function can_edit() {
2770 return $this->has_manage_capability();
2771 }
2772
2773 /**
2774 * Returns true if the current user can review role assignments for this category.
2775 * @return bool
2776 */
2777 public function can_review_roles() {
beff3806 2778 return $this->is_uservisible() && has_capability('moodle/role:assign', $this->get_context());
442f12f8
MG
2779 }
2780
2781 /**
2782 * Returns true if the current user can review permissions for this category.
2783 * @return bool
2784 */
2785 public function can_review_permissions() {
beff3806
MG
2786 return $this->is_uservisible() &&
2787 has_any_capability(array(
442f12f8
MG
2788 'moodle/role:assign',
2789 'moodle/role:safeoverride',
2790 'moodle/role:override',
2791 'moodle/role:assign'
2792 ), $this->get_context());
2793 }
2794
2795 /**
2796 * Returns true if the current user can review cohorts for this category.
2797 * @return bool
2798 */
2799 public function can_review_cohorts() {
beff3806
MG
2800 return $this->is_uservisible() &&
2801 has_any_capability(array('moodle/cohort:view', 'moodle/cohort:manage'), $this->get_context());
442f12f8
MG
2802 }
2803
2804 /**
2805 * Returns true if the current user can review filter settings for this category.
2806 * @return bool
2807 */
2808 public function can_review_filters() {
beff3806
MG
2809 return $this->is_uservisible() &&
2810 has_capability('moodle/filter:manage', $this->get_context()) &&
2811 count(filter_get_available_in_context($this->get_context())) > 0;
442f12f8
MG
2812 }
2813
2814 /**
2815 * Returns true if the current user is able to change the visbility of this category.
2816 * @return bool
2817 */
2818 public function can_change_visibility() {
2819 return $this->parent_has_manage_capability();
2820 }
2821
2822 /**
2823 * Returns true if the user can move courses out of this category.
2824 * @return bool
2825 */
2826 public function can_move_courses_out_of() {
2827 return $this->has_manage_capability();
2828 }
2829
2830 /**
2831 * Returns true if the user can move courses into this category.
2832 * @return bool
2833 */
2834 public function can_move_courses_into() {
2835 return $this->has_manage_capability();
2836 }
2837
2838 /**
2839 * Returns true if the user is able to restore a course into this category as a new course.
2840 * @return bool
2841 */
2842 public function can_restore_courses_into() {
beff3806 2843 return $this->is_uservisible() && has_capability('moodle/restore:restorecourse', $this->get_context());
442f12f8
MG
2844 }
2845
2846 /**
2847 * Resorts the sub categories of this category by the given field.
2848 *
2849 * @param string $field One of name, idnumber or descending values of each (appended desc)
2850 * @param bool $cleanup If true cleanup will be done, if false you will need to do it manually later.
2851 * @return bool True on success.
2852 * @throws coding_exception
2853 */
2854 public function resort_subcategories($field, $cleanup = true) {
2855 global $DB;
2856 $desc = false;
2857 if (substr($field, -4) === "desc") {
2858 $desc = true;
2859 $field = substr($field, 0, -4); // Remove "desc" from field name.
2860 }
2861 if ($field !== 'name' && $field !== 'idnumber') {
2862 throw new coding_exception('Invalid field requested');
2863 }
2864 $children = $this->get_children();
2865 core_collator::asort_objects_by_property($children, $field, core_collator::SORT_NATURAL);
2866 if (!empty($desc)) {
2867 $children = array_reverse($children);
2868 }
2869 $i = 1;
2870 foreach ($children as $cat) {
2871 $i++;
2872 $DB->set_field('course_categories', 'sortorder', $i, array('id' => $cat->id));
2873 $i += $cat->coursecount;
2874 }
2875 if ($cleanup) {
2876 self::resort_categories_cleanup();
2877 }
2878 return true;
2879 }
2880
2881 /**
2882 * Cleans things up after categories have been resorted.
2883 * @param bool $includecourses If set to true we know courses have been resorted as well.
2884 */
2885 public static function resort_categories_cleanup($includecourses = false) {
2886 // This should not be needed but we do it just to be safe.
2887 fix_course_sortorder();
2888 cache_helper::purge_by_event('changesincoursecat');
2889 if ($includecourses) {
2890 cache_helper::purge_by_event('changesincourse');
2891 }
2892 }
2893
2894 /**
2895 * Resort the courses within this category by the given field.
2896 *
2897 * @param string $field One of fullname, shortname, idnumber or descending values of each (appended desc)
2898 * @param bool $cleanup
2899 * @return bool True for success.
2900 * @throws coding_exception
2901 */
2902 public function resort_courses($field, $cleanup = true) {
2903 global $DB;
2904 $desc = false;
2905 if (substr($field, -4) === "desc") {
2906 $desc = true;
2907 $field = substr($field, 0, -4); // Remove "desc" from field name.
2908 }
2909 if ($field !== 'fullname' && $field !== 'shortname' && $field !== 'idnumber' && $field !== 'timecreated') {
2910 // This is ultra important as we use $field in an SQL statement below this.
2911 throw new coding_exception('Invalid field requested');
2912 }
2913 $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
2914 $sql = "SELECT c.id, c.sortorder, c.{$field}, $ctxfields
2915 FROM {course} c
2916 LEFT JOIN {context} ctx ON ctx.instanceid = c.id
2917 WHERE ctx.contextlevel = :ctxlevel AND
2918 c.category = :categoryid";
2919 $params = array(
2920 'ctxlevel' => CONTEXT_COURSE,
2921 'categoryid' => $this->id
2922 );
2923 $courses = $DB->get_records_sql($sql, $params);
2924 if (count($courses) > 0) {
2925 foreach ($courses as $courseid => $course) {
2926 context_helper::preload_from_record($course);
2927 if ($field === 'idnumber') {
2928 $course->sortby = $course->idnumber;
2929 } else {
2930 // It'll require formatting.
2931 $options = array(
2932 'context' => context_course::instance($course->id)
2933 );
2934 // We format the string first so that it appears as the user would see it.
2935 // This ensures the sorting makes sense to them. However it won't necessarily make
2936 // sense to everyone if things like multilang filters are enabled.
2937 // We then strip any tags as we don't want things such as image tags skewing the
2938 // sort results.
2939 $course->sortby = strip_tags(format_string($course->$field, true, $options));
2940 }
2941 // We set it back here rather than using references as there is a bug with using
2942 // references in a foreach before passing as an arg by reference.
2943 $courses[$courseid] = $course;
2944 }
2945 // Sort the courses.
2946 core_collator::asort_objects_by_property($courses, 'sortby', core_collator::SORT_NATURAL);
2947 if (!empty($desc)) {
2948 $courses = array_reverse($courses);
2949 }
2950 $i = 1;
2951 foreach ($courses as $course) {
2952 $DB->set_field('course', 'sortorder', $this->sortorder + $i, array('id' => $course->id));
2953 $i++;
2954 }
2955 if ($cleanup) {
2956 // This should not be needed but we do it just to be safe.
2957 fix_course_sortorder();
2958 cache_helper::purge_by_event('changesincourse');
2959 }
2960 }
2961 return true;
2962 }
2963
2964 /**
2965 * Changes the sort order of this categories parent shifting this category up or down one.
2966 *
2967 * @param bool $up If set to true the category is shifted up one spot, else its moved down.
2968 * @return bool True on success, false otherwise.
2969 */
2970 public function change_sortorder_by_one($up) {
2971 global $DB;
2972 $params = array($this->sortorder, $this->parent);
2973 if ($up) {
2974 $select = 'sortorder < ? AND parent = ?';
2975 $sort = 'sortorder DESC';
2976 } else {
2977 $select = 'sortorder > ? AND parent = ?';
2978 $sort = 'sortorder ASC';
2979 }
2980 fix_course_sortorder();
2981 $swapcategory = $DB->get_records_select('course_categories', $select, $params, $sort, '*', 0, 1);
2982 $swapcategory = reset($swapcategory);
2983 if ($swapcategory) {
2984 $DB->set_field('course_categories', 'sortorder', $swapcategory->sortorder, array('id' => $this->id));
2985 $DB->set_field('course_categories', 'sortorder', $this->sortorder, array('id' => $swapcategory->id));
2986 $this->sortorder = $swapcategory->sortorder;
2987
2988 $event = \core\event\course_category_updated::create(array(
2989 'objectid' => $this->id,
2990 'context' => $this->get_context()
2991 ));
2992 $event->set_legacy_logdata(array(SITEID, 'category', 'move', 'management.php?categoryid=' . $this->id,
2993 $this->id));
2994 $event->trigger();
2995
2996 // Finally reorder courses.
2997 fix_course_sortorder();
2998 cache_helper::purge_by_event('changesincoursecat');
2999 return true;
3000 }
3001 return false;
3002 }
3003
3004 /**
3005 * Returns the parent core_course_category object for this category.
3006 *
beff3806
MG
3007 * Only returns parent if it exists and is visible to the current user
3008 *
3009 * @return core_course_category|null
442f12f8
MG
3010 */
3011 public function get_parent_coursecat() {
beff3806
MG
3012 if (!$this->id) {
3013 return null;
3014 }
3015 return self::get($this->parent, IGNORE_MISSING);
442f12f8
MG
3016 }
3017
3018
3019 /**
3020 * Returns true if the user is able to request a new course be created.
3021 * @return bool
3022 */
3023 public function can_request_course() {
3e15abe5 3024 return course_request::can_request($this->get_context());
442f12f8
MG
3025 }
3026
3027 /**
3028 * Returns true if the user can approve course requests.
3029 * @return bool
3030 */
3031 public static function can_approve_course_requests() {
3032 global $CFG, $DB;
3033 if (empty($CFG->enablecourserequests)) {
3034 return false;
3035 }
3036 $context = context_system::instance();
3037 if (!has_capability('moodle/site:approvecourse', $context)) {
3038 return false;
3039 }
3040 if (!$DB->record_exists('course_request', array())) {
3041 return false;
3042 }
3043 return true;
3044 }
3045}