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