MDL-38147 fixes to phpdocs and avoid using deprecated context functions
[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 *
31 * @package core
32 * @subpackage course
33 * @copyright 2013 Marina Glancy
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36class coursecat implements renderable, cacheable_object, IteratorAggregate {
37 /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
38 protected static $coursecat0;
39
40 /** @var array list of all fields and their short name and default value for caching */
41 protected static $coursecatfields = array(
42 'id' => array('id', 0),
43 'name' => array('na', ''),
44 'idnumber' => array('in', null),
15d50fff
MG
45 'description' => null, // not cached
46 'descriptionformat' => null, // not cached
b33389d2
MG
47 'parent' => array('pa', 0),
48 'sortorder' => array('so', 0),
15d50fff 49 'coursecount' => null, // not cached
b33389d2 50 'visible' => array('vi', 1),
15d50fff 51 'visibleold' => null, // not cached
b33389d2
MG
52 'timemodified' => null, // not cached
53 'depth' => array('dh', 1),
54 'path' => array('ph', null),
15d50fff 55 'theme' => null, // not cached
b33389d2
MG
56 );
57
58 /** @var int */
59 protected $id;
60
61 /** @var string */
62 protected $name = '';
63
64 /** @var string */
65 protected $idnumber = null;
66
67 /** @var string */
15d50fff 68 protected $description = false;
b33389d2
MG
69
70 /** @var int */
15d50fff 71 protected $descriptionformat = false;
b33389d2
MG
72
73 /** @var int */
74 protected $parent = 0;
75
76 /** @var int */
77 protected $sortorder = 0;
78
79 /** @var int */
15d50fff 80 protected $coursecount = false;
b33389d2
MG
81
82 /** @var int */
83 protected $visible = 1;
84
85 /** @var int */
15d50fff 86 protected $visibleold = false;
b33389d2
MG
87
88 /** @var int */
15d50fff 89 protected $timemodified = false;
b33389d2
MG
90
91 /** @var int */
92 protected $depth = 0;
93
94 /** @var string */
95 protected $path = '';
96
97 /** @var string */
15d50fff 98 protected $theme = false;
b33389d2
MG
99
100 /** @var bool */
101 protected $fromcache;
102
103 // ====== magic methods =======
104
105 /**
106 * Magic setter method, we do not want anybody to modify properties from the outside
9c6cfc08 107 *
b33389d2
MG
108 * @param string $name
109 * @param mixed $value
110 */
111 public function __set($name, $value) {
112 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
113 }
114
115 /**
15d50fff 116 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
9c6cfc08 117 *
b33389d2
MG
118 * @param string $name
119 * @return mixed
120 */
121 public function __get($name) {
15d50fff 122 global $DB;
b33389d2 123 if (array_key_exists($name, self::$coursecatfields)) {
15d50fff
MG
124 if ($this->$name === false) {
125 // property was not retrieved from DB, retrieve all not retrieved fields
126 $notretrievedfields = array_diff(self::$coursecatfields, array_filter(self::$coursecatfields));
127 $record = $DB->get_record('course_categories', array('id' => $this->id),
128 join(',', array_keys($notretrievedfields)), MUST_EXIST);
129 foreach ($record as $key => $value) {
130 $this->$key = $value;
131 }
132 }
b33389d2
MG
133 return $this->$name;
134 }
135 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
136 return null;
137 }
138
139 /**
140 * Full support for isset on our magic read only properties.
9c6cfc08 141 *
b33389d2
MG
142 * @param string $name
143 * @return bool
144 */
145 public function __isset($name) {
146 if (array_key_exists($name, self::$coursecatfields)) {
147 return isset($this->$name);
148 }
149 return false;
150 }
151
152 /**
9c6cfc08
MG
153 * All properties are read only, sorry.
154 *
b33389d2
MG
155 * @param string $name
156 */
157 public function __unset($name) {
158 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
159 }
160
b33389d2
MG
161 /**
162 * Create an iterator because magic vars can't be seen by 'foreach'.
9c6cfc08
MG
163 *
164 * implementing method from interface IteratorAggregate
165 *
166 * @return ArrayIterator
b33389d2
MG
167 */
168 public function getIterator() {
169 $ret = array();
170 foreach (self::$coursecatfields as $property => $unused) {
15d50fff
MG
171 if ($this->$property !== false) {
172 $ret[$property] = $this->$property;
173 }
b33389d2
MG
174 }
175 return new ArrayIterator($ret);
176 }
177
b33389d2
MG
178 /**
179 * Constructor
180 *
181 * Constructor is protected, use coursecat::get($id) to retrieve category
182 *
9c6cfc08
MG
183 * @param stdClass $record record from DB (may not contain all fields)
184 * @param bool $fromcache whether it is being restored from cache
b33389d2
MG
185 */
186 protected function __construct(stdClass $record, $fromcache = false) {
9c6cfc08 187 context_helper::preload_from_record($record);
b33389d2
MG
188 foreach ($record as $key => $val) {
189 if (array_key_exists($key, self::$coursecatfields)) {
190 $this->$key = $val;
191 }
192 }
193 $this->fromcache = $fromcache;
194 }
195
196 /**
197 * Returns coursecat object for requested category
198 *
199 * If category is not visible to user it is treated as non existing
15d50fff 200 * unless $alwaysreturnhidden is set to true
b33389d2
MG
201 *
202 * If id is 0, the pseudo object for root category is returned (convenient
203 * for calling other functions such as get_children())
204 *
205 * @param int $id category id
206 * @param int $strictness whether to throw an exception (MUST_EXIST) or
207 * return null (IGNORE_MISSING) in case the category is not found or
208 * not visible to current user
15d50fff 209 * @param bool $alwaysreturnhidden set to true if you want an object to be
b33389d2
MG
210 * returned even if this category is not visible to the current user
211 * (category is hidden and user does not have
212 * 'moodle/category:viewhiddencategories' capability). Use with care!
15d50fff 213 * @return null|coursecat
b33389d2 214 */
15d50fff 215 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
b33389d2
MG
216 if (!$id) {
217 if (!isset(self::$coursecat0)) {
15d50fff
MG
218 $record = new stdClass();
219 $record->id = 0;
220 $record->visible = 1;
221 $record->depth = 0;
222 $record->path = '';
223 self::$coursecat0 = new coursecat($record);
b33389d2
MG
224 }
225 return self::$coursecat0;
226 }
eabbfa82
MG
227 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
228 $coursecat = $coursecatrecordcache->get($id);
15d50fff 229 if ($coursecat === false) {
eabbfa82
MG
230 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
231 $record = reset($records);
232 $coursecat = new coursecat($record);
233 // Store in cache
234 $coursecatrecordcache->set($id, $coursecat);
b33389d2
MG
235 }
236 }
15d50fff 237 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
b33389d2
MG
238 return $coursecat;
239 } else {
240 if ($strictness == MUST_EXIST) {
241 throw new moodle_exception('unknowcategory');
242 }
243 }
244 return null;
245 }
246
247 /**
248 * Returns the first found category
249 *
250 * Note that if there are no categories visible to the current user on the first level,
251 * the invisible category may be returned
252 *
253 * @return coursecat
254 */
255 public static function get_default() {
256 if ($visiblechildren = self::get(0)->get_children()) {
257 $defcategory = reset($visiblechildren);
258 } else {
eabbfa82
MG
259 $toplevelcategories = self::get_tree(0);
260 $defcategoryid = $toplevelcategories[0];
b33389d2
MG
261 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
262 }
263 return $defcategory;
264 }
265
266 /**
267 * Restores the object after it has been externally modified in DB for example
268 * during {@link fix_course_sortorder()}
269 */
270 protected function restore() {
271 // update all fields in the current object
272 $newrecord = self::get($this->id, MUST_EXIST, true);
273 foreach (self::$coursecatfields as $key => $unused) {
274 $this->$key = $newrecord->$key;
275 }
276 }
277
278 /**
279 * Creates a new category either from form data or from raw data
280 *
281 * Please note that this function does not verify access control.
282 *
283 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
284 *
285 * Category visibility is inherited from parent unless $data->visible = 0 is specified
286 *
287 * @param array|stdClass $data
288 * @param array $editoroptions if specified, the data is considered to be
289 * form data and file_postupdate_standard_editor() is being called to
290 * process images in description.
291 * @return coursecat
292 * @throws moodle_exception
293 */
294 public static function create($data, $editoroptions = null) {
295 global $DB, $CFG;
296 $data = (object)$data;
297 $newcategory = new stdClass();
298
299 $newcategory->descriptionformat = FORMAT_MOODLE;
300 $newcategory->description = '';
301 // copy all description* fields regardless of whether this is form data or direct field update
302 foreach ($data as $key => $value) {
303 if (preg_match("/^description/", $key)) {
304 $newcategory->$key = $value;
305 }
306 }
307
308 if (empty($data->name)) {
309 throw new moodle_exception('categorynamerequired');
310 }
311 if (textlib::strlen($data->name) > 255) {
312 throw new moodle_exception('categorytoolong');
313 }
314 $newcategory->name = $data->name;
315
316 // validate and set idnumber
317 if (!empty($data->idnumber)) {
b33389d2
MG
318 if (textlib::strlen($data->idnumber) > 100) {
319 throw new moodle_exception('idnumbertoolong');
320 }
9c6cfc08
MG
321 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
322 throw new moodle_exception('categoryidnumbertaken');
323 }
b33389d2
MG
324 }
325 if (isset($data->idnumber)) {
326 $newcategory->idnumber = $data->idnumber;
327 }
328
329 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
330 $newcategory->theme = $data->theme;
331 }
332
333 if (empty($data->parent)) {
334 $parent = self::get(0);
335 } else {
336 $parent = self::get($data->parent, MUST_EXIST, true);
337 }
338 $newcategory->parent = $parent->id;
339 $newcategory->depth = $parent->depth + 1;
340
341 // By default category is visible, unless visible = 0 is specified or parent category is hidden
342 if (isset($data->visible) && !$data->visible) {
343 // create a hidden category
344 $newcategory->visible = $newcategory->visibleold = 0;
345 } else {
346 // create a category that inherits visibility from parent
347 $newcategory->visible = $parent->visible;
348 // in case parent is hidden, when it changes visibility this new subcategory will automatically become visible too
349 $newcategory->visibleold = 1;
350 }
351
352 $newcategory->sortorder = 0;
353 $newcategory->timemodified = time();
354
355 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
356
357 // update path (only possible after we know the category id
358 $path = $parent->path . '/' . $newcategory->id;
359 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
360
361 // We should mark the context as dirty
362 context_coursecat::instance($newcategory->id)->mark_dirty();
363
364 fix_course_sortorder();
365
366 // if this is data from form results, save embedded files and update description
367 $categorycontext = context_coursecat::instance($newcategory->id);
368 if ($editoroptions) {
369 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
370
371 // update only fields description and descriptionformat
9c6cfc08
MG
372 $updatedata = new stdClass();
373 $updatedata->id = $newcategory->id;
374 $updatedata->description = $newcategory->description;
375 $updatedata->descriptionformat = $newcategory->descriptionformat;
b33389d2 376 $DB->update_record('course_categories', $updatedata);
b33389d2
MG
377 }
378
379 add_to_log(SITEID, "category", 'add', "editcategory.php?id=$newcategory->id", $newcategory->id);
eabbfa82 380 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
381
382 return self::get($newcategory->id, MUST_EXIST, true);
383 }
384
385 /**
386 * Updates the record with either form data or raw data
387 *
388 * Please note that this function does not verify access control.
389 *
15d50fff
MG
390 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
391 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
b33389d2
MG
392 * Visibility is changed first and then parent is changed. This means that
393 * if parent category is hidden, the current category will become hidden
394 * too and it may overwrite whatever was set in field 'visible'.
395 *
396 * Note that fields 'path' and 'depth' can not be updated manually
397 * Also coursecat::update() can not directly update the field 'sortoder'
398 *
399 * @param array|stdClass $data
400 * @param array $editoroptions if specified, the data is considered to be
401 * form data and file_postupdate_standard_editor() is being called to
402 * process images in description.
403 * @throws moodle_exception
404 */
405 public function update($data, $editoroptions = null) {
406 global $DB, $CFG;
407 if (!$this->id) {
408 // there is no actual DB record associated with root category
409 return;
410 }
411
412 $data = (object)$data;
413 $newcategory = new stdClass();
414 $newcategory->id = $this->id;
415
416 // copy all description* fields regardless of whether this is form data or direct field update
417 foreach ($data as $key => $value) {
418 if (preg_match("/^description/", $key)) {
419 $newcategory->$key = $value;
420 }
421 }
422
423 if (isset($data->name) && empty($data->name)) {
424 throw new moodle_exception('categorynamerequired');
425 }
426
427 if (!empty($data->name) && $data->name !== $this->name) {
428 if (textlib::strlen($data->name) > 255) {
429 throw new moodle_exception('categorytoolong');
430 }
431 $newcategory->name = $data->name;
432 }
433
434 if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
435 if (textlib::strlen($data->idnumber) > 100) {
436 throw new moodle_exception('idnumbertoolong');
437 }
9c6cfc08 438 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
b33389d2
MG
439 throw new moodle_exception('categoryidnumbertaken');
440 }
441 $newcategory->idnumber = $data->idnumber;
442 }
443
444 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
445 $newcategory->theme = $data->theme;
446 }
447
448 $changes = false;
449 if (isset($data->visible)) {
450 if ($data->visible) {
15d50fff 451 $changes = $this->show_raw();
b33389d2 452 } else {
15d50fff 453 $changes = $this->hide_raw(0);
b33389d2
MG
454 }
455 }
456
457 if (isset($data->parent) && $data->parent != $this->parent) {
458 if ($changes) {
eabbfa82 459 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
460 }
461 $parentcat = self::get($data->parent, MUST_EXIST, true);
15d50fff 462 $this->change_parent_raw($parentcat);
b33389d2
MG
463 fix_course_sortorder();
464 }
465
466 $newcategory->timemodified = time();
467
468 if ($editoroptions) {
469 $categorycontext = context_coursecat::instance($this->id);
470 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
471 }
472 $DB->update_record('course_categories', $newcategory);
473 add_to_log(SITEID, "category", 'update', "editcategory.php?id=$this->id", $this->id);
474 fix_course_sortorder();
eabbfa82
MG
475 // purge cache even if fix_course_sortorder() did not do it
476 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
477
478 // update all fields in the current object
479 $this->restore();
480 }
481
482 /**
483 * Checks if this course category is visible to current user
484 *
485 * Please note that methods coursecat::get (without 3rd argumet),
486 * coursecat::get_children(), etc. return only visible categories so it is
487 * usually not needed to call this function outside of this class
488 *
489 * @return bool
490 */
491 public function is_uservisible() {
492 return !$this->id || $this->visible ||
493 has_capability('moodle/category:viewhiddencategories',
494 context_coursecat::instance($this->id));
495 }
496
497 /**
498 * Returns all categories visible to the current user
499 *
500 * This is a generic function that returns an array of
501 * (category id => coursecat object) sorted by sortorder
502 *
503 * @see coursecat::get_children()
504 * @see coursecat::get_all_parents()
505 *
506 * @return cacheable_object_array array of coursecat objects
507 */
508 public static function get_all_visible() {
509 global $USER;
510 $coursecatcache = cache::make('core', 'coursecat');
511 $ids = $coursecatcache->get('user'. $USER->id);
512 if ($ids === false) {
513 $all = self::get_all_ids();
514 $parentvisible = $all[0];
515 $rv = array();
516 foreach ($all as $id => $children) {
517 if ($id && in_array($id, $parentvisible) &&
518 ($coursecat = self::get($id, IGNORE_MISSING)) &&
519 (!$coursecat->parent || isset($rv[$coursecat->parent]))) {
520 $rv[$id] = $coursecat;
521 $parentvisible += $children;
522 }
523 }
524 $coursecatcache->set('user'. $USER->id, array_keys($rv));
525 } else {
526 $rv = array();
527 foreach ($ids as $id) {
528 if ($coursecat = self::get($id, IGNORE_MISSING)) {
529 $rv[$id] = $coursecat;
530 }
531 }
532 }
533 return $rv;
534 }
535
536 /**
eabbfa82 537 * Returns the entry from categories tree and makes sure the application-level tree cache is built
b33389d2 538 *
eabbfa82 539 * The following keys can be requested:
b33389d2 540 *
eabbfa82
MG
541 * 'countall' - total number of categories in the system (always present)
542 * 0 - array of ids of top-level categories (always present)
543 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
544 * $id (int) - array of ids of categories that are direct children of category with id $id. If
545 * category with id $id does not exist returns false. If category has no children returns empty array
546 * $id.'i' - array of ids of children categories that have visible=0
547 *
548 * @param int|string $id
549 * @return mixed
b33389d2 550 */
eabbfa82 551 protected static function get_tree($id) {
b33389d2 552 global $DB;
eabbfa82
MG
553 $coursecattreecache = cache::make('core', 'coursecattree');
554 $rv = $coursecattreecache->get($id);
555 if ($rv !== false) {
556 return $rv;
557 }
558 // We did not find the entry in cache but it also can mean that tree is not built.
559 // The keys 0 and 'countall' must always be present if tree is built.
560 if ($id !== 0 && $id !== 'countall' && $coursecattreecache->has('countall')) {
561 // Tree was built, it means the non-existing $id was requested.
562 return false;
563 }
564 // Re-build the tree.
565 $sql = "SELECT cc.id, cc.parent, cc.visible
566 FROM {course_categories} cc
567 ORDER BY cc.sortorder";
568 $rs = $DB->get_recordset_sql($sql, array());
569 $all = array(0 => array(), '0i' => array());
570 $count = 0;
571 foreach ($rs as $record) {
572 $all[$record->id] = array();
573 $all[$record->id. 'i'] = array();
574 if (array_key_exists($record->parent, $all)) {
b33389d2 575 $all[$record->parent][] = $record->id;
eabbfa82
MG
576 if (!$record->visible) {
577 $all[$record->parent. 'i'][] = $record->id;
578 }
579 } else {
580 // parent not found. This is data consistency error but next fix_course_sortorder() should fix it
581 $all[0][] = $record->id;
b33389d2 582 }
eabbfa82
MG
583 $count++;
584 }
585 $rs->close();
586 if (!$count) {
587 // No categories found.
588 // This may happen after upgrade from very old moodle version. In new versions the default category is created on install.
589 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
590 set_config('defaultrequestcategory', $defcoursecat->id);
591 $all[0] = array($defcoursecat->id);
592 $all[$defcoursecat->id] = array();
593 $count++;
b33389d2 594 }
eabbfa82
MG
595 foreach ($all as $key => $children) {
596 $coursecattreecache->set($key, $children);
597 }
598 $coursecattreecache->set('countall', $count);
599 if (array_key_exists($id, $all)) {
600 return $all[$id];
601 }
602 return false;
b33389d2
MG
603 }
604
b33389d2
MG
605 /**
606 * Returns number of ALL categories in the system regardless if
607 * they are visible to current user or not
608 *
609 * @return int
610 */
15d50fff 611 public static function count_all() {
eabbfa82
MG
612 return self::get_tree('countall');
613 }
614
615 /**
616 * Retrieves number of records from course_categories table
617 *
618 * Only cached fields are retrieved. Records are ready for preloading context
619 *
620 * @param string $whereclause
621 * @param array $params
622 * @return array array of stdClass objects
623 */
624 protected static function get_records($whereclause, $params) {
625 global $DB;
626 // Retrieve from DB only the fields that need to be stored in cache
627 $fields = array_filter(array_keys(self::$coursecatfields), function ($element)
628 { return (self::$coursecatfields[$element] !== null); } );
629 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
630 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
631 FROM {course_categories} cc
632 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
633 WHERE ". $whereclause." ORDER BY cc.sortorder";
634 return $DB->get_records_sql($sql,
635 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
636 }
637
638 /**
639 * Returns array of ids of children categories that current user can not see
640 *
641 * This data is cached in user session cache
642 *
643 * @return array
644 */
645 protected function get_not_visible_children_ids() {
646 global $DB;
647 $coursecatcache = cache::make('core', 'coursecat');
648 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
649 // we never checked visible children before
650 $hidden = self::get_tree($this->id.'i');
651 $invisibleids = array();
652 if ($hidden) {
653 // preload categories contexts
654 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
655 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
656 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
657 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
658 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
659 foreach ($contexts as $record) {
660 context_helper::preload_from_record($record);
661 }
662 // check that user has 'viewhiddencategories' capability for each hidden category
663 foreach ($hidden as $id) {
664 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
665 $invisibleids[] = $id;
666 }
667 }
668 }
669 $coursecatcache->set('ic'. $this->id, $invisibleids);
670 }
671 return $invisibleids;
672 }
673
674 /**
675 * Compares two records. For use in uasort()
676 *
677 * @param stdClass $a
678 * @param stdClass $b
679 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
680 * @return int
681 */
682 protected static function compare_records($a, $b, $sortfields) {
683 foreach ($sortfields as $field => $mult) {
684 if ($field === 'name' || $field === 'idnumber' || $field === 'path') {
685 // string fields
686 if ($cmp = strcmp($a->$field, $b->$field)) {
687 // TODO textlib?
688 return $mult * $cmp;
689 }
690 } else {
691 // int fields
692 if ($a->$field > $b->$field) {
693 return $mult;
694 }
695 if ($a->$field < $b->$field) {
696 return -$mult;
697 }
698 }
699 }
700 return 0;
b33389d2
MG
701 }
702
703 /**
704 * Returns array of children categories visible to the current user
705 *
eabbfa82
MG
706 * @param array $options options for retrieving children
707 * - sort - list of fields to sort. Example
708 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
709 * will sort by idnumber asc, name asc and id desc.
710 * Default: array('sortorder' => 1)
711 * Only cached fields may be used for sorting!
712 * - offset
713 * - limit - maximum number of children to return, 0 or null for no limit
b33389d2
MG
714 * @return array of coursecat objects indexed by category id
715 */
eabbfa82
MG
716 public function get_children($options = array()) {
717 global $DB;
718 $coursecatcache = cache::make('core', 'coursecat');
719
720 // get default values for options
721 if (!empty($options['sort']) && is_array($options['sort'])) {
722 $sortfields = $options['sort'];
723 } else {
724 $sortfields = array('sortorder' => 1);
725 }
726 $limit = null;
727 if (!empty($options['limit']) && (int)$options['limit']) {
728 $limit = (int)$options['limit'];
729 }
730 $offset = 0;
731 if (!empty($options['offset']) && (int)$options['offset']) {
732 $offset = (int)$options['offset'];
733 }
734
735 // first retrieve list of user-visible and sorted children ids from cache
736 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
737 if ($sortedids === false) {
738 $sortfieldskeys = array_keys($sortfields);
739 if ($sortfieldskeys[0] === 'sortorder') {
740 // no DB requests required to build the list of ids sorted by sortorder.
741 // We can easily ignore other sort fields because sortorder is always different
742 $sortedids = self::get_tree($this->id);
743 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
744 $sortedids = array_diff($sortedids, $invisibleids);
745 if ($sortfields['sortorder'] == -1) {
746 $sortedids = array_reverse($sortedids, true);
747 }
b33389d2 748 }
eabbfa82
MG
749 } else {
750 // we need to retrieve and sort all children. Good thing that it is done only on first request
751 if ($invisibleids = $this->get_not_visible_children_ids()) {
752 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
753 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
754 array('parent' => $this->id) + $params);
755 } else {
756 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
757 }
758 uasort($records, function ($a, $b) use ($sortfields) { return self::compare_records($a, $b, $sortfields); });
759 $sortedids = array_keys($records);
760 }
761 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
762 }
763
764 if (empty($sortedids)) {
765 return array();
766 }
767
768 // now retrieive and return categories
769 if ($offset || $limit) {
770 $sortedids = array_slice($sortedids, $offset, $limit);
771 }
772 if (isset($records)) {
773 // easy, we have already retrieved records
774 if ($offset || $limit) {
775 $records = array_slice($records, $offset, $limit, true);
776 }
777 } else {
778 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
779 $records = self::get_records('cc.id '. $sql,
780 array('parent' => $this->id) + $params);
781 }
782
783 $rv = array();
784 foreach ($sortedids as $id) {
785 if (isset($records[$id])) {
786 $rv[$id] = new coursecat($records[$id]);
b33389d2
MG
787 }
788 }
789 return $rv;
790 }
791
eabbfa82
MG
792 /**
793 * Returns number of subcategories visible to the current user
794 *
795 * @return int
796 */
797 public function get_children_count() {
798 $sortedids = self::get_tree($this->id);
799 $invisibleids = $this->get_not_visible_children_ids();
800 return count($sortedids) - count($invisibleids);
801 }
802
b33389d2
MG
803 /**
804 * Returns true if the category has ANY children, including those not visible to the user
805 *
806 * @return boolean
807 */
808 public function has_children() {
eabbfa82
MG
809 $allchildren = self::get_tree($this->id);
810 return !empty($allchildren);
b33389d2
MG
811 }
812
813 /**
814 * Returns true if the category has courses in it (count does not include courses
815 * in child categories)
816 *
817 * @return bool
818 */
819 public function has_courses() {
820 global $DB;
821 return $DB->record_exists_sql("select 1 from {course} where category = ?",
822 array($this->id));
823 }
824
825 /**
826 * Returns true if user can delete current category and all its contents
827 *
828 * To be able to delete course category the user must have permission
829 * 'moodle/category:manage' in ALL child course categories AND
830 * be able to delete all courses
831 *
832 * @return bool
833 */
834 public function can_delete_full() {
835 global $DB;
836 if (!$this->id) {
837 // fool-proof
838 return false;
839 }
840
841 $context = context_coursecat::instance($this->id);
842 if (!$this->is_uservisible() ||
843 !has_capability('moodle/category:manage', $context)) {
844 return false;
845 }
846
15d50fff
MG
847 // Check all child categories (not only direct children)
848 $sql = context_helper::get_preload_record_columns_sql('ctx');
849 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
850 ' FROM {context} ctx '.
851 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
852 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
853 array($context->path. '/%', CONTEXT_COURSECAT));
854 foreach ($childcategories as $childcat) {
855 context_helper::preload_from_record($childcat);
856 $childcontext = context_coursecat::instance($childcat->id);
857 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
858 !has_capability('moodle/category:manage', $childcontext)) {
859 return false;
b33389d2
MG
860 }
861 }
862
863 // Check courses
15d50fff
MG
864 $sql = context_helper::get_preload_record_columns_sql('ctx');
865 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
866 $sql. ' FROM {context} ctx '.
867 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
b33389d2
MG
868 array('pathmask' => $context->path. '/%',
869 'courselevel' => CONTEXT_COURSE));
15d50fff
MG
870 foreach ($coursescontexts as $ctxrecord) {
871 context_helper::preload_from_record($ctxrecord);
872 if (!can_delete_course($ctxrecord->courseid)) {
b33389d2
MG
873 return false;
874 }
875 }
876
877 return true;
878 }
879
880 /**
881 * Recursively delete category including all subcategories and courses
882 *
883 * Function {@link coursecat::can_delete_full()} MUST be called prior
884 * to calling this function because there is no capability check
885 * inside this function
886 *
887 * @param boolean $showfeedback display some notices
888 * @return array return deleted courses
889 */
15d50fff 890 public function delete_full($showfeedback = true) {
b33389d2
MG
891 global $CFG, $DB;
892 require_once($CFG->libdir.'/gradelib.php');
893 require_once($CFG->libdir.'/questionlib.php');
894 require_once($CFG->dirroot.'/cohort/lib.php');
895
896 $deletedcourses = array();
897
898 // Get children. Note, we don't want to use cache here because
899 // it would be rebuilt too often
900 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
901 foreach ($children as $record) {
902 $coursecat = new coursecat($record);
903 $deletedcourses += $coursecat->delete_full($showfeedback);
904 }
905
906 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
907 foreach ($courses as $course) {
908 if (!delete_course($course, false)) {
909 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
910 }
911 $deletedcourses[] = $course;
912 }
913 }
914
915 // move or delete cohorts in this context
916 cohort_delete_category($this);
917
918 // now delete anything that may depend on course category context
919 grade_course_category_delete($this->id, 0, $showfeedback);
920 if (!question_delete_course_category($this, 0, $showfeedback)) {
921 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
922 }
923
924 // finally delete the category and it's context
925 $DB->delete_records('course_categories', array('id' => $this->id));
926 delete_context(CONTEXT_COURSECAT, $this->id);
927 add_to_log(SITEID, "category", "delete", "index.php", "$this->name (ID $this->id)");
928
eabbfa82 929 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
930
931 events_trigger('course_category_deleted', $this);
932
933 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
934 if ($this->id == $CFG->defaultrequestcategory) {
935 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
936 }
937 return $deletedcourses;
938 }
939
940 /**
941 * Checks if user can delete this category and move content (courses, subcategories and questions)
942 * to another category. If yes returns the array of possible target categories names
943 *
944 * If user can not manage this category or it is completely empty - empty array will be returned
945 *
946 * @return array
947 */
948 public function move_content_targets_list() {
949 global $CFG;
950 require_once($CFG->libdir . '/questionlib.php');
951 $context = context_coursecat::instance($this->id);
952 if (!$this->is_uservisible() ||
953 !has_capability('moodle/category:manage', $context)) {
954 // User is not able to manage current category, he is not able to delete it.
955 // No possible target categories.
956 return array();
957 }
958
959 $testcaps = array();
960 // If this category has courses in it, user must have 'course:create' capability in target category.
961 if ($this->has_courses()) {
962 $testcaps[] = 'moodle/course:create';
963 }
964 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
965 if ($this->has_children() || question_context_has_any_questions($context)) {
966 $testcaps[] = 'moodle/category:manage';
967 }
968 if (!empty($testcaps)) {
969 // return list of categories excluding this one and it's children
970 return self::make_categories_list($testcaps, $this->id);
971 }
972
973 // Category is completely empty, no need in target for contents.
974 return array();
975 }
976
977 /**
978 * Checks if user has capability to move all category content to the new parent before
979 * removing this category
980 *
981 * @param int $newcatid
982 * @return bool
983 */
984 public function can_move_content_to($newcatid) {
985 global $CFG;
986 require_once($CFG->libdir . '/questionlib.php');
987 $context = context_coursecat::instance($this->id);
988 if (!$this->is_uservisible() ||
989 !has_capability('moodle/category:manage', $context)) {
990 return false;
991 }
992 $testcaps = array();
993 // If this category has courses in it, user must have 'course:create' capability in target category.
994 if ($this->has_courses()) {
995 $testcaps[] = 'moodle/course:create';
996 }
997 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
998 if ($this->has_children() || question_context_has_any_questions($context)) {
999 $testcaps[] = 'moodle/category:manage';
1000 }
1001 if (!empty($testcaps)) {
1002 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1003 }
1004
1005 // there is no content but still return true
1006 return true;
1007 }
1008
1009 /**
1010 * Deletes a category and moves all content (children, courses and questions) to the new parent
1011 *
1012 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1013 * must be called prior
1014 *
1015 * @param int $newparentid
1016 * @param bool $showfeedback
1017 * @return bool
1018 */
1019 public function delete_move($newparentid, $showfeedback = false) {
1020 global $CFG, $DB, $OUTPUT;
1021 require_once($CFG->libdir.'/gradelib.php');
1022 require_once($CFG->libdir.'/questionlib.php');
1023 require_once($CFG->dirroot.'/cohort/lib.php');
1024
1025 // get all objects and lists because later the caches will be reset so
1026 // we don't need to make extra queries
1027 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1028 $catname = $this->get_formatted_name();
1029 $children = $this->get_children();
1030 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', array('category' => $this->id));
1031 $context = context_coursecat::instance($this->id);
1032
1033 if ($children) {
1034 foreach ($children as $childcat) {
15d50fff 1035 $childcat->change_parent_raw($newparentcat);
b33389d2
MG
1036 // Log action.
1037 add_to_log(SITEID, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id);
1038 }
1039 fix_course_sortorder();
1040 }
1041
1042 if ($coursesids) {
1043 if (!move_courses($coursesids, $newparentid)) {
1044 if ($showfeedback) {
1045 echo $OUTPUT->notification("Error moving courses");
1046 }
1047 return false;
1048 }
1049 if ($showfeedback) {
1050 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1051 }
1052 }
1053
1054 // move or delete cohorts in this context
1055 cohort_delete_category($this);
1056
1057 // now delete anything that may depend on course category context
1058 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1059 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1060 if ($showfeedback) {
1061 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1062 }
1063 return false;
1064 }
1065
1066 // finally delete the category and it's context
1067 $DB->delete_records('course_categories', array('id' => $this->id));
1068 $context->delete();
1069 add_to_log(SITEID, "category", "delete", "index.php", "$this->name (ID $this->id)");
1070
1071 events_trigger('course_category_deleted', $this);
1072
eabbfa82 1073 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1074
1075 if ($showfeedback) {
1076 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1077 }
1078
1079 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1080 if ($this->id == $CFG->defaultrequestcategory) {
1081 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1082 }
1083 return true;
1084 }
1085
1086 /**
1087 * Checks if user can move current category to the new parent
1088 *
1089 * This checks if new parent category exists, user has manage cap there
1090 * and new parent is not a child of this category
1091 *
1092 * @param int|stdClass|coursecat $newparentcat
1093 * @return bool
1094 */
1095 public function can_change_parent($newparentcat) {
1096 if (!has_capability('moodle/category:manage', context_coursecat::instance($this->id))) {
1097 return false;
1098 }
1099 if (is_object($newparentcat)) {
1100 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1101 } else {
1102 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1103 }
1104 if (!$newparentcat) {
1105 return false;
1106 }
15d50fff 1107 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
b33389d2
MG
1108 // can not move to itself or it's own child
1109 return false;
1110 }
1111 return has_capability('moodle/category:manage', get_category_or_system_context($newparentcat->id));
1112 }
1113
1114 /**
1115 * Moves the category under another parent category. All associated contexts are moved as well
1116 *
1117 * This is protected function, use change_parent() or update() from outside of this class
1118 *
1119 * @see coursecat::change_parent()
1120 * @see coursecat::update()
1121 *
1122 * @param coursecat $newparentcat
1123 */
15d50fff 1124 protected function change_parent_raw(coursecat $newparentcat) {
b33389d2
MG
1125 global $DB;
1126
1127 $context = context_coursecat::instance($this->id);
1128
1129 $hidecat = false;
1130 if (empty($newparentcat->id)) {
1131 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1132 $newparent = context_system::instance();
1133 } else {
15d50fff 1134 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
b33389d2
MG
1135 // can not move to itself or it's own child
1136 throw new moodle_exception('cannotmovecategory');
1137 }
1138 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1139 $newparent = context_coursecat::instance($newparentcat->id);
1140
1141 if (!$newparentcat->visible and $this->visible) {
1142 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
1143 $hidecat = true;
1144 }
1145 }
1146 $this->parent = $newparentcat->id;
1147
9c6cfc08 1148 $context->update_moved($newparent);
b33389d2
MG
1149
1150 // now make it last in new category
1151 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1152
1153 if ($hidecat) {
1154 fix_course_sortorder();
1155 $this->restore();
1156 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must become visible again.
15d50fff 1157 $this->hide_raw(1);
b33389d2
MG
1158 }
1159 }
1160
1161 /**
1162 * Efficiently moves a category - NOTE that this can have
1163 * a huge impact access-control-wise...
1164 *
1165 * Note that this function does not check capabilities.
1166 *
1167 * Example of usage:
1168 * $coursecat = coursecat::get($categoryid);
1169 * if ($coursecat->can_change_parent($newparentcatid)) {
1170 * $coursecat->change_parent($newparentcatid);
1171 * }
1172 *
1173 * This function does not update field course_categories.timemodified
1174 * If you want to update timemodified, use
1175 * $coursecat->update(array('parent' => $newparentcat));
1176 *
1177 * @param int|stdClass|coursecat $newparentcat
1178 */
1179 public function change_parent($newparentcat) {
1180 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1181 if (is_object($newparentcat)) {
1182 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1183 } else {
1184 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1185 }
1186 if ($newparentcat->id != $this->parent) {
15d50fff 1187 $this->change_parent_raw($newparentcat);
b33389d2 1188 fix_course_sortorder();
eabbfa82 1189 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1190 $this->restore();
1191 add_to_log(SITEID, "category", "move", "editcategory.php?id=$this->id", $this->id);
1192 }
1193 }
1194
1195 /**
1196 * Hide course category and child course and subcategories
1197 *
1198 * If this category has changed the parent and is moved under hidden
1199 * category we will want to store it's current visibility state in
1200 * the field 'visibleold'. If admin clicked 'hide' for this particular
1201 * category, the field 'visibleold' should become 0.
1202 *
1203 * All subcategories and courses will have their current visibility in the field visibleold
1204 *
1205 * This is protected function, use hide() or update() from outside of this class
1206 *
1207 * @see coursecat::hide()
1208 * @see coursecat::update()
1209 *
1210 * @param int $visibleold value to set in field $visibleold for this category
1211 * @return bool whether changes have been made and caches need to be purged afterwards
1212 */
15d50fff 1213 protected function hide_raw($visibleold = 0) {
b33389d2
MG
1214 global $DB;
1215 $changes = false;
1216
15d50fff
MG
1217 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing
1218 if ($this->id && $this->__get('visibleold') != $visibleold) {
b33389d2
MG
1219 $this->visibleold = $visibleold;
1220 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1221 $changes = true;
1222 }
1223 if (!$this->visible || !$this->id) {
1224 // already hidden or can not be hidden
1225 return $changes;
1226 }
1227
1228 $this->visible = 0;
1229 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1230 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($this->id)); // store visible flag so that we can return to it if we immediately unhide
1231 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1232 // get all child categories and hide too
1233 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1234 foreach ($subcats as $cat) {
1235 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1236 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1237 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1238 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1239 }
1240 }
1241 return true;
1242 }
1243
1244 /**
1245 * Hide course category and child course and subcategories
1246 *
1247 * Note that there is no capability check inside this function
1248 *
1249 * This function does not update field course_categories.timemodified
1250 * If you want to update timemodified, use
1251 * $coursecat->update(array('visible' => 0));
1252 */
1253 public function hide() {
15d50fff 1254 if ($this->hide_raw(0)) {
eabbfa82 1255 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1256 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$this->id", $this->id);
1257 }
1258 }
1259
1260 /**
1261 * Show course category and restores visibility for child course and subcategories
1262 *
1263 * Note that there is no capability check inside this function
1264 *
1265 * This is protected function, use show() or update() from outside of this class
1266 *
1267 * @see coursecat::show()
1268 * @see coursecat::update()
1269 *
1270 * @return bool whether changes have been made and caches need to be purged afterwards
1271 */
15d50fff 1272 protected function show_raw() {
b33389d2
MG
1273 global $DB;
1274
1275 if ($this->visible) {
1276 // already visible
1277 return false;
1278 }
1279
1280 $this->visible = 1;
1281 $this->visibleold = 1;
1282 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1283 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1284 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
1285 // get all child categories and unhide too
1286 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1287 foreach ($subcats as $cat) {
1288 if ($cat->visibleold) {
1289 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
1290 }
1291 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
1292 }
1293 }
1294 return true;
1295 }
1296
1297 /**
1298 * Show course category and restores visibility for child course and subcategories
1299 *
1300 * Note that there is no capability check inside this function
1301 *
1302 * This function does not update field course_categories.timemodified
1303 * If you want to update timemodified, use
1304 * $coursecat->update(array('visible' => 1));
1305 */
1306 public function show() {
15d50fff 1307 if ($this->show_raw()) {
eabbfa82 1308 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1309 add_to_log(SITEID, "category", "show", "editcategory.php?id=$this->id", $this->id);
1310 }
1311 }
1312
1313 /**
1314 * Returns name of the category formatted as a string
1315 *
1316 * @param array $options formatting options other than context
1317 * @return string
1318 */
1319 public function get_formatted_name($options = array()) {
1320 if ($this->id) {
1321 $context = context_coursecat::instance($this->id);
1322 return format_string($this->name, true, array('context' => $context) + $options);
1323 } else {
1324 return ''; // TODO 'Top'?
1325 }
1326 }
1327
1328 /**
15d50fff 1329 * Returns ids of all parents of the category. Last element in the return array is the direct parent
b33389d2
MG
1330 *
1331 * For example, if you have a tree of categories like:
1332 * Miscellaneous (id = 1)
1333 * Subcategory (id = 2)
1334 * Sub-subcategory (id = 4)
1335 * Other category (id = 3)
1336 *
15d50fff
MG
1337 * coursecat::get(1)->get_parents() == array()
1338 * coursecat::get(2)->get_parents() == array(1)
1339 * coursecat::get(4)->get_parents() == array(1, 2);
b33389d2
MG
1340 *
1341 * Note that this method does not check if all parents are accessible by current user
1342 *
15d50fff 1343 * @return array of category ids
b33389d2 1344 */
15d50fff
MG
1345 public function get_parents() {
1346 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
1347 array_pop($parents);
1348 return $parents;
b33389d2
MG
1349 }
1350
1351 /**
9178bbbc 1352 * This function returns a nice list representing category tree
b33389d2
MG
1353 * for display or to use in a form <select> element
1354 *
9178bbbc
MG
1355 * List is cached for 10 minutes
1356 *
b33389d2
MG
1357 * For example, if you have a tree of categories like:
1358 * Miscellaneous (id = 1)
1359 * Subcategory (id = 2)
1360 * Sub-subcategory (id = 4)
1361 * Other category (id = 3)
1362 * Then after calling this function you will have
1363 * array(1 => 'Miscellaneous',
1364 * 2 => 'Miscellaneous / Subcategory',
1365 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1366 * 3 => 'Other category');
1367 *
1368 * If you specify $requiredcapability, then only categories where the current
1369 * user has that capability will be added to $list.
1370 * If you only have $requiredcapability in a child category, not the parent,
1371 * then the child catgegory will still be included.
1372 *
1373 * If you specify the option $excludeid, then that category, and all its children,
1374 * are omitted from the tree. This is useful when you are doing something like
1375 * moving categories, where you do not want to allow people to move a category
1376 * to be the child of itself.
1377 *
1378 * See also {@link make_categories_options()}
1379 *
1380 * @param string/array $requiredcapability if given, only categories where the current
1381 * user has this capability will be returned. Can also be an array of capabilities,
1382 * in which case they are all required.
1383 * @param integer $excludeid Exclude this category and its children from the lists built.
1384 * @param string $separator string to use as a separator between parent and child category. Default ' / '
1385 * @return array of strings
1386 */
1387 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
9178bbbc
MG
1388 global $DB;
1389 $coursecatcache = cache::make('core', 'coursecat');
b33389d2 1390
9178bbbc
MG
1391 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids with requried cap ($thislist).
1392 $basecachekey = 'catlist';
1393 $baselist = $coursecatcache->get($basecachekey);
1394 if ($baselist !== false) {
1395 $baselist = false;
1396 }
1397 $thislist = false;
1398 if (!empty($requiredcapability)) {
1399 $requiredcapability = (array)$requiredcapability;
1400 $thiscachekey = 'catlist:'. serialize($requiredcapability);
1401 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
1402 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
b33389d2 1403 }
9178bbbc
MG
1404 } else if ($baselist !== false) {
1405 $thislist = array_keys($baselist);
1406 }
1407
1408 if ($baselist === false) {
1409 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
1410 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1411 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
1412 FROM {course_categories} cc
1413 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
1414 ORDER BY cc.sortorder";
1415 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1416 $baselist = array();
1417 $thislist = array();
1418 foreach ($rs as $record) {
1419 // If the category's parent is not visible to the user, it is not visible as well.
1420 if (!$record->parent || isset($baselist[$record->parent])) {
1421 $context = context_coursecat::instance($record->id);
1422 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
1423 // No cap to view category, added to neither $baselist nor $thislist
1424 continue;
1425 }
1426 $baselist[$record->id] = array(
1427 'name' => format_string($record->name, true, array('context' => $context)),
1428 'path' => $record->path
1429 );
1430 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
1431 // No required capability, added to $baselist but not to $thislist.
1432 continue;
1433 }
1434 $thislist[] = $record->id;
1435 }
1436 }
1437 $rs->close();
1438 $coursecatcache->set($basecachekey, $baselist);
1439 if (!empty($requiredcapability)) {
1440 $coursecatcache->set($thiscachekey, join(',', $thislist));
b33389d2 1441 }
9178bbbc
MG
1442 } else if ($thislist === false) {
1443 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
1444 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1445 $sql = "SELECT ctx.instanceid id, $ctxselect
1446 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
1447 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1448 $thislist = array();
1449 foreach (array_keys($baselist) as $id) {
1450 context_helper::preload_from_record($contexts[$id]);
1451 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
1452 $thislist[] = $id;
1453 }
1454 }
1455 $coursecatcache->set($thiscachekey, join(',', $thislist));
b33389d2
MG
1456 }
1457
9178bbbc
MG
1458 // Now build the array of strings to return, mind $separator and $excludeid.
1459 $names = array();
1460 foreach ($thislist as $id) {
1461 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
1462 if (!$excludeid || !in_array($excludeid, $path)) {
1463 $namechunks = array();
1464 foreach ($path as $parentid) {
1465 $namechunks[] = $baselist[$parentid]['name'];
1466 }
1467 $names[$id] = join($separator, $namechunks);
1468 }
b33389d2 1469 }
9178bbbc 1470 return $names;
b33389d2
MG
1471 }
1472
b33389d2
MG
1473 /**
1474 * Prepares the object for caching. Works like the __sleep method.
1475 *
9c6cfc08
MG
1476 * implementing method from interface cacheable_object
1477 *
b33389d2
MG
1478 * @return array ready to be cached
1479 */
1480 public function prepare_to_cache() {
1481 $a = array();
1482 foreach (self::$coursecatfields as $property => $cachedirectives) {
1483 if ($cachedirectives !== null) {
1484 list($shortname, $defaultvalue) = $cachedirectives;
1485 if ($this->$property !== $defaultvalue) {
1486 $a[$shortname] = $this->$property;
1487 }
1488 }
1489 }
1490 $context = context_coursecat::instance($this->id);
1491 $a['xi'] = $context->id;
1492 $a['xp'] = $context->path;
1493 return $a;
1494 }
1495
1496 /**
1497 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
1498 *
9c6cfc08
MG
1499 * implementing method from interface cacheable_object
1500 *
b33389d2
MG
1501 * @param array $a
1502 * @return coursecat
1503 */
1504 public static function wake_from_cache($a) {
1505 $record = new stdClass;
1506 foreach (self::$coursecatfields as $property => $cachedirectives) {
1507 if ($cachedirectives !== null) {
1508 list($shortname, $defaultvalue) = $cachedirectives;
1509 if (array_key_exists($shortname, $a)) {
1510 $record->$property = $a[$shortname];
1511 } else {
1512 $record->$property = $defaultvalue;
1513 }
1514 }
1515 }
1516 $record->ctxid = $a['xi'];
1517 $record->ctxpath = $a['xp'];
1518 $record->ctxdepth = $record->depth + 1;
1519 $record->ctxlevel = CONTEXT_COURSECAT;
1520 $record->ctxinstance = $record->id;
1521 return new coursecat($record, true);
1522 }
1523}