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