Merge branch 'MDL-39422-master' of git://github.com/danpoltawski/moodle
[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
0a02b80c 126 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
15d50fff
MG
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 }
290af254 595 $all['countall'] = $count;
eabbfa82
MG
596 foreach ($all as $key => $children) {
597 $coursecattreecache->set($key, $children);
598 }
eabbfa82
MG
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
93c544bd 627 $fields = array_keys(array_filter(self::$coursecatfields));
eabbfa82
MG
628 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
629 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
630 FROM {course_categories} cc
631 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
632 WHERE ". $whereclause." ORDER BY cc.sortorder";
633 return $DB->get_records_sql($sql,
634 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
635 }
636
93c544bd
MG
637 /**
638 * Given list of DB records from table course populates each record with list of users with course contact roles
639 *
640 * This function fills the courses with raw information as {@link get_role_users()} would do.
641 * See also {@link course_in_list::get_course_contacts()} for more readable return
642 *
643 * $courses[$i]->managers = array(
644 * $roleassignmentid => $roleuser,
645 * ...
646 * );
647 *
648 * where $roleuser is an stdClass with the following properties:
649 *
650 * $roleuser->raid - role assignment id
651 * $roleuser->id - user id
652 * $roleuser->username
653 * $roleuser->firstname
654 * $roleuser->lastname
655 * $roleuser->rolecoursealias
656 * $roleuser->rolename
657 * $roleuser->sortorder - role sortorder
658 * $roleuser->roleid
659 * $roleuser->roleshortname
660 *
661 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
662 *
663 * @param array $courses
664 */
665 public static function preload_course_contacts(&$courses) {
666 global $CFG, $DB;
667 if (empty($courses) || empty($CFG->coursecontact)) {
668 return;
669 }
670 $managerroles = explode(',', $CFG->coursecontact);
671 /*
672 // TODO MDL-38596, this commented code is similar to get_courses_wmanagers()
673 // It bulk-preloads course contacts for all courses BUT it does not check enrolments
674
675 // first build the array of all context ids of the courses and their categories
676 $allcontexts = array();
677 foreach (array_keys($courses) as $id) {
678 $context = context_course::instance($id);
679 $courses[$id]->managers = array();
680 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
681 if (!isset($allcontexts[$ctxid])) {
682 $allcontexts[$ctxid] = array();
683 }
684 $allcontexts[$ctxid][] = $id;
685 }
686 }
687
688 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
689 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
690 list($sort, $sortparams) = users_order_by_sql('u');
691 $sql = "SELECT ra.contextid, ra.id AS raid,
692 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
693 rn.name AS rolecoursealias, u.id, u.username, u.firstname, u.lastname
694 FROM {role_assignments} ra
695 JOIN {user} u ON ra.userid = u.id
696 JOIN {role} r ON ra.roleid = r.id
697 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
698 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2."
699 ORDER BY r.sortorder, $sort";
700 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $sortparams);
701 foreach($rs as $ra) {
702 foreach ($allcontexts[$ra->contextid] as $id) {
703 $courses[$id]->managers[$ra->raid] = $ra;
704 }
705 }
706 $rs->close();
707 */
708 list($sort, $sortparams) = users_order_by_sql('u');
709 foreach (array_keys($courses) as $id) {
710 $context = context_course::instance($id);
711 $courses[$id]->managers = get_role_users($managerroles, $context, true,
712 'ra.id AS raid, u.id, u.username, u.firstname, u.lastname, rn.name AS rolecoursealias,
713 r.name AS rolename, r.sortorder, r.id AS roleid, r.shortname AS roleshortname',
714 'r.sortorder ASC, ' . $sort, false, '', '', '', '', $sortparams);
715 }
716 }
717
718 /**
719 * Retrieves number of records from course table
720 *
721 * Not all fields are retrieved. Records are ready for preloading context
722 *
723 * @param string $whereclause
724 * @param array $params
725 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
726 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
727 * on not visible courses
728 * @return array array of stdClass objects
729 */
730 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
731 global $DB;
732 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
733 $fields = array('c.id', 'c.category', 'c.sortorder',
734 'c.shortname', 'c.fullname', 'c.idnumber',
735 'c.startdate', 'c.visible');
736 if (!empty($options['summary'])) {
737 $fields[] = 'c.summary';
738 $fields[] = 'c.summaryformat';
739 } else {
a32f163d 740 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' hassummary';
93c544bd
MG
741 }
742 $sql = "SELECT ". join(',', $fields). ", $ctxselect
743 FROM {course} c
744 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
745 WHERE ". $whereclause." ORDER BY c.sortorder";
746 $list = $DB->get_records_sql($sql,
747 array('contextcourse' => CONTEXT_COURSE) + $params);
748
749 if ($checkvisibility) {
750 // Loop through all records and make sure we only return the courses accessible by user.
751 foreach ($list as $course) {
a32f163d
MG
752 if (isset($list[$course->id]->hassummary)) {
753 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
754 }
93c544bd
MG
755 if (empty($course->visible)) {
756 // load context only if we need to check capability
757 context_helper::preload_from_record($course);
758 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
759 unset($list[$course->id]);
760 }
761 }
762 }
763 }
764
765 // preload course contacts if necessary
766 if (!empty($options['coursecontacts'])) {
767 self::preload_course_contacts($list);
768 }
769 return $list;
770 }
771
eabbfa82
MG
772 /**
773 * Returns array of ids of children categories that current user can not see
774 *
775 * This data is cached in user session cache
776 *
777 * @return array
778 */
779 protected function get_not_visible_children_ids() {
780 global $DB;
781 $coursecatcache = cache::make('core', 'coursecat');
782 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
783 // we never checked visible children before
784 $hidden = self::get_tree($this->id.'i');
785 $invisibleids = array();
786 if ($hidden) {
787 // preload categories contexts
788 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
789 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
790 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
791 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
792 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
793 foreach ($contexts as $record) {
794 context_helper::preload_from_record($record);
795 }
796 // check that user has 'viewhiddencategories' capability for each hidden category
797 foreach ($hidden as $id) {
798 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
799 $invisibleids[] = $id;
800 }
801 }
802 }
803 $coursecatcache->set('ic'. $this->id, $invisibleids);
804 }
805 return $invisibleids;
806 }
807
808 /**
93c544bd 809 * Sorts list of records by several fields
eabbfa82 810 *
93c544bd 811 * @param array $records array of stdClass objects
eabbfa82
MG
812 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
813 * @return int
814 */
93c544bd
MG
815 protected static function sort_records(&$records, $sortfields) {
816 if (empty($records)) {
817 return;
818 }
819 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname)
820 if (array_key_exists('displayname', $sortfields)) {
821 foreach ($records as $key => $record) {
822 if (!isset($record->displayname)) {
823 $records[$key]->displayname = get_course_display_name_for_list($record);
eabbfa82 824 }
93c544bd
MG
825 }
826 }
827 // sorting by one field - use collatorlib
828 if (count($sortfields) == 1) {
829 $property = key($sortfields);
830 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
831 $sortflag = collatorlib::SORT_NUMERIC;
832 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
833 $sortflag = collatorlib::SORT_STRING;
eabbfa82 834 } else {
93c544bd
MG
835 $sortflag = collatorlib::SORT_REGULAR;
836 }
837 collatorlib::asort_objects_by_property($records, $property, $sortflag);
838 if ($sortfields[$property] < 0) {
839 $records = array_reverse($records, true);
840 }
841 return;
842 }
843 // sorting by multiple fields
844 uasort($records, function ($a, $b) use ($sortfields) {
845 foreach ($sortfields as $field => $mult) {
846 // nulls first
847 if (is_null($a->$field) && !is_null($b->$field)) {
848 return -$mult;
849 }
850 if (is_null($b->$field) && !is_null($a->$field)) {
eabbfa82
MG
851 return $mult;
852 }
93c544bd
MG
853
854 if (is_string($a->$field) || is_string($b->$field)) {
855 // string fields
856 if ($cmp = strcoll($a->$field, $b->$field)) {
857 return $mult * $cmp;
858 }
859 } else {
860 // int fields
861 if ($a->$field > $b->$field) {
862 return $mult;
863 }
864 if ($a->$field < $b->$field) {
865 return -$mult;
866 }
eabbfa82
MG
867 }
868 }
93c544bd
MG
869 return 0;
870 });
b33389d2
MG
871 }
872
873 /**
874 * Returns array of children categories visible to the current user
875 *
eabbfa82
MG
876 * @param array $options options for retrieving children
877 * - sort - list of fields to sort. Example
878 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
879 * will sort by idnumber asc, name asc and id desc.
880 * Default: array('sortorder' => 1)
881 * Only cached fields may be used for sorting!
882 * - offset
883 * - limit - maximum number of children to return, 0 or null for no limit
b33389d2
MG
884 * @return array of coursecat objects indexed by category id
885 */
eabbfa82
MG
886 public function get_children($options = array()) {
887 global $DB;
888 $coursecatcache = cache::make('core', 'coursecat');
889
890 // get default values for options
891 if (!empty($options['sort']) && is_array($options['sort'])) {
892 $sortfields = $options['sort'];
893 } else {
894 $sortfields = array('sortorder' => 1);
895 }
896 $limit = null;
897 if (!empty($options['limit']) && (int)$options['limit']) {
898 $limit = (int)$options['limit'];
899 }
900 $offset = 0;
901 if (!empty($options['offset']) && (int)$options['offset']) {
902 $offset = (int)$options['offset'];
903 }
904
905 // first retrieve list of user-visible and sorted children ids from cache
906 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
907 if ($sortedids === false) {
908 $sortfieldskeys = array_keys($sortfields);
909 if ($sortfieldskeys[0] === 'sortorder') {
910 // no DB requests required to build the list of ids sorted by sortorder.
911 // We can easily ignore other sort fields because sortorder is always different
912 $sortedids = self::get_tree($this->id);
913 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
914 $sortedids = array_diff($sortedids, $invisibleids);
915 if ($sortfields['sortorder'] == -1) {
916 $sortedids = array_reverse($sortedids, true);
917 }
b33389d2 918 }
eabbfa82
MG
919 } else {
920 // we need to retrieve and sort all children. Good thing that it is done only on first request
921 if ($invisibleids = $this->get_not_visible_children_ids()) {
922 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
923 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
924 array('parent' => $this->id) + $params);
925 } else {
926 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
927 }
93c544bd 928 self::sort_records($records, $sortfields);
eabbfa82
MG
929 $sortedids = array_keys($records);
930 }
931 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
932 }
933
934 if (empty($sortedids)) {
935 return array();
936 }
937
938 // now retrieive and return categories
939 if ($offset || $limit) {
940 $sortedids = array_slice($sortedids, $offset, $limit);
941 }
942 if (isset($records)) {
943 // easy, we have already retrieved records
944 if ($offset || $limit) {
945 $records = array_slice($records, $offset, $limit, true);
946 }
947 } else {
948 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
949 $records = self::get_records('cc.id '. $sql,
950 array('parent' => $this->id) + $params);
951 }
952
953 $rv = array();
954 foreach ($sortedids as $id) {
955 if (isset($records[$id])) {
956 $rv[$id] = new coursecat($records[$id]);
b33389d2
MG
957 }
958 }
959 return $rv;
960 }
961
eabbfa82
MG
962 /**
963 * Returns number of subcategories visible to the current user
964 *
965 * @return int
966 */
967 public function get_children_count() {
968 $sortedids = self::get_tree($this->id);
969 $invisibleids = $this->get_not_visible_children_ids();
970 return count($sortedids) - count($invisibleids);
971 }
972
b33389d2
MG
973 /**
974 * Returns true if the category has ANY children, including those not visible to the user
975 *
976 * @return boolean
977 */
978 public function has_children() {
eabbfa82
MG
979 $allchildren = self::get_tree($this->id);
980 return !empty($allchildren);
b33389d2
MG
981 }
982
983 /**
984 * Returns true if the category has courses in it (count does not include courses
985 * in child categories)
986 *
987 * @return bool
988 */
989 public function has_courses() {
990 global $DB;
991 return $DB->record_exists_sql("select 1 from {course} where category = ?",
992 array($this->id));
993 }
994
93c544bd
MG
995 /**
996 * Searches courses
997 *
998 * List of found course ids is cached for 10 minutes. Cache may be purged prior
999 * to this when somebody edits courses or categories, however it is very
1000 * difficult to keep track of all possible changes that may affect list of courses.
1001 *
1002 * @param array $search contains search criterias, such as:
1003 * - search - search string
1004 * - blocklist - id of block (if we are searching for courses containing specific block0
1005 * - modulelist - name of module (if we are searching for courses containing specific module
1006 * - tagid - id of tag
1007 * @param array $options display options, same as in get_courses() except 'recursive' is ignored - search is always category-independent
1008 * @return array
1009 */
1010 public static function search_courses($search, $options = array()) {
1011 global $DB;
1012 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1013 $limit = !empty($options['limit']) ? $options['limit'] : null;
1014 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1015
1016 $coursecatcache = cache::make('core', 'coursecat');
1017 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1018 $cntcachekey = 'scnt-'. serialize($search);
1019
1020 $ids = $coursecatcache->get($cachekey);
1021 if ($ids !== false) {
1022 // we already cached last search result
1023 $ids = array_slice($ids, $offset, $limit);
1024 $courses = array();
1025 if (!empty($ids)) {
1026 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1027 $records = self::get_course_records("c.id ". $sql, $params, $options);
1028 foreach ($ids as $id) {
1029 $courses[$id] = new course_in_list($records[$id]);
1030 }
1031 }
1032 return $courses;
1033 }
1034
1035 $preloadcoursecontacts = !empty($options['coursecontacts']);
1036 unset($options['coursecontacts']);
1037
1038 if (!empty($search['search'])) {
1039 // search courses that have specified words in their names/summaries
1040 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
1041 $searchterms = array_filter($searchterms, function ($v) { return strlen($v) > 1; } );
1042 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1043 self::sort_records($courselist, $sortfields);
1044 $coursecatcache->set($cachekey, array_keys($courselist));
1045 $coursecatcache->set($cntcachekey, $totalcount);
1046 $records = array_slice($courselist, $offset, $limit, true);
1047 } else {
1048 if (!empty($search['blocklist'])) {
1049 // search courses that have block with specified id
1050 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1051 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1052 WHERE bi.blockname = :blockname)';
1053 $params = array('blockname' => $blockname);
1054 } else if (!empty($search['modulelist'])) {
1055 // search courses that have module with specified name
1056 $where = "c.id IN (SELECT DISTINCT module.course ".
1057 "FROM {".$search['modulelist']."} module)";
1058 $params = array();
1059 } else if (!empty($search['tagid'])) {
1060 // search courses that are tagged with the specified tag
1061 $where = "c.id IN (SELECT t.itemid ".
1062 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1063 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1064 } else {
1065 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1066 return array();
1067 }
1068 $courselist = self::get_course_records($where, $params, $options, true);
1069 self::sort_records($courselist, $sortfields);
1070 $coursecatcache->set($cachekey, array_keys($courselist));
1071 $coursecatcache->set($cntcachekey, count($courselist));
1072 $records = array_slice($courselist, $offset, $limit, true);
1073 }
1074
1075 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1076 if (!empty($preloadcoursecontacts)) {
1077 self::preload_course_contacts($records);
1078 }
1079 $courses = array();
1080 foreach ($records as $record) {
1081 $courses[$record->id] = new course_in_list($record);
1082 }
1083 return $courses;
1084 }
1085
1086 /**
1087 * Returns number of courses in the search results
1088 *
1089 * It is recommended to call this function after {@link coursecat::search_courses()}
1090 * and not before because only course ids are cached. Otherwise search_courses() may
1091 * perform extra DB queries.
1092 *
1093 * @param array $search search criteria, see method search_courses() for more details
1094 * @param array $options display options. They do not affect the result but
1095 * the 'sort' property is used in cache key for storing list of course ids
1096 * @return int
1097 */
1098 public static function search_courses_count($search, $options = array()) {
1099 $coursecatcache = cache::make('core', 'coursecat');
1100 $cntcachekey = 'scnt-'. serialize($search);
1101 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1102 self::search_courses($search, $options);
1103 $cnt = $coursecatcache->get($cntcachekey);
1104 }
1105 return $cnt;
1106 }
1107
1108 /**
1109 * Retrieves the list of courses accessible by user
1110 *
1111 * Not all information is cached, try to avoid calling this method
1112 * twice in the same request.
1113 *
1114 * The following fields are always retrieved:
1115 * - id, visible, fullname, shortname, idnumber, category, sortorder
1116 *
1117 * If you plan to use properties/methods course_in_list::$summary and/or
1118 * course_in_list::get_course_contacts()
1119 * you can preload this information using appropriate 'options'. Otherwise
1120 * they will be retrieved from DB on demand and it may end with bigger DB load.
1121 *
1122 * Note that method course_in_list::has_summary() will not perform additional
1123 * DB queries even if $options['summary'] is not specified
1124 *
1125 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1126 * to this when somebody edits courses or categories, however it is very
1127 * difficult to keep track of all possible changes that may affect list of courses.
1128 *
1129 * @param array $options options for retrieving children
1130 * - recursive - return courses from subcategories as well. Use with care,
1131 * this may be a huge list!
1132 * - summary - preloads fields 'summary' and 'summaryformat'
1133 * - coursecontacts - preloads course contacts
1134 * - sort - list of fields to sort. Example
1135 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1136 * will sort by idnumber asc, shortname asc and id desc.
1137 * Default: array('sortorder' => 1)
1138 * Only cached fields may be used for sorting!
1139 * - offset
1140 * - limit - maximum number of children to return, 0 or null for no limit
1141 * @return array array of instances of course_in_list
1142 */
1143 public function get_courses($options = array()) {
1144 global $DB;
1145 $recursive = !empty($options['recursive']);
1146 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1147 $limit = !empty($options['limit']) ? $options['limit'] : null;
1148 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1149
1150 // Check if this category is hidden.
1151 // Also 0-category never has courses unless this is recursive call.
1152 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1153 return array();
1154 }
1155
1156 $coursecatcache = cache::make('core', 'coursecat');
1157 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1158 '-'. serialize($sortfields);
1159 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1160
1161 // check if we have already cached results
1162 $ids = $coursecatcache->get($cachekey);
1163 if ($ids !== false) {
1164 // we already cached last search result and it did not expire yet
1165 $ids = array_slice($ids, $offset, $limit);
1166 $courses = array();
1167 if (!empty($ids)) {
1168 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1169 $records = self::get_course_records("c.id ". $sql, $params, $options);
1170 foreach ($ids as $id) {
1171 $courses[$id] = new course_in_list($records[$id]);
1172 }
1173 }
1174 return $courses;
1175 }
1176
1177 // retrieve list of courses in category
1178 $where = 'c.id <> :siteid';
1179 $params = array('siteid' => SITEID);
1180 if ($recursive) {
1181 if ($this->id) {
1182 $context = get_category_or_system_context($this->id);
1183 $where .= ' AND ctx.path like :path';
1184 $params['path'] = $context->path. '/%';
1185 }
1186 } else {
1187 $where .= ' AND c.category = :categoryid';
1188 $params['categoryid'] = $this->id;
1189 }
1190 // get list of courses without preloaded coursecontacts because we don't need them for every course
1191 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1192
1193 // sort and cache list
1194 self::sort_records($list, $sortfields);
1195 $coursecatcache->set($cachekey, array_keys($list));
1196 $coursecatcache->set($cntcachekey, count($list));
1197
1198 // Apply offset/limit, convert to course_in_list and return.
1199 $courses = array();
1200 if (isset($list)) {
1201 if ($offset || $limit) {
1202 $list = array_slice($list, $offset, $limit, true);
1203 }
1204 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1205 if (!empty($options['coursecontacts'])) {
1206 self::preload_course_contacts($list);
1207 }
1208 foreach ($list as $record) {
1209 $courses[$record->id] = new course_in_list($record);
1210 }
1211 }
1212 return $courses;
1213 }
1214
1215 /**
1216 * Returns number of courses visible to the user
1217 *
1218 * @param array $options similar to get_courses() except some options do not affect
1219 * number of courses (i.e. sort, summary, offset, limit etc.)
1220 * @return int
1221 */
1222 public function get_courses_count($options = array()) {
1223 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1224 $coursecatcache = cache::make('core', 'coursecat');
1225 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
1226 $this->get_courses($options);
1227 $cnt = $coursecatcache->get($cntcachekey);
1228 }
1229 return $cnt;
1230 }
1231
b33389d2
MG
1232 /**
1233 * Returns true if user can delete current category and all its contents
1234 *
1235 * To be able to delete course category the user must have permission
1236 * 'moodle/category:manage' in ALL child course categories AND
1237 * be able to delete all courses
1238 *
1239 * @return bool
1240 */
1241 public function can_delete_full() {
1242 global $DB;
1243 if (!$this->id) {
1244 // fool-proof
1245 return false;
1246 }
1247
1248 $context = context_coursecat::instance($this->id);
1249 if (!$this->is_uservisible() ||
1250 !has_capability('moodle/category:manage', $context)) {
1251 return false;
1252 }
1253
15d50fff
MG
1254 // Check all child categories (not only direct children)
1255 $sql = context_helper::get_preload_record_columns_sql('ctx');
1256 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1257 ' FROM {context} ctx '.
1258 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1259 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1260 array($context->path. '/%', CONTEXT_COURSECAT));
1261 foreach ($childcategories as $childcat) {
1262 context_helper::preload_from_record($childcat);
1263 $childcontext = context_coursecat::instance($childcat->id);
1264 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1265 !has_capability('moodle/category:manage', $childcontext)) {
1266 return false;
b33389d2
MG
1267 }
1268 }
1269
1270 // Check courses
15d50fff
MG
1271 $sql = context_helper::get_preload_record_columns_sql('ctx');
1272 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1273 $sql. ' FROM {context} ctx '.
1274 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
b33389d2
MG
1275 array('pathmask' => $context->path. '/%',
1276 'courselevel' => CONTEXT_COURSE));
15d50fff
MG
1277 foreach ($coursescontexts as $ctxrecord) {
1278 context_helper::preload_from_record($ctxrecord);
1279 if (!can_delete_course($ctxrecord->courseid)) {
b33389d2
MG
1280 return false;
1281 }
1282 }
1283
1284 return true;
1285 }
1286
1287 /**
1288 * Recursively delete category including all subcategories and courses
1289 *
1290 * Function {@link coursecat::can_delete_full()} MUST be called prior
1291 * to calling this function because there is no capability check
1292 * inside this function
1293 *
1294 * @param boolean $showfeedback display some notices
1295 * @return array return deleted courses
1296 */
15d50fff 1297 public function delete_full($showfeedback = true) {
b33389d2
MG
1298 global $CFG, $DB;
1299 require_once($CFG->libdir.'/gradelib.php');
1300 require_once($CFG->libdir.'/questionlib.php');
1301 require_once($CFG->dirroot.'/cohort/lib.php');
1302
1303 $deletedcourses = array();
1304
1305 // Get children. Note, we don't want to use cache here because
1306 // it would be rebuilt too often
1307 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1308 foreach ($children as $record) {
1309 $coursecat = new coursecat($record);
1310 $deletedcourses += $coursecat->delete_full($showfeedback);
1311 }
1312
1313 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1314 foreach ($courses as $course) {
1315 if (!delete_course($course, false)) {
1316 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1317 }
1318 $deletedcourses[] = $course;
1319 }
1320 }
1321
1322 // move or delete cohorts in this context
1323 cohort_delete_category($this);
1324
1325 // now delete anything that may depend on course category context
1326 grade_course_category_delete($this->id, 0, $showfeedback);
1327 if (!question_delete_course_category($this, 0, $showfeedback)) {
1328 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1329 }
1330
1331 // finally delete the category and it's context
1332 $DB->delete_records('course_categories', array('id' => $this->id));
1333 delete_context(CONTEXT_COURSECAT, $this->id);
1334 add_to_log(SITEID, "category", "delete", "index.php", "$this->name (ID $this->id)");
1335
eabbfa82 1336 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1337
1338 events_trigger('course_category_deleted', $this);
1339
1340 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1341 if ($this->id == $CFG->defaultrequestcategory) {
1342 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1343 }
1344 return $deletedcourses;
1345 }
1346
1347 /**
1348 * Checks if user can delete this category and move content (courses, subcategories and questions)
1349 * to another category. If yes returns the array of possible target categories names
1350 *
1351 * If user can not manage this category or it is completely empty - empty array will be returned
1352 *
1353 * @return array
1354 */
1355 public function move_content_targets_list() {
1356 global $CFG;
1357 require_once($CFG->libdir . '/questionlib.php');
1358 $context = context_coursecat::instance($this->id);
1359 if (!$this->is_uservisible() ||
1360 !has_capability('moodle/category:manage', $context)) {
1361 // User is not able to manage current category, he is not able to delete it.
1362 // No possible target categories.
1363 return array();
1364 }
1365
1366 $testcaps = array();
1367 // If this category has courses in it, user must have 'course:create' capability in target category.
1368 if ($this->has_courses()) {
1369 $testcaps[] = 'moodle/course:create';
1370 }
1371 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1372 if ($this->has_children() || question_context_has_any_questions($context)) {
1373 $testcaps[] = 'moodle/category:manage';
1374 }
1375 if (!empty($testcaps)) {
1376 // return list of categories excluding this one and it's children
1377 return self::make_categories_list($testcaps, $this->id);
1378 }
1379
1380 // Category is completely empty, no need in target for contents.
1381 return array();
1382 }
1383
1384 /**
1385 * Checks if user has capability to move all category content to the new parent before
1386 * removing this category
1387 *
1388 * @param int $newcatid
1389 * @return bool
1390 */
1391 public function can_move_content_to($newcatid) {
1392 global $CFG;
1393 require_once($CFG->libdir . '/questionlib.php');
1394 $context = context_coursecat::instance($this->id);
1395 if (!$this->is_uservisible() ||
1396 !has_capability('moodle/category:manage', $context)) {
1397 return false;
1398 }
1399 $testcaps = array();
1400 // If this category has courses in it, user must have 'course:create' capability in target category.
1401 if ($this->has_courses()) {
1402 $testcaps[] = 'moodle/course:create';
1403 }
1404 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1405 if ($this->has_children() || question_context_has_any_questions($context)) {
1406 $testcaps[] = 'moodle/category:manage';
1407 }
1408 if (!empty($testcaps)) {
1409 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1410 }
1411
1412 // there is no content but still return true
1413 return true;
1414 }
1415
1416 /**
1417 * Deletes a category and moves all content (children, courses and questions) to the new parent
1418 *
1419 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1420 * must be called prior
1421 *
1422 * @param int $newparentid
1423 * @param bool $showfeedback
1424 * @return bool
1425 */
1426 public function delete_move($newparentid, $showfeedback = false) {
1427 global $CFG, $DB, $OUTPUT;
1428 require_once($CFG->libdir.'/gradelib.php');
1429 require_once($CFG->libdir.'/questionlib.php');
1430 require_once($CFG->dirroot.'/cohort/lib.php');
1431
1432 // get all objects and lists because later the caches will be reset so
1433 // we don't need to make extra queries
1434 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1435 $catname = $this->get_formatted_name();
1436 $children = $this->get_children();
1437 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', array('category' => $this->id));
1438 $context = context_coursecat::instance($this->id);
1439
1440 if ($children) {
1441 foreach ($children as $childcat) {
15d50fff 1442 $childcat->change_parent_raw($newparentcat);
b33389d2
MG
1443 // Log action.
1444 add_to_log(SITEID, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id);
1445 }
1446 fix_course_sortorder();
1447 }
1448
1449 if ($coursesids) {
1450 if (!move_courses($coursesids, $newparentid)) {
1451 if ($showfeedback) {
1452 echo $OUTPUT->notification("Error moving courses");
1453 }
1454 return false;
1455 }
1456 if ($showfeedback) {
1457 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1458 }
1459 }
1460
1461 // move or delete cohorts in this context
1462 cohort_delete_category($this);
1463
1464 // now delete anything that may depend on course category context
1465 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1466 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1467 if ($showfeedback) {
1468 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1469 }
1470 return false;
1471 }
1472
1473 // finally delete the category and it's context
1474 $DB->delete_records('course_categories', array('id' => $this->id));
1475 $context->delete();
1476 add_to_log(SITEID, "category", "delete", "index.php", "$this->name (ID $this->id)");
1477
1478 events_trigger('course_category_deleted', $this);
1479
eabbfa82 1480 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1481
1482 if ($showfeedback) {
1483 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1484 }
1485
1486 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1487 if ($this->id == $CFG->defaultrequestcategory) {
1488 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1489 }
1490 return true;
1491 }
1492
1493 /**
1494 * Checks if user can move current category to the new parent
1495 *
1496 * This checks if new parent category exists, user has manage cap there
1497 * and new parent is not a child of this category
1498 *
1499 * @param int|stdClass|coursecat $newparentcat
1500 * @return bool
1501 */
1502 public function can_change_parent($newparentcat) {
1503 if (!has_capability('moodle/category:manage', context_coursecat::instance($this->id))) {
1504 return false;
1505 }
1506 if (is_object($newparentcat)) {
1507 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1508 } else {
1509 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1510 }
1511 if (!$newparentcat) {
1512 return false;
1513 }
15d50fff 1514 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
b33389d2
MG
1515 // can not move to itself or it's own child
1516 return false;
1517 }
1518 return has_capability('moodle/category:manage', get_category_or_system_context($newparentcat->id));
1519 }
1520
1521 /**
1522 * Moves the category under another parent category. All associated contexts are moved as well
1523 *
1524 * This is protected function, use change_parent() or update() from outside of this class
1525 *
1526 * @see coursecat::change_parent()
1527 * @see coursecat::update()
1528 *
1529 * @param coursecat $newparentcat
1530 */
15d50fff 1531 protected function change_parent_raw(coursecat $newparentcat) {
b33389d2
MG
1532 global $DB;
1533
1534 $context = context_coursecat::instance($this->id);
1535
1536 $hidecat = false;
1537 if (empty($newparentcat->id)) {
1538 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1539 $newparent = context_system::instance();
1540 } else {
15d50fff 1541 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
b33389d2
MG
1542 // can not move to itself or it's own child
1543 throw new moodle_exception('cannotmovecategory');
1544 }
1545 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1546 $newparent = context_coursecat::instance($newparentcat->id);
1547
1548 if (!$newparentcat->visible and $this->visible) {
1549 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
1550 $hidecat = true;
1551 }
1552 }
1553 $this->parent = $newparentcat->id;
1554
9c6cfc08 1555 $context->update_moved($newparent);
b33389d2
MG
1556
1557 // now make it last in new category
1558 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1559
1560 if ($hidecat) {
1561 fix_course_sortorder();
1562 $this->restore();
1563 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must become visible again.
15d50fff 1564 $this->hide_raw(1);
b33389d2
MG
1565 }
1566 }
1567
1568 /**
1569 * Efficiently moves a category - NOTE that this can have
1570 * a huge impact access-control-wise...
1571 *
1572 * Note that this function does not check capabilities.
1573 *
1574 * Example of usage:
1575 * $coursecat = coursecat::get($categoryid);
1576 * if ($coursecat->can_change_parent($newparentcatid)) {
1577 * $coursecat->change_parent($newparentcatid);
1578 * }
1579 *
1580 * This function does not update field course_categories.timemodified
1581 * If you want to update timemodified, use
1582 * $coursecat->update(array('parent' => $newparentcat));
1583 *
1584 * @param int|stdClass|coursecat $newparentcat
1585 */
1586 public function change_parent($newparentcat) {
1587 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1588 if (is_object($newparentcat)) {
1589 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1590 } else {
1591 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1592 }
1593 if ($newparentcat->id != $this->parent) {
15d50fff 1594 $this->change_parent_raw($newparentcat);
b33389d2 1595 fix_course_sortorder();
eabbfa82 1596 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1597 $this->restore();
1598 add_to_log(SITEID, "category", "move", "editcategory.php?id=$this->id", $this->id);
1599 }
1600 }
1601
1602 /**
1603 * Hide course category and child course and subcategories
1604 *
1605 * If this category has changed the parent and is moved under hidden
1606 * category we will want to store it's current visibility state in
1607 * the field 'visibleold'. If admin clicked 'hide' for this particular
1608 * category, the field 'visibleold' should become 0.
1609 *
1610 * All subcategories and courses will have their current visibility in the field visibleold
1611 *
1612 * This is protected function, use hide() or update() from outside of this class
1613 *
1614 * @see coursecat::hide()
1615 * @see coursecat::update()
1616 *
1617 * @param int $visibleold value to set in field $visibleold for this category
1618 * @return bool whether changes have been made and caches need to be purged afterwards
1619 */
15d50fff 1620 protected function hide_raw($visibleold = 0) {
b33389d2
MG
1621 global $DB;
1622 $changes = false;
1623
15d50fff
MG
1624 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing
1625 if ($this->id && $this->__get('visibleold') != $visibleold) {
b33389d2
MG
1626 $this->visibleold = $visibleold;
1627 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1628 $changes = true;
1629 }
1630 if (!$this->visible || !$this->id) {
1631 // already hidden or can not be hidden
1632 return $changes;
1633 }
1634
1635 $this->visible = 0;
1636 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1637 $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
1638 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1639 // get all child categories and hide too
1640 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1641 foreach ($subcats as $cat) {
1642 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1643 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1644 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1645 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1646 }
1647 }
1648 return true;
1649 }
1650
1651 /**
1652 * Hide course category and child course and subcategories
1653 *
1654 * Note that there is no capability check inside this function
1655 *
1656 * This function does not update field course_categories.timemodified
1657 * If you want to update timemodified, use
1658 * $coursecat->update(array('visible' => 0));
1659 */
1660 public function hide() {
15d50fff 1661 if ($this->hide_raw(0)) {
eabbfa82 1662 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1663 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$this->id", $this->id);
1664 }
1665 }
1666
1667 /**
1668 * Show course category and restores visibility for child course and subcategories
1669 *
1670 * Note that there is no capability check inside this function
1671 *
1672 * This is protected function, use show() or update() from outside of this class
1673 *
1674 * @see coursecat::show()
1675 * @see coursecat::update()
1676 *
1677 * @return bool whether changes have been made and caches need to be purged afterwards
1678 */
15d50fff 1679 protected function show_raw() {
b33389d2
MG
1680 global $DB;
1681
1682 if ($this->visible) {
1683 // already visible
1684 return false;
1685 }
1686
1687 $this->visible = 1;
1688 $this->visibleold = 1;
1689 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1690 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1691 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
1692 // get all child categories and unhide too
1693 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1694 foreach ($subcats as $cat) {
1695 if ($cat->visibleold) {
1696 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
1697 }
1698 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
1699 }
1700 }
1701 return true;
1702 }
1703
1704 /**
1705 * Show course category and restores visibility for child course and subcategories
1706 *
1707 * Note that there is no capability check inside this function
1708 *
1709 * This function does not update field course_categories.timemodified
1710 * If you want to update timemodified, use
1711 * $coursecat->update(array('visible' => 1));
1712 */
1713 public function show() {
15d50fff 1714 if ($this->show_raw()) {
eabbfa82 1715 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1716 add_to_log(SITEID, "category", "show", "editcategory.php?id=$this->id", $this->id);
1717 }
1718 }
1719
1720 /**
1721 * Returns name of the category formatted as a string
1722 *
1723 * @param array $options formatting options other than context
1724 * @return string
1725 */
1726 public function get_formatted_name($options = array()) {
1727 if ($this->id) {
1728 $context = context_coursecat::instance($this->id);
1729 return format_string($this->name, true, array('context' => $context) + $options);
1730 } else {
1731 return ''; // TODO 'Top'?
1732 }
1733 }
1734
1735 /**
15d50fff 1736 * Returns ids of all parents of the category. Last element in the return array is the direct parent
b33389d2
MG
1737 *
1738 * For example, if you have a tree of categories like:
1739 * Miscellaneous (id = 1)
1740 * Subcategory (id = 2)
1741 * Sub-subcategory (id = 4)
1742 * Other category (id = 3)
1743 *
15d50fff
MG
1744 * coursecat::get(1)->get_parents() == array()
1745 * coursecat::get(2)->get_parents() == array(1)
1746 * coursecat::get(4)->get_parents() == array(1, 2);
b33389d2
MG
1747 *
1748 * Note that this method does not check if all parents are accessible by current user
1749 *
15d50fff 1750 * @return array of category ids
b33389d2 1751 */
15d50fff
MG
1752 public function get_parents() {
1753 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
1754 array_pop($parents);
1755 return $parents;
b33389d2
MG
1756 }
1757
1758 /**
9178bbbc 1759 * This function returns a nice list representing category tree
b33389d2
MG
1760 * for display or to use in a form <select> element
1761 *
9178bbbc
MG
1762 * List is cached for 10 minutes
1763 *
b33389d2
MG
1764 * For example, if you have a tree of categories like:
1765 * Miscellaneous (id = 1)
1766 * Subcategory (id = 2)
1767 * Sub-subcategory (id = 4)
1768 * Other category (id = 3)
1769 * Then after calling this function you will have
1770 * array(1 => 'Miscellaneous',
1771 * 2 => 'Miscellaneous / Subcategory',
1772 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1773 * 3 => 'Other category');
1774 *
1775 * If you specify $requiredcapability, then only categories where the current
1776 * user has that capability will be added to $list.
1777 * If you only have $requiredcapability in a child category, not the parent,
1778 * then the child catgegory will still be included.
1779 *
1780 * If you specify the option $excludeid, then that category, and all its children,
1781 * are omitted from the tree. This is useful when you are doing something like
1782 * moving categories, where you do not want to allow people to move a category
1783 * to be the child of itself.
1784 *
1785 * See also {@link make_categories_options()}
1786 *
1787 * @param string/array $requiredcapability if given, only categories where the current
1788 * user has this capability will be returned. Can also be an array of capabilities,
1789 * in which case they are all required.
1790 * @param integer $excludeid Exclude this category and its children from the lists built.
1791 * @param string $separator string to use as a separator between parent and child category. Default ' / '
1792 * @return array of strings
1793 */
1794 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
9178bbbc
MG
1795 global $DB;
1796 $coursecatcache = cache::make('core', 'coursecat');
b33389d2 1797
9178bbbc
MG
1798 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids with requried cap ($thislist).
1799 $basecachekey = 'catlist';
1800 $baselist = $coursecatcache->get($basecachekey);
1801 if ($baselist !== false) {
1802 $baselist = false;
1803 }
1804 $thislist = false;
1805 if (!empty($requiredcapability)) {
1806 $requiredcapability = (array)$requiredcapability;
1807 $thiscachekey = 'catlist:'. serialize($requiredcapability);
1808 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
1809 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
b33389d2 1810 }
9178bbbc
MG
1811 } else if ($baselist !== false) {
1812 $thislist = array_keys($baselist);
1813 }
1814
1815 if ($baselist === false) {
1816 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
1817 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1818 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
1819 FROM {course_categories} cc
1820 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
1821 ORDER BY cc.sortorder";
1822 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1823 $baselist = array();
1824 $thislist = array();
1825 foreach ($rs as $record) {
1826 // If the category's parent is not visible to the user, it is not visible as well.
1827 if (!$record->parent || isset($baselist[$record->parent])) {
1828 $context = context_coursecat::instance($record->id);
1829 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
1830 // No cap to view category, added to neither $baselist nor $thislist
1831 continue;
1832 }
1833 $baselist[$record->id] = array(
1834 'name' => format_string($record->name, true, array('context' => $context)),
1835 'path' => $record->path
1836 );
1837 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
1838 // No required capability, added to $baselist but not to $thislist.
1839 continue;
1840 }
1841 $thislist[] = $record->id;
1842 }
1843 }
1844 $rs->close();
1845 $coursecatcache->set($basecachekey, $baselist);
1846 if (!empty($requiredcapability)) {
1847 $coursecatcache->set($thiscachekey, join(',', $thislist));
b33389d2 1848 }
9178bbbc
MG
1849 } else if ($thislist === false) {
1850 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
1851 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1852 $sql = "SELECT ctx.instanceid id, $ctxselect
1853 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
1854 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1855 $thislist = array();
1856 foreach (array_keys($baselist) as $id) {
1857 context_helper::preload_from_record($contexts[$id]);
1858 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
1859 $thislist[] = $id;
1860 }
1861 }
1862 $coursecatcache->set($thiscachekey, join(',', $thislist));
b33389d2
MG
1863 }
1864
9178bbbc
MG
1865 // Now build the array of strings to return, mind $separator and $excludeid.
1866 $names = array();
1867 foreach ($thislist as $id) {
1868 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
1869 if (!$excludeid || !in_array($excludeid, $path)) {
1870 $namechunks = array();
1871 foreach ($path as $parentid) {
1872 $namechunks[] = $baselist[$parentid]['name'];
1873 }
1874 $names[$id] = join($separator, $namechunks);
1875 }
b33389d2 1876 }
9178bbbc 1877 return $names;
b33389d2
MG
1878 }
1879
b33389d2
MG
1880 /**
1881 * Prepares the object for caching. Works like the __sleep method.
1882 *
9c6cfc08
MG
1883 * implementing method from interface cacheable_object
1884 *
b33389d2
MG
1885 * @return array ready to be cached
1886 */
1887 public function prepare_to_cache() {
1888 $a = array();
1889 foreach (self::$coursecatfields as $property => $cachedirectives) {
1890 if ($cachedirectives !== null) {
1891 list($shortname, $defaultvalue) = $cachedirectives;
1892 if ($this->$property !== $defaultvalue) {
1893 $a[$shortname] = $this->$property;
1894 }
1895 }
1896 }
1897 $context = context_coursecat::instance($this->id);
1898 $a['xi'] = $context->id;
1899 $a['xp'] = $context->path;
1900 return $a;
1901 }
1902
1903 /**
1904 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
1905 *
9c6cfc08
MG
1906 * implementing method from interface cacheable_object
1907 *
b33389d2
MG
1908 * @param array $a
1909 * @return coursecat
1910 */
1911 public static function wake_from_cache($a) {
1912 $record = new stdClass;
1913 foreach (self::$coursecatfields as $property => $cachedirectives) {
1914 if ($cachedirectives !== null) {
1915 list($shortname, $defaultvalue) = $cachedirectives;
1916 if (array_key_exists($shortname, $a)) {
1917 $record->$property = $a[$shortname];
1918 } else {
1919 $record->$property = $defaultvalue;
1920 }
1921 }
1922 }
1923 $record->ctxid = $a['xi'];
1924 $record->ctxpath = $a['xp'];
1925 $record->ctxdepth = $record->depth + 1;
1926 $record->ctxlevel = CONTEXT_COURSECAT;
1927 $record->ctxinstance = $record->id;
1928 return new coursecat($record, true);
1929 }
1930}
93c544bd
MG
1931
1932/**
1933 * Class to store information about one course in a list of courses
1934 *
1935 * Not all information may be retrieved when object is created but
1936 * it will be retrieved on demand when appropriate property or method is
1937 * called.
1938 *
1939 * Instances of this class are usually returned by functions
1940 * {@link coursecat::search_courses()}
1941 * and
1942 * {@link coursecat::get_courses()}
1943 *
1944 * @package core
1945 * @subpackage course
1946 * @copyright 2013 Marina Glancy
1947 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1948 */
1949class course_in_list implements IteratorAggregate {
1950
1951 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
1952 protected $record;
1953
1954 /** @var array array of course contacts - stores result of call to get_course_contacts() */
1955 protected $coursecontacts;
1956
1957 /**
1958 * Creates an instance of the class from record
1959 *
1960 * @param stdClass $record except fields from course table it may contain
1961 * field hassummary indicating that summary field is not empty.
1962 * Also it is recommended to have context fields here ready for
1963 * context preloading
1964 */
1965 public function __construct(stdClass $record) {
1966 context_instance_preload($record);
1967 $this->record = new stdClass();
1968 foreach ($record as $key => $value) {
1969 $this->record->$key = $value;
1970 }
1971 }
1972
1973 /**
1974 * Indicates if the course has non-empty summary field
1975 *
1976 * @return bool
1977 */
1978 public function has_summary() {
1979 if (isset($this->record->hassummary)) {
1980 return !empty($this->record->hassummary);
1981 }
1982 if (!isset($this->record->summary)) {
1983 // we need to retrieve summary
1984 $this->__get('summary');
1985 }
1986 return !empty($this->record->summary);
1987 }
1988
1989 /**
1990 * Indicates if the course have course contacts to display
1991 *
1992 * @return bool
1993 */
1994 public function has_course_contacts() {
1995 if (!isset($this->record->managers)) {
1996 $courses = array($this->id => &$this->record);
1997 coursecat::preload_course_contacts($courses);
1998 }
1999 return !empty($this->record->managers);
2000 }
2001
2002 /**
2003 * Returns list of course contacts (usually teachers) to display in course link
2004 *
2005 * Roles to display are set up in $CFG->coursecontact
2006 *
2007 * The result is the list of users where user id is the key and the value
2008 * is an array with elements:
2009 * - 'user' - object containing basic user information
2010 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2011 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2012 * - 'username' => fullname($user, $canviewfullnames)
2013 *
2014 * @return array
2015 */
2016 public function get_course_contacts() {
2017 global $CFG;
2018 if (empty($CFG->coursecontact)) {
2019 // no roles are configured to be displayed as course contacts
2020 return array();
2021 }
2022 if ($this->coursecontacts === null) {
2023 $this->coursecontacts = array();
2024 $context = context_course::instance($this->id);
2025
2026 if (!isset($this->record->managers)) {
2027 // preload course contacts from DB
2028 $courses = array($this->id => &$this->record);
2029 coursecat::preload_course_contacts($courses);
2030 }
2031
2032 // build return array with full roles names (for this course context) and users names
2033 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2034 foreach ($this->record->managers as $ruser) {
2035 if (isset($this->coursecontacts[$ruser->id])) {
2036 // only display a user once with the highest sortorder role
2037 continue;
2038 }
2039 $user = new stdClass();
2040 $user->id = $ruser->id;
2041 $user->username = $ruser->username;
2042 $user->firstname = $ruser->firstname;
2043 $user->lastname = $ruser->lastname;
2044 $role = new stdClass();
2045 $role->id = $ruser->roleid;
2046 $role->name = $ruser->rolename;
2047 $role->shortname = $ruser->roleshortname;
2048 $role->coursealias = $ruser->rolecoursealias;
2049
2050 $this->coursecontacts[$user->id] = array(
2051 'user' => $user,
2052 'role' => $role,
2053 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2054 'username' => fullname($user, $canviewfullnames)
2055 );
2056 }
2057 }
2058 return $this->coursecontacts;
2059 }
2060
d1f8c1bd
MG
2061 /**
2062 * Checks if course has any associated overview files
2063 *
2064 * @return bool
2065 */
2066 public function has_course_overviewfiles() {
2067 global $CFG;
2068 if (empty($CFG->courseoverviewfileslimit)) {
2069 return 0;
2070 }
2071 require_once($CFG->libdir. '/filestorage/file_storage.php');
2072 $fs = get_file_storage();
2073 $context = context_course::instance($this->id);
2074 return $fs->is_area_empty($context->id, 'course', 'overviewfiles');
2075 }
2076
2077 /**
2078 * Returns all course overview files
2079 *
2080 * @return array array of stored_file objects
2081 */
2082 public function get_course_overviewfiles() {
2083 global $CFG;
2084 if (empty($CFG->courseoverviewfileslimit)) {
2085 return array();
2086 }
2087 require_once($CFG->libdir. '/filestorage/file_storage.php');
473d5f74 2088 require_once($CFG->dirroot. '/course/lib.php');
d1f8c1bd
MG
2089 $fs = get_file_storage();
2090 $context = context_course::instance($this->id);
2091 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2092 if (count($files)) {
2093 $overviewfilesoptions = course_overviewfiles_options($this->id);
2094 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2095 if ($acceptedtypes !== '*') {
2096 // filter only files with allowed extensions
2097 require_once($CFG->libdir. '/filelib.php');
2098 $files = array_filter($files, function ($file) use ($acceptedtypes) {
2099 return file_extension_in_typegroup($file->get_filename(), $acceptedtypes);} );
2100 }
2101 if (count($files) > $CFG->courseoverviewfileslimit) {
2102 // return no more than $CFG->courseoverviewfileslimit files
2103 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2104 }
2105 }
2106 return $files;
2107 }
2108
93c544bd
MG
2109 // ====== magic methods =======
2110
2111 public function __isset($name) {
2112 return isset($this->record->$name);
2113 }
2114
2115 /**
2116 * Magic method to get a course property
2117 *
2118 * Returns any field from table course (from cache or from DB) and/or special field 'hassummary'
2119 *
2120 * @param string $name
2121 * @return mixed
2122 */
2123 public function __get($name) {
2124 global $DB;
2125 if (property_exists($this->record, $name)) {
2126 return $this->record->$name;
2127 } else if ($name === 'summary' || $name === 'summaryformat') {
2128 // retrieve fields summary and summaryformat together because they are most likely to be used together
2129 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2130 $this->record->summary = $record->summary;
2131 $this->record->summaryformat = $record->summaryformat;
2132 return $this->record->$name;
2133 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2134 // another field from table 'course' that was not retrieved
2135 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2136 return $this->record->$name;
2137 }
2138 debugging('Invalid course property accessed! '.$name);
2139 return null;
2140 }
2141
2142 /**
2143 * ALl properties are read only, sorry.
2144 * @param string $name
2145 */
2146 public function __unset($name) {
2147 debugging('Can not unset '.get_class($this).' instance properties!');
2148 }
2149
2150 /**
2151 * Magic setter method, we do not want anybody to modify properties from the outside
2152 * @param string $name
2153 * @param mixed $value
2154 */
2155 public function __set($name, $value) {
2156 debugging('Can not change '.get_class($this).' instance properties!');
2157 }
2158
2159 // ====== implementing method from interface IteratorAggregate ======
2160
2161 /**
2162 * Create an iterator because magic vars can't be seen by 'foreach'.
2163 * Exclude context fields
2164 */
2165 public function getIterator() {
2166 $ret = array('id' => $this->record->id);
2167 foreach ($this->record as $property => $value) {
2168 $ret[$property] = $value;
2169 }
2170 return new ArrayIterator($ret);
2171 }
2172}