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