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