MDL-41942 course: Allow course listings to work with caches disabled
[moodle.git] / lib / coursecatlib.php
CommitLineData
b33389d2
MG
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Contains class coursecat reponsible for course category operations
19 *
20 * @package core
21 * @subpackage course
22 * @copyright 2013 Marina Glancy
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26defined('MOODLE_INTERNAL') || die();
27
28/**
29 * Class to store, cache, render and manage course category
30 *
1eac2033
SH
31 * @property-read int $id
32 * @property-read string $name
33 * @property-read string $idnumber
34 * @property-read string $description
35 * @property-read int $descriptionformat
36 * @property-read int $parent
37 * @property-read int $sortorder
38 * @property-read int $coursecount
39 * @property-read int $visible
40 * @property-read int $visibleold
41 * @property-read int $timemodified
42 * @property-read int $depth
43 * @property-read string $path
44 * @property-read string $theme
45 *
b33389d2
MG
46 * @package core
47 * @subpackage course
48 * @copyright 2013 Marina Glancy
49 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 */
51class coursecat implements renderable, cacheable_object, IteratorAggregate {
52 /** @var coursecat stores pseudo category with id=0. Use coursecat::get(0) to retrieve */
53 protected static $coursecat0;
54
36ba8fde
MG
55 const CACHE_COURSE_CONTACTS_TTL = 3600; // do not fetch course contacts more often than once per hour
56
b33389d2
MG
57 /** @var array list of all fields and their short name and default value for caching */
58 protected static $coursecatfields = array(
59 'id' => array('id', 0),
60 'name' => array('na', ''),
61 'idnumber' => array('in', null),
15d50fff
MG
62 'description' => null, // not cached
63 'descriptionformat' => null, // not cached
b33389d2
MG
64 'parent' => array('pa', 0),
65 'sortorder' => array('so', 0),
e4008e9d 66 'coursecount' => array('cc', 0),
b33389d2 67 'visible' => array('vi', 1),
15d50fff 68 'visibleold' => null, // not cached
b33389d2
MG
69 'timemodified' => null, // not cached
70 'depth' => array('dh', 1),
71 'path' => array('ph', null),
15d50fff 72 'theme' => null, // not cached
b33389d2
MG
73 );
74
75 /** @var int */
76 protected $id;
77
78 /** @var string */
79 protected $name = '';
80
81 /** @var string */
82 protected $idnumber = null;
83
84 /** @var string */
15d50fff 85 protected $description = false;
b33389d2
MG
86
87 /** @var int */
15d50fff 88 protected $descriptionformat = false;
b33389d2
MG
89
90 /** @var int */
91 protected $parent = 0;
92
93 /** @var int */
94 protected $sortorder = 0;
95
96 /** @var int */
15d50fff 97 protected $coursecount = false;
b33389d2
MG
98
99 /** @var int */
100 protected $visible = 1;
101
102 /** @var int */
15d50fff 103 protected $visibleold = false;
b33389d2
MG
104
105 /** @var int */
15d50fff 106 protected $timemodified = false;
b33389d2
MG
107
108 /** @var int */
109 protected $depth = 0;
110
111 /** @var string */
112 protected $path = '';
113
114 /** @var string */
15d50fff 115 protected $theme = false;
b33389d2
MG
116
117 /** @var bool */
118 protected $fromcache;
119
120 // ====== magic methods =======
121
122 /**
123 * Magic setter method, we do not want anybody to modify properties from the outside
9c6cfc08 124 *
b33389d2
MG
125 * @param string $name
126 * @param mixed $value
127 */
128 public function __set($name, $value) {
129 debugging('Can not change coursecat instance properties!', DEBUG_DEVELOPER);
130 }
131
132 /**
15d50fff 133 * Magic method getter, redirects to read only values. Queries from DB the fields that were not cached
9c6cfc08 134 *
b33389d2
MG
135 * @param string $name
136 * @return mixed
137 */
138 public function __get($name) {
15d50fff 139 global $DB;
b33389d2 140 if (array_key_exists($name, self::$coursecatfields)) {
15d50fff
MG
141 if ($this->$name === false) {
142 // property was not retrieved from DB, retrieve all not retrieved fields
0a02b80c 143 $notretrievedfields = array_diff_key(self::$coursecatfields, array_filter(self::$coursecatfields));
15d50fff
MG
144 $record = $DB->get_record('course_categories', array('id' => $this->id),
145 join(',', array_keys($notretrievedfields)), MUST_EXIST);
146 foreach ($record as $key => $value) {
147 $this->$key = $value;
148 }
149 }
b33389d2
MG
150 return $this->$name;
151 }
152 debugging('Invalid coursecat property accessed! '.$name, DEBUG_DEVELOPER);
153 return null;
154 }
155
156 /**
157 * Full support for isset on our magic read only properties.
9c6cfc08 158 *
b33389d2
MG
159 * @param string $name
160 * @return bool
161 */
162 public function __isset($name) {
163 if (array_key_exists($name, self::$coursecatfields)) {
164 return isset($this->$name);
165 }
166 return false;
167 }
168
169 /**
9c6cfc08
MG
170 * All properties are read only, sorry.
171 *
b33389d2
MG
172 * @param string $name
173 */
174 public function __unset($name) {
175 debugging('Can not unset coursecat instance properties!', DEBUG_DEVELOPER);
176 }
177
b33389d2
MG
178 /**
179 * Create an iterator because magic vars can't be seen by 'foreach'.
9c6cfc08
MG
180 *
181 * implementing method from interface IteratorAggregate
182 *
183 * @return ArrayIterator
b33389d2
MG
184 */
185 public function getIterator() {
186 $ret = array();
187 foreach (self::$coursecatfields as $property => $unused) {
15d50fff
MG
188 if ($this->$property !== false) {
189 $ret[$property] = $this->$property;
190 }
b33389d2
MG
191 }
192 return new ArrayIterator($ret);
193 }
194
b33389d2
MG
195 /**
196 * Constructor
197 *
198 * Constructor is protected, use coursecat::get($id) to retrieve category
199 *
9c6cfc08
MG
200 * @param stdClass $record record from DB (may not contain all fields)
201 * @param bool $fromcache whether it is being restored from cache
b33389d2
MG
202 */
203 protected function __construct(stdClass $record, $fromcache = false) {
9c6cfc08 204 context_helper::preload_from_record($record);
b33389d2
MG
205 foreach ($record as $key => $val) {
206 if (array_key_exists($key, self::$coursecatfields)) {
207 $this->$key = $val;
208 }
209 }
210 $this->fromcache = $fromcache;
211 }
212
213 /**
214 * Returns coursecat object for requested category
215 *
216 * If category is not visible to user it is treated as non existing
15d50fff 217 * unless $alwaysreturnhidden is set to true
b33389d2
MG
218 *
219 * If id is 0, the pseudo object for root category is returned (convenient
220 * for calling other functions such as get_children())
221 *
222 * @param int $id category id
223 * @param int $strictness whether to throw an exception (MUST_EXIST) or
224 * return null (IGNORE_MISSING) in case the category is not found or
225 * not visible to current user
15d50fff 226 * @param bool $alwaysreturnhidden set to true if you want an object to be
b33389d2
MG
227 * returned even if this category is not visible to the current user
228 * (category is hidden and user does not have
229 * 'moodle/category:viewhiddencategories' capability). Use with care!
15d50fff 230 * @return null|coursecat
b33389d2 231 */
15d50fff 232 public static function get($id, $strictness = MUST_EXIST, $alwaysreturnhidden = false) {
b33389d2
MG
233 if (!$id) {
234 if (!isset(self::$coursecat0)) {
15d50fff
MG
235 $record = new stdClass();
236 $record->id = 0;
237 $record->visible = 1;
238 $record->depth = 0;
239 $record->path = '';
240 self::$coursecat0 = new coursecat($record);
b33389d2
MG
241 }
242 return self::$coursecat0;
243 }
eabbfa82
MG
244 $coursecatrecordcache = cache::make('core', 'coursecatrecords');
245 $coursecat = $coursecatrecordcache->get($id);
15d50fff 246 if ($coursecat === false) {
eabbfa82
MG
247 if ($records = self::get_records('cc.id = :id', array('id' => $id))) {
248 $record = reset($records);
249 $coursecat = new coursecat($record);
250 // Store in cache
251 $coursecatrecordcache->set($id, $coursecat);
b33389d2
MG
252 }
253 }
15d50fff 254 if ($coursecat && ($alwaysreturnhidden || $coursecat->is_uservisible())) {
b33389d2
MG
255 return $coursecat;
256 } else {
257 if ($strictness == MUST_EXIST) {
258 throw new moodle_exception('unknowcategory');
259 }
260 }
261 return null;
262 }
263
264 /**
265 * Returns the first found category
266 *
267 * Note that if there are no categories visible to the current user on the first level,
268 * the invisible category may be returned
269 *
270 * @return coursecat
271 */
272 public static function get_default() {
273 if ($visiblechildren = self::get(0)->get_children()) {
274 $defcategory = reset($visiblechildren);
275 } else {
eabbfa82
MG
276 $toplevelcategories = self::get_tree(0);
277 $defcategoryid = $toplevelcategories[0];
b33389d2
MG
278 $defcategory = self::get($defcategoryid, MUST_EXIST, true);
279 }
280 return $defcategory;
281 }
282
283 /**
284 * Restores the object after it has been externally modified in DB for example
285 * during {@link fix_course_sortorder()}
286 */
287 protected function restore() {
288 // update all fields in the current object
289 $newrecord = self::get($this->id, MUST_EXIST, true);
290 foreach (self::$coursecatfields as $key => $unused) {
291 $this->$key = $newrecord->$key;
292 }
293 }
294
295 /**
296 * Creates a new category either from form data or from raw data
297 *
298 * Please note that this function does not verify access control.
299 *
300 * Exception is thrown if name is missing or idnumber is duplicating another one in the system.
301 *
302 * Category visibility is inherited from parent unless $data->visible = 0 is specified
303 *
304 * @param array|stdClass $data
305 * @param array $editoroptions if specified, the data is considered to be
306 * form data and file_postupdate_standard_editor() is being called to
307 * process images in description.
308 * @return coursecat
309 * @throws moodle_exception
310 */
311 public static function create($data, $editoroptions = null) {
312 global $DB, $CFG;
313 $data = (object)$data;
314 $newcategory = new stdClass();
315
316 $newcategory->descriptionformat = FORMAT_MOODLE;
317 $newcategory->description = '';
318 // copy all description* fields regardless of whether this is form data or direct field update
319 foreach ($data as $key => $value) {
320 if (preg_match("/^description/", $key)) {
321 $newcategory->$key = $value;
322 }
323 }
324
325 if (empty($data->name)) {
326 throw new moodle_exception('categorynamerequired');
327 }
2f1e464a 328 if (core_text::strlen($data->name) > 255) {
b33389d2
MG
329 throw new moodle_exception('categorytoolong');
330 }
331 $newcategory->name = $data->name;
332
333 // validate and set idnumber
334 if (!empty($data->idnumber)) {
2f1e464a 335 if (core_text::strlen($data->idnumber) > 100) {
b33389d2
MG
336 throw new moodle_exception('idnumbertoolong');
337 }
9c6cfc08
MG
338 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
339 throw new moodle_exception('categoryidnumbertaken');
340 }
b33389d2
MG
341 }
342 if (isset($data->idnumber)) {
343 $newcategory->idnumber = $data->idnumber;
344 }
345
346 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
347 $newcategory->theme = $data->theme;
348 }
349
350 if (empty($data->parent)) {
351 $parent = self::get(0);
352 } else {
353 $parent = self::get($data->parent, MUST_EXIST, true);
354 }
355 $newcategory->parent = $parent->id;
356 $newcategory->depth = $parent->depth + 1;
357
358 // By default category is visible, unless visible = 0 is specified or parent category is hidden
359 if (isset($data->visible) && !$data->visible) {
360 // create a hidden category
361 $newcategory->visible = $newcategory->visibleold = 0;
362 } else {
363 // create a category that inherits visibility from parent
364 $newcategory->visible = $parent->visible;
365 // in case parent is hidden, when it changes visibility this new subcategory will automatically become visible too
366 $newcategory->visibleold = 1;
367 }
368
369 $newcategory->sortorder = 0;
370 $newcategory->timemodified = time();
371
372 $newcategory->id = $DB->insert_record('course_categories', $newcategory);
373
374 // update path (only possible after we know the category id
375 $path = $parent->path . '/' . $newcategory->id;
376 $DB->set_field('course_categories', 'path', $path, array('id' => $newcategory->id));
377
378 // We should mark the context as dirty
379 context_coursecat::instance($newcategory->id)->mark_dirty();
380
381 fix_course_sortorder();
382
383 // if this is data from form results, save embedded files and update description
384 $categorycontext = context_coursecat::instance($newcategory->id);
385 if ($editoroptions) {
386 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
387
388 // update only fields description and descriptionformat
9c6cfc08
MG
389 $updatedata = new stdClass();
390 $updatedata->id = $newcategory->id;
391 $updatedata->description = $newcategory->description;
392 $updatedata->descriptionformat = $newcategory->descriptionformat;
b33389d2 393 $DB->update_record('course_categories', $updatedata);
b33389d2
MG
394 }
395
396 add_to_log(SITEID, "category", 'add', "editcategory.php?id=$newcategory->id", $newcategory->id);
eabbfa82 397 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
398
399 return self::get($newcategory->id, MUST_EXIST, true);
400 }
401
402 /**
403 * Updates the record with either form data or raw data
404 *
405 * Please note that this function does not verify access control.
406 *
15d50fff
MG
407 * This function calls coursecat::change_parent_raw if field 'parent' is updated.
408 * It also calls coursecat::hide_raw or coursecat::show_raw if 'visible' is updated.
b33389d2
MG
409 * Visibility is changed first and then parent is changed. This means that
410 * if parent category is hidden, the current category will become hidden
411 * too and it may overwrite whatever was set in field 'visible'.
412 *
413 * Note that fields 'path' and 'depth' can not be updated manually
414 * Also coursecat::update() can not directly update the field 'sortoder'
415 *
416 * @param array|stdClass $data
417 * @param array $editoroptions if specified, the data is considered to be
418 * form data and file_postupdate_standard_editor() is being called to
419 * process images in description.
420 * @throws moodle_exception
421 */
422 public function update($data, $editoroptions = null) {
423 global $DB, $CFG;
424 if (!$this->id) {
425 // there is no actual DB record associated with root category
426 return;
427 }
428
429 $data = (object)$data;
430 $newcategory = new stdClass();
431 $newcategory->id = $this->id;
432
433 // copy all description* fields regardless of whether this is form data or direct field update
434 foreach ($data as $key => $value) {
435 if (preg_match("/^description/", $key)) {
436 $newcategory->$key = $value;
437 }
438 }
439
440 if (isset($data->name) && empty($data->name)) {
441 throw new moodle_exception('categorynamerequired');
442 }
443
444 if (!empty($data->name) && $data->name !== $this->name) {
2f1e464a 445 if (core_text::strlen($data->name) > 255) {
b33389d2
MG
446 throw new moodle_exception('categorytoolong');
447 }
448 $newcategory->name = $data->name;
449 }
450
451 if (isset($data->idnumber) && $data->idnumber != $this->idnumber) {
2f1e464a 452 if (core_text::strlen($data->idnumber) > 100) {
b33389d2
MG
453 throw new moodle_exception('idnumbertoolong');
454 }
9c6cfc08 455 if ($DB->record_exists('course_categories', array('idnumber' => $data->idnumber))) {
b33389d2
MG
456 throw new moodle_exception('categoryidnumbertaken');
457 }
458 $newcategory->idnumber = $data->idnumber;
459 }
460
461 if (isset($data->theme) && !empty($CFG->allowcategorythemes)) {
462 $newcategory->theme = $data->theme;
463 }
464
465 $changes = false;
466 if (isset($data->visible)) {
467 if ($data->visible) {
15d50fff 468 $changes = $this->show_raw();
b33389d2 469 } else {
15d50fff 470 $changes = $this->hide_raw(0);
b33389d2
MG
471 }
472 }
473
474 if (isset($data->parent) && $data->parent != $this->parent) {
475 if ($changes) {
eabbfa82 476 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
477 }
478 $parentcat = self::get($data->parent, MUST_EXIST, true);
15d50fff 479 $this->change_parent_raw($parentcat);
b33389d2
MG
480 fix_course_sortorder();
481 }
482
483 $newcategory->timemodified = time();
484
485 if ($editoroptions) {
486 $categorycontext = context_coursecat::instance($this->id);
487 $newcategory = file_postupdate_standard_editor($newcategory, 'description', $editoroptions, $categorycontext, 'coursecat', 'description', 0);
488 }
489 $DB->update_record('course_categories', $newcategory);
490 add_to_log(SITEID, "category", 'update', "editcategory.php?id=$this->id", $this->id);
491 fix_course_sortorder();
eabbfa82
MG
492 // purge cache even if fix_course_sortorder() did not do it
493 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
494
495 // update all fields in the current object
496 $this->restore();
497 }
498
499 /**
500 * Checks if this course category is visible to current user
501 *
502 * Please note that methods coursecat::get (without 3rd argumet),
503 * coursecat::get_children(), etc. return only visible categories so it is
504 * usually not needed to call this function outside of this class
505 *
506 * @return bool
507 */
508 public function is_uservisible() {
509 return !$this->id || $this->visible ||
510 has_capability('moodle/category:viewhiddencategories',
511 context_coursecat::instance($this->id));
512 }
513
514 /**
515 * Returns all categories visible to the current user
516 *
517 * This is a generic function that returns an array of
518 * (category id => coursecat object) sorted by sortorder
519 *
520 * @see coursecat::get_children()
521 * @see coursecat::get_all_parents()
522 *
523 * @return cacheable_object_array array of coursecat objects
524 */
525 public static function get_all_visible() {
526 global $USER;
527 $coursecatcache = cache::make('core', 'coursecat');
528 $ids = $coursecatcache->get('user'. $USER->id);
529 if ($ids === false) {
530 $all = self::get_all_ids();
531 $parentvisible = $all[0];
532 $rv = array();
533 foreach ($all as $id => $children) {
534 if ($id && in_array($id, $parentvisible) &&
535 ($coursecat = self::get($id, IGNORE_MISSING)) &&
536 (!$coursecat->parent || isset($rv[$coursecat->parent]))) {
537 $rv[$id] = $coursecat;
538 $parentvisible += $children;
539 }
540 }
541 $coursecatcache->set('user'. $USER->id, array_keys($rv));
542 } else {
543 $rv = array();
544 foreach ($ids as $id) {
545 if ($coursecat = self::get($id, IGNORE_MISSING)) {
546 $rv[$id] = $coursecat;
547 }
548 }
549 }
550 return $rv;
551 }
552
553 /**
eabbfa82 554 * Returns the entry from categories tree and makes sure the application-level tree cache is built
b33389d2 555 *
eabbfa82 556 * The following keys can be requested:
b33389d2 557 *
eabbfa82
MG
558 * 'countall' - total number of categories in the system (always present)
559 * 0 - array of ids of top-level categories (always present)
560 * '0i' - array of ids of top-level categories that have visible=0 (always present but may be empty array)
561 * $id (int) - array of ids of categories that are direct children of category with id $id. If
562 * category with id $id does not exist returns false. If category has no children returns empty array
563 * $id.'i' - array of ids of children categories that have visible=0
564 *
565 * @param int|string $id
566 * @return mixed
b33389d2 567 */
eabbfa82 568 protected static function get_tree($id) {
b33389d2 569 global $DB;
eabbfa82
MG
570 $coursecattreecache = cache::make('core', 'coursecattree');
571 $rv = $coursecattreecache->get($id);
572 if ($rv !== false) {
573 return $rv;
574 }
eabbfa82
MG
575 // Re-build the tree.
576 $sql = "SELECT cc.id, cc.parent, cc.visible
577 FROM {course_categories} cc
578 ORDER BY cc.sortorder";
579 $rs = $DB->get_recordset_sql($sql, array());
580 $all = array(0 => array(), '0i' => array());
581 $count = 0;
582 foreach ($rs as $record) {
583 $all[$record->id] = array();
584 $all[$record->id. 'i'] = array();
585 if (array_key_exists($record->parent, $all)) {
b33389d2 586 $all[$record->parent][] = $record->id;
eabbfa82
MG
587 if (!$record->visible) {
588 $all[$record->parent. 'i'][] = $record->id;
589 }
590 } else {
591 // parent not found. This is data consistency error but next fix_course_sortorder() should fix it
592 $all[0][] = $record->id;
b73d8a35
MG
593 if (!$record->visible) {
594 $all['0i'][] = $record->id;
595 }
b33389d2 596 }
eabbfa82
MG
597 $count++;
598 }
599 $rs->close();
600 if (!$count) {
601 // No categories found.
602 // This may happen after upgrade from very old moodle version. In new versions the default category is created on install.
603 $defcoursecat = self::create(array('name' => get_string('miscellaneous')));
604 set_config('defaultrequestcategory', $defcoursecat->id);
605 $all[0] = array($defcoursecat->id);
606 $all[$defcoursecat->id] = array();
607 $count++;
b33389d2 608 }
290af254 609 $all['countall'] = $count;
eabbfa82
MG
610 foreach ($all as $key => $children) {
611 $coursecattreecache->set($key, $children);
612 }
eabbfa82
MG
613 if (array_key_exists($id, $all)) {
614 return $all[$id];
615 }
6b0b05b3
MG
616 // Requested non-existing category.
617 return array();
b33389d2
MG
618 }
619
b33389d2
MG
620 /**
621 * Returns number of ALL categories in the system regardless if
622 * they are visible to current user or not
623 *
624 * @return int
625 */
15d50fff 626 public static function count_all() {
eabbfa82
MG
627 return self::get_tree('countall');
628 }
629
630 /**
631 * Retrieves number of records from course_categories table
632 *
633 * Only cached fields are retrieved. Records are ready for preloading context
634 *
635 * @param string $whereclause
636 * @param array $params
637 * @return array array of stdClass objects
638 */
639 protected static function get_records($whereclause, $params) {
640 global $DB;
641 // Retrieve from DB only the fields that need to be stored in cache
93c544bd 642 $fields = array_keys(array_filter(self::$coursecatfields));
eabbfa82
MG
643 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
644 $sql = "SELECT cc.". join(',cc.', $fields). ", $ctxselect
645 FROM {course_categories} cc
646 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
647 WHERE ". $whereclause." ORDER BY cc.sortorder";
648 return $DB->get_records_sql($sql,
649 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
650 }
651
93c544bd
MG
652 /**
653 * Given list of DB records from table course populates each record with list of users with course contact roles
654 *
655 * This function fills the courses with raw information as {@link get_role_users()} would do.
656 * See also {@link course_in_list::get_course_contacts()} for more readable return
657 *
658 * $courses[$i]->managers = array(
659 * $roleassignmentid => $roleuser,
660 * ...
661 * );
662 *
663 * where $roleuser is an stdClass with the following properties:
664 *
665 * $roleuser->raid - role assignment id
666 * $roleuser->id - user id
667 * $roleuser->username
668 * $roleuser->firstname
669 * $roleuser->lastname
670 * $roleuser->rolecoursealias
671 * $roleuser->rolename
672 * $roleuser->sortorder - role sortorder
673 * $roleuser->roleid
674 * $roleuser->roleshortname
675 *
676 * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
677 *
678 * @param array $courses
679 */
680 public static function preload_course_contacts(&$courses) {
681 global $CFG, $DB;
682 if (empty($courses) || empty($CFG->coursecontact)) {
683 return;
684 }
685 $managerroles = explode(',', $CFG->coursecontact);
36ba8fde
MG
686 $cache = cache::make('core', 'coursecontacts');
687 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
688 // check if cache was set for the current course contacts and it is not yet expired
689 if (empty($cacheddata['basic']) || $cacheddata['basic']['roles'] !== $CFG->coursecontact ||
690 $cacheddata['basic']['lastreset'] < time() - self::CACHE_COURSE_CONTACTS_TTL) {
691 // reset cache
692 $cache->purge();
693 $cache->set('basic', array('roles' => $CFG->coursecontact, 'lastreset' => time()));
694 $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
695 }
696 $courseids = array();
697 foreach (array_keys($courses) as $id) {
698 if ($cacheddata[$id] !== false) {
699 $courses[$id]->managers = $cacheddata[$id];
700 } else {
701 $courseids[] = $id;
702 }
703 }
31b0530a 704
36ba8fde
MG
705 // $courseids now stores list of ids of courses for which we still need to retrieve contacts
706 if (empty($courseids)) {
707 return;
708 }
93c544bd
MG
709
710 // first build the array of all context ids of the courses and their categories
711 $allcontexts = array();
31b0530a 712 foreach ($courseids as $id) {
93c544bd
MG
713 $context = context_course::instance($id);
714 $courses[$id]->managers = array();
715 foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
716 if (!isset($allcontexts[$ctxid])) {
717 $allcontexts[$ctxid] = array();
718 }
719 $allcontexts[$ctxid][] = $id;
720 }
721 }
722
31b0530a 723 // fetch list of all users with course contact roles in any of the courses contexts or parent contexts
93c544bd
MG
724 list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
725 list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
726 list($sort, $sortparams) = users_order_by_sql('u');
ef4d3233 727 $notdeleted = array('notdeleted'=>0);
a327f25e 728 $allnames = get_all_user_name_fields(true, 'u');
93c544bd
MG
729 $sql = "SELECT ra.contextid, ra.id AS raid,
730 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
a327f25e 731 rn.name AS rolecoursealias, u.id, u.username, $allnames
93c544bd
MG
732 FROM {role_assignments} ra
733 JOIN {user} u ON ra.userid = u.id
734 JOIN {role} r ON ra.roleid = r.id
735 LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)
ef4d3233 736 WHERE ra.contextid ". $sql1." AND ra.roleid ". $sql2." AND u.deleted = :notdeleted
93c544bd 737 ORDER BY r.sortorder, $sort";
ef4d3233 738 $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
31b0530a 739 $checkenrolments = array();
93c544bd
MG
740 foreach($rs as $ra) {
741 foreach ($allcontexts[$ra->contextid] as $id) {
742 $courses[$id]->managers[$ra->raid] = $ra;
31b0530a
MG
743 if (!isset($checkenrolments[$id])) {
744 $checkenrolments[$id] = array();
745 }
746 $checkenrolments[$id][] = $ra->id;
93c544bd
MG
747 }
748 }
749 $rs->close();
31b0530a
MG
750
751 // remove from course contacts users who are not enrolled in the course
752 $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
753 foreach ($checkenrolments as $id => $userids) {
754 if (empty($enrolleduserids[$id])) {
755 $courses[$id]->managers = array();
756 } else if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
757 foreach ($courses[$id]->managers as $raid => $ra) {
758 if (in_array($ra->id, $notenrolled)) {
759 unset($courses[$id]->managers[$raid]);
760 }
761 }
762 }
763 }
36ba8fde
MG
764
765 // set the cache
766 $values = array();
767 foreach ($courseids as $id) {
768 $values[$id] = $courses[$id]->managers;
769 }
770 $cache->set_many($values);
31b0530a
MG
771 }
772
773 /**
774 * Verify user enrollments for multiple course-user combinations
775 *
776 * @param array $courseusers array where keys are course ids and values are array
777 * of users in this course whose enrolment we wish to verify
778 * @return array same structure as input array but values list only users from input
779 * who are enrolled in the course
780 */
781 protected static function ensure_users_enrolled($courseusers) {
782 global $DB;
783 // If the input array is too big, split it into chunks
784 $maxcoursesinquery = 20;
785 if (count($courseusers) > $maxcoursesinquery) {
786 $rv = array();
787 for ($offset = 0; $offset < count($courseusers); $offset += $maxcoursesinquery) {
788 $chunk = array_slice($courseusers, $offset, $maxcoursesinquery, true);
789 $rv = $rv + self::ensure_users_enrolled($chunk);
790 }
791 return $rv;
792 }
793
794 // create a query verifying valid user enrolments for the number of courses
795 $sql = "SELECT DISTINCT e.courseid, ue.userid
796 FROM {user_enrolments} ue
797 JOIN {enrol} e ON e.id = ue.enrolid
798 WHERE ue.status = :active
799 AND e.status = :enabled
800 AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
801 $now = round(time(), -2); // rounding helps caching in DB
802 $params = array('enabled' => ENROL_INSTANCE_ENABLED,
803 'active' => ENROL_USER_ACTIVE,
804 'now1' => $now, 'now2' => $now);
805 $cnt = 0;
806 $subsqls = array();
807 $enrolled = array();
808 foreach ($courseusers as $id => $userids) {
809 $enrolled[$id] = array();
810 if (count($userids)) {
811 list($sql2, $params2) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid'.$cnt.'_');
812 $subsqls[] = "(e.courseid = :courseid$cnt AND ue.userid ".$sql2.")";
813 $params = $params + array('courseid'.$cnt => $id) + $params2;
814 $cnt++;
815 }
816 }
817 if (count($subsqls)) {
818 $sql .= "AND (". join(' OR ', $subsqls).")";
819 $rs = $DB->get_recordset_sql($sql, $params);
820 foreach ($rs as $record) {
821 $enrolled[$record->courseid][] = $record->userid;
822 }
823 $rs->close();
93c544bd 824 }
31b0530a 825 return $enrolled;
93c544bd
MG
826 }
827
828 /**
829 * Retrieves number of records from course table
830 *
831 * Not all fields are retrieved. Records are ready for preloading context
832 *
833 * @param string $whereclause
834 * @param array $params
835 * @param array $options may indicate that summary and/or coursecontacts need to be retrieved
836 * @param bool $checkvisibility if true, capability 'moodle/course:viewhiddencourses' will be checked
837 * on not visible courses
838 * @return array array of stdClass objects
839 */
840 protected static function get_course_records($whereclause, $params, $options, $checkvisibility = false) {
841 global $DB;
842 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
843 $fields = array('c.id', 'c.category', 'c.sortorder',
844 'c.shortname', 'c.fullname', 'c.idnumber',
4a3fb71c 845 'c.startdate', 'c.visible', 'c.cacherev');
93c544bd
MG
846 if (!empty($options['summary'])) {
847 $fields[] = 'c.summary';
848 $fields[] = 'c.summaryformat';
849 } else {
d0ed33d6 850 $fields[] = $DB->sql_substr('c.summary', 1, 1). ' as hassummary';
93c544bd
MG
851 }
852 $sql = "SELECT ". join(',', $fields). ", $ctxselect
853 FROM {course} c
854 JOIN {context} ctx ON c.id = ctx.instanceid AND ctx.contextlevel = :contextcourse
855 WHERE ". $whereclause." ORDER BY c.sortorder";
856 $list = $DB->get_records_sql($sql,
857 array('contextcourse' => CONTEXT_COURSE) + $params);
858
859 if ($checkvisibility) {
860 // Loop through all records and make sure we only return the courses accessible by user.
861 foreach ($list as $course) {
a32f163d
MG
862 if (isset($list[$course->id]->hassummary)) {
863 $list[$course->id]->hassummary = strlen($list[$course->id]->hassummary) > 0;
864 }
93c544bd
MG
865 if (empty($course->visible)) {
866 // load context only if we need to check capability
867 context_helper::preload_from_record($course);
868 if (!has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
869 unset($list[$course->id]);
870 }
871 }
872 }
873 }
874
875 // preload course contacts if necessary
876 if (!empty($options['coursecontacts'])) {
877 self::preload_course_contacts($list);
878 }
879 return $list;
880 }
881
eabbfa82
MG
882 /**
883 * Returns array of ids of children categories that current user can not see
884 *
885 * This data is cached in user session cache
886 *
887 * @return array
888 */
889 protected function get_not_visible_children_ids() {
890 global $DB;
891 $coursecatcache = cache::make('core', 'coursecat');
892 if (($invisibleids = $coursecatcache->get('ic'. $this->id)) === false) {
893 // we never checked visible children before
894 $hidden = self::get_tree($this->id.'i');
895 $invisibleids = array();
896 if ($hidden) {
897 // preload categories contexts
898 list($sql, $params) = $DB->get_in_or_equal($hidden, SQL_PARAMS_NAMED, 'id');
899 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
900 $contexts = $DB->get_records_sql("SELECT $ctxselect FROM {context} ctx
901 WHERE ctx.contextlevel = :contextcoursecat AND ctx.instanceid ".$sql,
902 array('contextcoursecat' => CONTEXT_COURSECAT) + $params);
903 foreach ($contexts as $record) {
904 context_helper::preload_from_record($record);
905 }
906 // check that user has 'viewhiddencategories' capability for each hidden category
907 foreach ($hidden as $id) {
908 if (!has_capability('moodle/category:viewhiddencategories', context_coursecat::instance($id))) {
909 $invisibleids[] = $id;
910 }
911 }
912 }
913 $coursecatcache->set('ic'. $this->id, $invisibleids);
914 }
915 return $invisibleids;
916 }
917
918 /**
93c544bd 919 * Sorts list of records by several fields
eabbfa82 920 *
93c544bd 921 * @param array $records array of stdClass objects
eabbfa82
MG
922 * @param array $sortfields assoc array where key is the field to sort and value is 1 for asc or -1 for desc
923 * @return int
924 */
93c544bd
MG
925 protected static function sort_records(&$records, $sortfields) {
926 if (empty($records)) {
927 return;
928 }
929 // If sorting by course display name, calculate it (it may be fullname or shortname+fullname)
930 if (array_key_exists('displayname', $sortfields)) {
931 foreach ($records as $key => $record) {
932 if (!isset($record->displayname)) {
933 $records[$key]->displayname = get_course_display_name_for_list($record);
eabbfa82 934 }
93c544bd
MG
935 }
936 }
2f1e464a 937 // sorting by one field - use core_collator
93c544bd
MG
938 if (count($sortfields) == 1) {
939 $property = key($sortfields);
940 if (in_array($property, array('sortorder', 'id', 'visible', 'parent', 'depth'))) {
2f1e464a 941 $sortflag = core_collator::SORT_NUMERIC;
93c544bd 942 } else if (in_array($property, array('idnumber', 'displayname', 'name', 'shortname', 'fullname'))) {
2f1e464a 943 $sortflag = core_collator::SORT_STRING;
eabbfa82 944 } else {
2f1e464a 945 $sortflag = core_collator::SORT_REGULAR;
93c544bd 946 }
2f1e464a 947 core_collator::asort_objects_by_property($records, $property, $sortflag);
93c544bd
MG
948 if ($sortfields[$property] < 0) {
949 $records = array_reverse($records, true);
950 }
951 return;
952 }
15f89e28 953 $records = coursecat_sortable_records::sort($records, $sortfields);
b33389d2
MG
954 }
955
956 /**
957 * Returns array of children categories visible to the current user
958 *
eabbfa82
MG
959 * @param array $options options for retrieving children
960 * - sort - list of fields to sort. Example
961 * array('idnumber' => 1, 'name' => 1, 'id' => -1)
962 * will sort by idnumber asc, name asc and id desc.
963 * Default: array('sortorder' => 1)
964 * Only cached fields may be used for sorting!
965 * - offset
966 * - limit - maximum number of children to return, 0 or null for no limit
b33389d2
MG
967 * @return array of coursecat objects indexed by category id
968 */
eabbfa82
MG
969 public function get_children($options = array()) {
970 global $DB;
971 $coursecatcache = cache::make('core', 'coursecat');
972
973 // get default values for options
974 if (!empty($options['sort']) && is_array($options['sort'])) {
975 $sortfields = $options['sort'];
976 } else {
977 $sortfields = array('sortorder' => 1);
978 }
979 $limit = null;
980 if (!empty($options['limit']) && (int)$options['limit']) {
981 $limit = (int)$options['limit'];
982 }
983 $offset = 0;
984 if (!empty($options['offset']) && (int)$options['offset']) {
985 $offset = (int)$options['offset'];
986 }
987
988 // first retrieve list of user-visible and sorted children ids from cache
989 $sortedids = $coursecatcache->get('c'. $this->id. ':'. serialize($sortfields));
990 if ($sortedids === false) {
991 $sortfieldskeys = array_keys($sortfields);
992 if ($sortfieldskeys[0] === 'sortorder') {
993 // no DB requests required to build the list of ids sorted by sortorder.
994 // We can easily ignore other sort fields because sortorder is always different
995 $sortedids = self::get_tree($this->id);
996 if ($sortedids && ($invisibleids = $this->get_not_visible_children_ids())) {
997 $sortedids = array_diff($sortedids, $invisibleids);
998 if ($sortfields['sortorder'] == -1) {
999 $sortedids = array_reverse($sortedids, true);
1000 }
b33389d2 1001 }
eabbfa82
MG
1002 } else {
1003 // we need to retrieve and sort all children. Good thing that it is done only on first request
1004 if ($invisibleids = $this->get_not_visible_children_ids()) {
1005 list($sql, $params) = $DB->get_in_or_equal($invisibleids, SQL_PARAMS_NAMED, 'id', false);
1006 $records = self::get_records('cc.parent = :parent AND cc.id '. $sql,
1007 array('parent' => $this->id) + $params);
1008 } else {
1009 $records = self::get_records('cc.parent = :parent', array('parent' => $this->id));
1010 }
93c544bd 1011 self::sort_records($records, $sortfields);
eabbfa82
MG
1012 $sortedids = array_keys($records);
1013 }
1014 $coursecatcache->set('c'. $this->id. ':'.serialize($sortfields), $sortedids);
1015 }
1016
1017 if (empty($sortedids)) {
1018 return array();
1019 }
1020
1021 // now retrieive and return categories
1022 if ($offset || $limit) {
1023 $sortedids = array_slice($sortedids, $offset, $limit);
1024 }
1025 if (isset($records)) {
1026 // easy, we have already retrieved records
1027 if ($offset || $limit) {
1028 $records = array_slice($records, $offset, $limit, true);
1029 }
1030 } else {
1031 list($sql, $params) = $DB->get_in_or_equal($sortedids, SQL_PARAMS_NAMED, 'id');
1032 $records = self::get_records('cc.id '. $sql,
1033 array('parent' => $this->id) + $params);
1034 }
1035
1036 $rv = array();
1037 foreach ($sortedids as $id) {
1038 if (isset($records[$id])) {
1039 $rv[$id] = new coursecat($records[$id]);
b33389d2
MG
1040 }
1041 }
1042 return $rv;
1043 }
1044
eabbfa82
MG
1045 /**
1046 * Returns number of subcategories visible to the current user
1047 *
1048 * @return int
1049 */
1050 public function get_children_count() {
1051 $sortedids = self::get_tree($this->id);
1052 $invisibleids = $this->get_not_visible_children_ids();
1053 return count($sortedids) - count($invisibleids);
1054 }
1055
b33389d2
MG
1056 /**
1057 * Returns true if the category has ANY children, including those not visible to the user
1058 *
1059 * @return boolean
1060 */
1061 public function has_children() {
eabbfa82
MG
1062 $allchildren = self::get_tree($this->id);
1063 return !empty($allchildren);
b33389d2
MG
1064 }
1065
1066 /**
1067 * Returns true if the category has courses in it (count does not include courses
1068 * in child categories)
1069 *
1070 * @return bool
1071 */
1072 public function has_courses() {
1073 global $DB;
1074 return $DB->record_exists_sql("select 1 from {course} where category = ?",
1075 array($this->id));
1076 }
1077
93c544bd
MG
1078 /**
1079 * Searches courses
1080 *
1081 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1082 * to this when somebody edits courses or categories, however it is very
1083 * difficult to keep track of all possible changes that may affect list of courses.
1084 *
1085 * @param array $search contains search criterias, such as:
1086 * - search - search string
1087 * - blocklist - id of block (if we are searching for courses containing specific block0
1088 * - modulelist - name of module (if we are searching for courses containing specific module
1089 * - tagid - id of tag
1090 * @param array $options display options, same as in get_courses() except 'recursive' is ignored - search is always category-independent
85708da6 1091 * @return course_in_list[]
93c544bd
MG
1092 */
1093 public static function search_courses($search, $options = array()) {
1094 global $DB;
1095 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1096 $limit = !empty($options['limit']) ? $options['limit'] : null;
1097 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1098
1099 $coursecatcache = cache::make('core', 'coursecat');
1100 $cachekey = 's-'. serialize($search + array('sort' => $sortfields));
1101 $cntcachekey = 'scnt-'. serialize($search);
1102
1103 $ids = $coursecatcache->get($cachekey);
1104 if ($ids !== false) {
1105 // we already cached last search result
1106 $ids = array_slice($ids, $offset, $limit);
1107 $courses = array();
1108 if (!empty($ids)) {
1109 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1110 $records = self::get_course_records("c.id ". $sql, $params, $options);
1111 foreach ($ids as $id) {
1112 $courses[$id] = new course_in_list($records[$id]);
1113 }
1114 }
1115 return $courses;
1116 }
1117
1118 $preloadcoursecontacts = !empty($options['coursecontacts']);
1119 unset($options['coursecontacts']);
1120
1121 if (!empty($search['search'])) {
1122 // search courses that have specified words in their names/summaries
1123 $searchterms = preg_split('|\s+|', trim($search['search']), 0, PREG_SPLIT_NO_EMPTY);
15f89e28 1124 $searchterms = array_filter($searchterms, create_function('$v', 'return strlen($v) > 1;'));
93c544bd
MG
1125 $courselist = get_courses_search($searchterms, 'c.sortorder ASC', 0, 9999999, $totalcount);
1126 self::sort_records($courselist, $sortfields);
1127 $coursecatcache->set($cachekey, array_keys($courselist));
1128 $coursecatcache->set($cntcachekey, $totalcount);
1129 $records = array_slice($courselist, $offset, $limit, true);
1130 } else {
1131 if (!empty($search['blocklist'])) {
1132 // search courses that have block with specified id
1133 $blockname = $DB->get_field('block', 'name', array('id' => $search['blocklist']));
1134 $where = 'ctx.id in (SELECT distinct bi.parentcontextid FROM {block_instances} bi
1135 WHERE bi.blockname = :blockname)';
1136 $params = array('blockname' => $blockname);
1137 } else if (!empty($search['modulelist'])) {
1138 // search courses that have module with specified name
1139 $where = "c.id IN (SELECT DISTINCT module.course ".
1140 "FROM {".$search['modulelist']."} module)";
1141 $params = array();
1142 } else if (!empty($search['tagid'])) {
1143 // search courses that are tagged with the specified tag
1144 $where = "c.id IN (SELECT t.itemid ".
1145 "FROM {tag_instance} t WHERE t.tagid = :tagid AND t.itemtype = :itemtype)";
1146 $params = array('tagid' => $search['tagid'], 'itemtype' => 'course');
1147 } else {
1148 debugging('No criteria is specified while searching courses', DEBUG_DEVELOPER);
1149 return array();
1150 }
1151 $courselist = self::get_course_records($where, $params, $options, true);
1152 self::sort_records($courselist, $sortfields);
1153 $coursecatcache->set($cachekey, array_keys($courselist));
1154 $coursecatcache->set($cntcachekey, count($courselist));
1155 $records = array_slice($courselist, $offset, $limit, true);
1156 }
1157
1158 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1159 if (!empty($preloadcoursecontacts)) {
1160 self::preload_course_contacts($records);
1161 }
1162 $courses = array();
1163 foreach ($records as $record) {
1164 $courses[$record->id] = new course_in_list($record);
1165 }
1166 return $courses;
1167 }
1168
1169 /**
1170 * Returns number of courses in the search results
1171 *
1172 * It is recommended to call this function after {@link coursecat::search_courses()}
1173 * and not before because only course ids are cached. Otherwise search_courses() may
1174 * perform extra DB queries.
1175 *
1176 * @param array $search search criteria, see method search_courses() for more details
1177 * @param array $options display options. They do not affect the result but
1178 * the 'sort' property is used in cache key for storing list of course ids
1179 * @return int
1180 */
1181 public static function search_courses_count($search, $options = array()) {
1182 $coursecatcache = cache::make('core', 'coursecat');
1183 $cntcachekey = 'scnt-'. serialize($search);
1184 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
6b0b05b3
MG
1185 // Cached value not found. Retrieve ALL courses and return their count.
1186 unset($options['offset']);
1187 unset($options['limit']);
1188 unset($options['summary']);
1189 unset($options['coursecontacts']);
1190 $courses = self::search_courses($search, $options);
1191 $cnt = count($courses);
93c544bd
MG
1192 }
1193 return $cnt;
1194 }
1195
1196 /**
1197 * Retrieves the list of courses accessible by user
1198 *
1199 * Not all information is cached, try to avoid calling this method
1200 * twice in the same request.
1201 *
1202 * The following fields are always retrieved:
1203 * - id, visible, fullname, shortname, idnumber, category, sortorder
1204 *
1205 * If you plan to use properties/methods course_in_list::$summary and/or
1206 * course_in_list::get_course_contacts()
1207 * you can preload this information using appropriate 'options'. Otherwise
1208 * they will be retrieved from DB on demand and it may end with bigger DB load.
1209 *
1210 * Note that method course_in_list::has_summary() will not perform additional
1211 * DB queries even if $options['summary'] is not specified
1212 *
1213 * List of found course ids is cached for 10 minutes. Cache may be purged prior
1214 * to this when somebody edits courses or categories, however it is very
1215 * difficult to keep track of all possible changes that may affect list of courses.
1216 *
1217 * @param array $options options for retrieving children
1218 * - recursive - return courses from subcategories as well. Use with care,
1219 * this may be a huge list!
1220 * - summary - preloads fields 'summary' and 'summaryformat'
1221 * - coursecontacts - preloads course contacts
1222 * - sort - list of fields to sort. Example
1223 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
1224 * will sort by idnumber asc, shortname asc and id desc.
1225 * Default: array('sortorder' => 1)
1226 * Only cached fields may be used for sorting!
1227 * - offset
1228 * - limit - maximum number of children to return, 0 or null for no limit
85708da6 1229 * @return course_in_list[]
93c544bd
MG
1230 */
1231 public function get_courses($options = array()) {
1232 global $DB;
1233 $recursive = !empty($options['recursive']);
1234 $offset = !empty($options['offset']) ? $options['offset'] : 0;
1235 $limit = !empty($options['limit']) ? $options['limit'] : null;
1236 $sortfields = !empty($options['sort']) ? $options['sort'] : array('sortorder' => 1);
1237
1238 // Check if this category is hidden.
1239 // Also 0-category never has courses unless this is recursive call.
1240 if (!$this->is_uservisible() || (!$this->id && !$recursive)) {
1241 return array();
1242 }
1243
1244 $coursecatcache = cache::make('core', 'coursecat');
1245 $cachekey = 'l-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '').
1246 '-'. serialize($sortfields);
1247 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1248
1249 // check if we have already cached results
1250 $ids = $coursecatcache->get($cachekey);
1251 if ($ids !== false) {
1252 // we already cached last search result and it did not expire yet
1253 $ids = array_slice($ids, $offset, $limit);
1254 $courses = array();
1255 if (!empty($ids)) {
1256 list($sql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'id');
1257 $records = self::get_course_records("c.id ". $sql, $params, $options);
1258 foreach ($ids as $id) {
1259 $courses[$id] = new course_in_list($records[$id]);
1260 }
1261 }
1262 return $courses;
1263 }
1264
1265 // retrieve list of courses in category
1266 $where = 'c.id <> :siteid';
1267 $params = array('siteid' => SITEID);
1268 if ($recursive) {
1269 if ($this->id) {
5db8f5a8 1270 $context = context_coursecat::instance($this->id);
93c544bd
MG
1271 $where .= ' AND ctx.path like :path';
1272 $params['path'] = $context->path. '/%';
1273 }
1274 } else {
1275 $where .= ' AND c.category = :categoryid';
1276 $params['categoryid'] = $this->id;
1277 }
1278 // get list of courses without preloaded coursecontacts because we don't need them for every course
1279 $list = $this->get_course_records($where, $params, array_diff_key($options, array('coursecontacts' => 1)), true);
1280
1281 // sort and cache list
1282 self::sort_records($list, $sortfields);
1283 $coursecatcache->set($cachekey, array_keys($list));
1284 $coursecatcache->set($cntcachekey, count($list));
1285
1286 // Apply offset/limit, convert to course_in_list and return.
1287 $courses = array();
1288 if (isset($list)) {
1289 if ($offset || $limit) {
1290 $list = array_slice($list, $offset, $limit, true);
1291 }
1292 // Preload course contacts if necessary - saves DB queries later to do it for each course separately.
1293 if (!empty($options['coursecontacts'])) {
1294 self::preload_course_contacts($list);
1295 }
1296 foreach ($list as $record) {
1297 $courses[$record->id] = new course_in_list($record);
1298 }
1299 }
1300 return $courses;
1301 }
1302
1303 /**
1304 * Returns number of courses visible to the user
1305 *
1306 * @param array $options similar to get_courses() except some options do not affect
1307 * number of courses (i.e. sort, summary, offset, limit etc.)
1308 * @return int
1309 */
1310 public function get_courses_count($options = array()) {
1311 $cntcachekey = 'lcnt-'. $this->id. '-'. (!empty($options['recursive']) ? 'r' : '');
1312 $coursecatcache = cache::make('core', 'coursecat');
1313 if (($cnt = $coursecatcache->get($cntcachekey)) === false) {
6b0b05b3
MG
1314 // Cached value not found. Retrieve ALL courses and return their count.
1315 unset($options['offset']);
1316 unset($options['limit']);
1317 unset($options['summary']);
1318 unset($options['coursecontacts']);
1319 $courses = $this->get_courses($options);
1320 $cnt = count($courses);
93c544bd
MG
1321 }
1322 return $cnt;
1323 }
1324
b33389d2
MG
1325 /**
1326 * Returns true if user can delete current category and all its contents
1327 *
1328 * To be able to delete course category the user must have permission
1329 * 'moodle/category:manage' in ALL child course categories AND
1330 * be able to delete all courses
1331 *
1332 * @return bool
1333 */
1334 public function can_delete_full() {
1335 global $DB;
1336 if (!$this->id) {
1337 // fool-proof
1338 return false;
1339 }
1340
1341 $context = context_coursecat::instance($this->id);
1342 if (!$this->is_uservisible() ||
1343 !has_capability('moodle/category:manage', $context)) {
1344 return false;
1345 }
1346
15d50fff
MG
1347 // Check all child categories (not only direct children)
1348 $sql = context_helper::get_preload_record_columns_sql('ctx');
1349 $childcategories = $DB->get_records_sql('SELECT c.id, c.visible, '. $sql.
1350 ' FROM {context} ctx '.
1351 ' JOIN {course_categories} c ON c.id = ctx.instanceid'.
1352 ' WHERE ctx.path like ? AND ctx.contextlevel = ?',
1353 array($context->path. '/%', CONTEXT_COURSECAT));
1354 foreach ($childcategories as $childcat) {
1355 context_helper::preload_from_record($childcat);
1356 $childcontext = context_coursecat::instance($childcat->id);
1357 if ((!$childcat->visible && !has_capability('moodle/category:viewhiddencategories', $childcontext)) ||
1358 !has_capability('moodle/category:manage', $childcontext)) {
1359 return false;
b33389d2
MG
1360 }
1361 }
1362
1363 // Check courses
15d50fff
MG
1364 $sql = context_helper::get_preload_record_columns_sql('ctx');
1365 $coursescontexts = $DB->get_records_sql('SELECT ctx.instanceid AS courseid, '.
1366 $sql. ' FROM {context} ctx '.
1367 'WHERE ctx.path like :pathmask and ctx.contextlevel = :courselevel',
b33389d2
MG
1368 array('pathmask' => $context->path. '/%',
1369 'courselevel' => CONTEXT_COURSE));
15d50fff
MG
1370 foreach ($coursescontexts as $ctxrecord) {
1371 context_helper::preload_from_record($ctxrecord);
1372 if (!can_delete_course($ctxrecord->courseid)) {
b33389d2
MG
1373 return false;
1374 }
1375 }
1376
1377 return true;
1378 }
1379
1380 /**
1381 * Recursively delete category including all subcategories and courses
1382 *
1383 * Function {@link coursecat::can_delete_full()} MUST be called prior
1384 * to calling this function because there is no capability check
1385 * inside this function
1386 *
1387 * @param boolean $showfeedback display some notices
1388 * @return array return deleted courses
1389 */
15d50fff 1390 public function delete_full($showfeedback = true) {
b33389d2 1391 global $CFG, $DB;
f326c5b4 1392
b33389d2
MG
1393 require_once($CFG->libdir.'/gradelib.php');
1394 require_once($CFG->libdir.'/questionlib.php');
1395 require_once($CFG->dirroot.'/cohort/lib.php');
1396
1397 $deletedcourses = array();
1398
1399 // Get children. Note, we don't want to use cache here because
1400 // it would be rebuilt too often
1401 $children = $DB->get_records('course_categories', array('parent' => $this->id), 'sortorder ASC');
1402 foreach ($children as $record) {
1403 $coursecat = new coursecat($record);
1404 $deletedcourses += $coursecat->delete_full($showfeedback);
1405 }
1406
1407 if ($courses = $DB->get_records('course', array('category' => $this->id), 'sortorder ASC')) {
1408 foreach ($courses as $course) {
1409 if (!delete_course($course, false)) {
1410 throw new moodle_exception('cannotdeletecategorycourse', '', '', $course->shortname);
1411 }
1412 $deletedcourses[] = $course;
1413 }
1414 }
1415
1416 // move or delete cohorts in this context
1417 cohort_delete_category($this);
1418
1419 // now delete anything that may depend on course category context
1420 grade_course_category_delete($this->id, 0, $showfeedback);
1421 if (!question_delete_course_category($this, 0, $showfeedback)) {
1422 throw new moodle_exception('cannotdeletecategoryquestions', '', '', $this->get_formatted_name());
1423 }
1424
1425 // finally delete the category and it's context
1426 $DB->delete_records('course_categories', array('id' => $this->id));
f326c5b4
MN
1427
1428 $coursecatcontext = context_coursecat::instance($this->id);
1429 $coursecatcontext->delete();
b33389d2 1430
eabbfa82 1431 cache_helper::purge_by_event('changesincoursecat');
b33389d2 1432
f326c5b4
MN
1433 // Trigger a course category deleted event.
1434 $event = \core\event\course_category_deleted::create(array(
1435 'objectid' => $this->id,
1436 'context' => $coursecatcontext,
1437 'other' => array('name' => $this->name)
1438 ));
1439 $event->set_legacy_eventdata($this);
1440 $event->trigger();
b33389d2
MG
1441
1442 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1443 if ($this->id == $CFG->defaultrequestcategory) {
1444 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1445 }
1446 return $deletedcourses;
1447 }
1448
1449 /**
1450 * Checks if user can delete this category and move content (courses, subcategories and questions)
1451 * to another category. If yes returns the array of possible target categories names
1452 *
1453 * If user can not manage this category or it is completely empty - empty array will be returned
1454 *
1455 * @return array
1456 */
1457 public function move_content_targets_list() {
1458 global $CFG;
1459 require_once($CFG->libdir . '/questionlib.php');
1460 $context = context_coursecat::instance($this->id);
1461 if (!$this->is_uservisible() ||
1462 !has_capability('moodle/category:manage', $context)) {
1463 // User is not able to manage current category, he is not able to delete it.
1464 // No possible target categories.
1465 return array();
1466 }
1467
1468 $testcaps = array();
1469 // If this category has courses in it, user must have 'course:create' capability in target category.
1470 if ($this->has_courses()) {
1471 $testcaps[] = 'moodle/course:create';
1472 }
1473 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1474 if ($this->has_children() || question_context_has_any_questions($context)) {
1475 $testcaps[] = 'moodle/category:manage';
1476 }
1477 if (!empty($testcaps)) {
1478 // return list of categories excluding this one and it's children
1479 return self::make_categories_list($testcaps, $this->id);
1480 }
1481
1482 // Category is completely empty, no need in target for contents.
1483 return array();
1484 }
1485
1486 /**
1487 * Checks if user has capability to move all category content to the new parent before
1488 * removing this category
1489 *
1490 * @param int $newcatid
1491 * @return bool
1492 */
1493 public function can_move_content_to($newcatid) {
1494 global $CFG;
1495 require_once($CFG->libdir . '/questionlib.php');
1496 $context = context_coursecat::instance($this->id);
1497 if (!$this->is_uservisible() ||
1498 !has_capability('moodle/category:manage', $context)) {
1499 return false;
1500 }
1501 $testcaps = array();
1502 // If this category has courses in it, user must have 'course:create' capability in target category.
1503 if ($this->has_courses()) {
1504 $testcaps[] = 'moodle/course:create';
1505 }
1506 // If this category has subcategories or questions, user must have 'category:manage' capability in target category.
1507 if ($this->has_children() || question_context_has_any_questions($context)) {
1508 $testcaps[] = 'moodle/category:manage';
1509 }
1510 if (!empty($testcaps)) {
1511 return has_all_capabilities($testcaps, context_coursecat::instance($newcatid));
1512 }
1513
1514 // there is no content but still return true
1515 return true;
1516 }
1517
1518 /**
1519 * Deletes a category and moves all content (children, courses and questions) to the new parent
1520 *
1521 * Note that this function does not check capabilities, {@link coursecat::can_move_content_to()}
1522 * must be called prior
1523 *
1524 * @param int $newparentid
1525 * @param bool $showfeedback
1526 * @return bool
1527 */
1528 public function delete_move($newparentid, $showfeedback = false) {
1529 global $CFG, $DB, $OUTPUT;
f326c5b4 1530
b33389d2
MG
1531 require_once($CFG->libdir.'/gradelib.php');
1532 require_once($CFG->libdir.'/questionlib.php');
1533 require_once($CFG->dirroot.'/cohort/lib.php');
1534
1535 // get all objects and lists because later the caches will be reset so
1536 // we don't need to make extra queries
1537 $newparentcat = self::get($newparentid, MUST_EXIST, true);
1538 $catname = $this->get_formatted_name();
1539 $children = $this->get_children();
1540 $coursesids = $DB->get_fieldset_select('course', 'id', 'category = :category ORDER BY sortorder ASC', array('category' => $this->id));
1541 $context = context_coursecat::instance($this->id);
1542
1543 if ($children) {
1544 foreach ($children as $childcat) {
15d50fff 1545 $childcat->change_parent_raw($newparentcat);
b33389d2
MG
1546 // Log action.
1547 add_to_log(SITEID, "category", "move", "editcategory.php?id=$childcat->id", $childcat->id);
1548 }
1549 fix_course_sortorder();
1550 }
1551
1552 if ($coursesids) {
1553 if (!move_courses($coursesids, $newparentid)) {
1554 if ($showfeedback) {
1555 echo $OUTPUT->notification("Error moving courses");
1556 }
1557 return false;
1558 }
1559 if ($showfeedback) {
1560 echo $OUTPUT->notification(get_string('coursesmovedout', '', $catname), 'notifysuccess');
1561 }
1562 }
1563
1564 // move or delete cohorts in this context
1565 cohort_delete_category($this);
1566
1567 // now delete anything that may depend on course category context
1568 grade_course_category_delete($this->id, $newparentid, $showfeedback);
1569 if (!question_delete_course_category($this, $newparentcat, $showfeedback)) {
1570 if ($showfeedback) {
1571 echo $OUTPUT->notification(get_string('errordeletingquestionsfromcategory', 'question', $catname), 'notifysuccess');
1572 }
1573 return false;
1574 }
1575
1576 // finally delete the category and it's context
1577 $DB->delete_records('course_categories', array('id' => $this->id));
1578 $context->delete();
b33389d2 1579
f326c5b4
MN
1580 // Trigger a course category deleted event.
1581 $event = \core\event\course_category_deleted::create(array(
1582 'objectid' => $this->id,
1583 'context' => $context,
1584 'other' => array('name' => $this->name)
1585 ));
1586 $event->set_legacy_eventdata($this);
1587 $event->trigger();
b33389d2 1588
eabbfa82 1589 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1590
1591 if ($showfeedback) {
1592 echo $OUTPUT->notification(get_string('coursecategorydeleted', '', $catname), 'notifysuccess');
1593 }
1594
1595 // If we deleted $CFG->defaultrequestcategory, make it point somewhere else.
1596 if ($this->id == $CFG->defaultrequestcategory) {
1597 set_config('defaultrequestcategory', $DB->get_field('course_categories', 'MIN(id)', array('parent' => 0)));
1598 }
1599 return true;
1600 }
1601
1602 /**
1603 * Checks if user can move current category to the new parent
1604 *
1605 * This checks if new parent category exists, user has manage cap there
1606 * and new parent is not a child of this category
1607 *
1608 * @param int|stdClass|coursecat $newparentcat
1609 * @return bool
1610 */
1611 public function can_change_parent($newparentcat) {
1612 if (!has_capability('moodle/category:manage', context_coursecat::instance($this->id))) {
1613 return false;
1614 }
1615 if (is_object($newparentcat)) {
1616 $newparentcat = self::get($newparentcat->id, IGNORE_MISSING);
1617 } else {
1618 $newparentcat = self::get((int)$newparentcat, IGNORE_MISSING);
1619 }
1620 if (!$newparentcat) {
1621 return false;
1622 }
15d50fff 1623 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
b33389d2
MG
1624 // can not move to itself or it's own child
1625 return false;
1626 }
5db8f5a8
MG
1627 if ($newparentcat->id) {
1628 return has_capability('moodle/category:manage', context_coursecat::instance($newparentcat->id));
1629 } else {
1630 return has_capability('moodle/category:manage', context_system::instance());
1631 }
b33389d2
MG
1632 }
1633
1634 /**
1635 * Moves the category under another parent category. All associated contexts are moved as well
1636 *
1637 * This is protected function, use change_parent() or update() from outside of this class
1638 *
1639 * @see coursecat::change_parent()
1640 * @see coursecat::update()
1641 *
1642 * @param coursecat $newparentcat
1643 */
15d50fff 1644 protected function change_parent_raw(coursecat $newparentcat) {
b33389d2
MG
1645 global $DB;
1646
1647 $context = context_coursecat::instance($this->id);
1648
1649 $hidecat = false;
1650 if (empty($newparentcat->id)) {
1651 $DB->set_field('course_categories', 'parent', 0, array('id' => $this->id));
1652 $newparent = context_system::instance();
1653 } else {
15d50fff 1654 if ($newparentcat->id == $this->id || in_array($this->id, $newparentcat->get_parents())) {
b33389d2
MG
1655 // can not move to itself or it's own child
1656 throw new moodle_exception('cannotmovecategory');
1657 }
1658 $DB->set_field('course_categories', 'parent', $newparentcat->id, array('id' => $this->id));
1659 $newparent = context_coursecat::instance($newparentcat->id);
1660
1661 if (!$newparentcat->visible and $this->visible) {
1662 // better hide category when moving into hidden category, teachers may unhide afterwards and the hidden children will be restored properly
1663 $hidecat = true;
1664 }
1665 }
1666 $this->parent = $newparentcat->id;
1667
9c6cfc08 1668 $context->update_moved($newparent);
b33389d2
MG
1669
1670 // now make it last in new category
1671 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('id' => $this->id));
1672
1673 if ($hidecat) {
1674 fix_course_sortorder();
1675 $this->restore();
1676 // Hide object but store 1 in visibleold, because when parent category visibility changes this category must become visible again.
15d50fff 1677 $this->hide_raw(1);
b33389d2
MG
1678 }
1679 }
1680
1681 /**
1682 * Efficiently moves a category - NOTE that this can have
1683 * a huge impact access-control-wise...
1684 *
1685 * Note that this function does not check capabilities.
1686 *
1687 * Example of usage:
1688 * $coursecat = coursecat::get($categoryid);
1689 * if ($coursecat->can_change_parent($newparentcatid)) {
1690 * $coursecat->change_parent($newparentcatid);
1691 * }
1692 *
1693 * This function does not update field course_categories.timemodified
1694 * If you want to update timemodified, use
1695 * $coursecat->update(array('parent' => $newparentcat));
1696 *
1697 * @param int|stdClass|coursecat $newparentcat
1698 */
1699 public function change_parent($newparentcat) {
1700 // Make sure parent category exists but do not check capabilities here that it is visible to current user.
1701 if (is_object($newparentcat)) {
1702 $newparentcat = self::get($newparentcat->id, MUST_EXIST, true);
1703 } else {
1704 $newparentcat = self::get((int)$newparentcat, MUST_EXIST, true);
1705 }
1706 if ($newparentcat->id != $this->parent) {
15d50fff 1707 $this->change_parent_raw($newparentcat);
b33389d2 1708 fix_course_sortorder();
eabbfa82 1709 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1710 $this->restore();
1711 add_to_log(SITEID, "category", "move", "editcategory.php?id=$this->id", $this->id);
1712 }
1713 }
1714
1715 /**
1716 * Hide course category and child course and subcategories
1717 *
1718 * If this category has changed the parent and is moved under hidden
1719 * category we will want to store it's current visibility state in
1720 * the field 'visibleold'. If admin clicked 'hide' for this particular
1721 * category, the field 'visibleold' should become 0.
1722 *
1723 * All subcategories and courses will have their current visibility in the field visibleold
1724 *
1725 * This is protected function, use hide() or update() from outside of this class
1726 *
1727 * @see coursecat::hide()
1728 * @see coursecat::update()
1729 *
1730 * @param int $visibleold value to set in field $visibleold for this category
1731 * @return bool whether changes have been made and caches need to be purged afterwards
1732 */
15d50fff 1733 protected function hide_raw($visibleold = 0) {
b33389d2
MG
1734 global $DB;
1735 $changes = false;
1736
15d50fff
MG
1737 // Note that field 'visibleold' is not cached so we must retrieve it from DB if it is missing
1738 if ($this->id && $this->__get('visibleold') != $visibleold) {
b33389d2
MG
1739 $this->visibleold = $visibleold;
1740 $DB->set_field('course_categories', 'visibleold', $visibleold, array('id' => $this->id));
1741 $changes = true;
1742 }
1743 if (!$this->visible || !$this->id) {
1744 // already hidden or can not be hidden
1745 return $changes;
1746 }
1747
1748 $this->visible = 0;
1749 $DB->set_field('course_categories', 'visible', 0, array('id'=>$this->id));
1750 $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
1751 $DB->set_field('course', 'visible', 0, array('category' => $this->id));
1752 // get all child categories and hide too
1753 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visible')) {
1754 foreach ($subcats as $cat) {
1755 $DB->set_field('course_categories', 'visibleold', $cat->visible, array('id' => $cat->id));
1756 $DB->set_field('course_categories', 'visible', 0, array('id' => $cat->id));
1757 $DB->execute("UPDATE {course} SET visibleold = visible WHERE category = ?", array($cat->id));
1758 $DB->set_field('course', 'visible', 0, array('category' => $cat->id));
1759 }
1760 }
1761 return true;
1762 }
1763
1764 /**
1765 * Hide course category and child course and subcategories
1766 *
1767 * Note that there is no capability check inside this function
1768 *
1769 * This function does not update field course_categories.timemodified
1770 * If you want to update timemodified, use
1771 * $coursecat->update(array('visible' => 0));
1772 */
1773 public function hide() {
15d50fff 1774 if ($this->hide_raw(0)) {
eabbfa82 1775 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1776 add_to_log(SITEID, "category", "hide", "editcategory.php?id=$this->id", $this->id);
1777 }
1778 }
1779
1780 /**
1781 * Show course category and restores visibility for child course and subcategories
1782 *
1783 * Note that there is no capability check inside this function
1784 *
1785 * This is protected function, use show() or update() from outside of this class
1786 *
1787 * @see coursecat::show()
1788 * @see coursecat::update()
1789 *
1790 * @return bool whether changes have been made and caches need to be purged afterwards
1791 */
15d50fff 1792 protected function show_raw() {
b33389d2
MG
1793 global $DB;
1794
1795 if ($this->visible) {
1796 // already visible
1797 return false;
1798 }
1799
1800 $this->visible = 1;
1801 $this->visibleold = 1;
1802 $DB->set_field('course_categories', 'visible', 1, array('id' => $this->id));
1803 $DB->set_field('course_categories', 'visibleold', 1, array('id' => $this->id));
1804 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($this->id));
1805 // get all child categories and unhide too
1806 if ($subcats = $DB->get_records_select('course_categories', "path LIKE ?", array("$this->path/%"), 'id, visibleold')) {
1807 foreach ($subcats as $cat) {
1808 if ($cat->visibleold) {
1809 $DB->set_field('course_categories', 'visible', 1, array('id' => $cat->id));
1810 }
1811 $DB->execute("UPDATE {course} SET visible = visibleold WHERE category = ?", array($cat->id));
1812 }
1813 }
1814 return true;
1815 }
1816
1817 /**
1818 * Show course category and restores visibility for child course and subcategories
1819 *
1820 * Note that there is no capability check inside this function
1821 *
1822 * This function does not update field course_categories.timemodified
1823 * If you want to update timemodified, use
1824 * $coursecat->update(array('visible' => 1));
1825 */
1826 public function show() {
15d50fff 1827 if ($this->show_raw()) {
eabbfa82 1828 cache_helper::purge_by_event('changesincoursecat');
b33389d2
MG
1829 add_to_log(SITEID, "category", "show", "editcategory.php?id=$this->id", $this->id);
1830 }
1831 }
1832
1833 /**
1834 * Returns name of the category formatted as a string
1835 *
1836 * @param array $options formatting options other than context
1837 * @return string
1838 */
1839 public function get_formatted_name($options = array()) {
1840 if ($this->id) {
1841 $context = context_coursecat::instance($this->id);
1842 return format_string($this->name, true, array('context' => $context) + $options);
1843 } else {
1844 return ''; // TODO 'Top'?
1845 }
1846 }
1847
1848 /**
15d50fff 1849 * Returns ids of all parents of the category. Last element in the return array is the direct parent
b33389d2
MG
1850 *
1851 * For example, if you have a tree of categories like:
1852 * Miscellaneous (id = 1)
1853 * Subcategory (id = 2)
1854 * Sub-subcategory (id = 4)
1855 * Other category (id = 3)
1856 *
15d50fff
MG
1857 * coursecat::get(1)->get_parents() == array()
1858 * coursecat::get(2)->get_parents() == array(1)
1859 * coursecat::get(4)->get_parents() == array(1, 2);
b33389d2
MG
1860 *
1861 * Note that this method does not check if all parents are accessible by current user
1862 *
15d50fff 1863 * @return array of category ids
b33389d2 1864 */
15d50fff
MG
1865 public function get_parents() {
1866 $parents = preg_split('|/|', $this->path, 0, PREG_SPLIT_NO_EMPTY);
1867 array_pop($parents);
1868 return $parents;
b33389d2
MG
1869 }
1870
1871 /**
9178bbbc 1872 * This function returns a nice list representing category tree
b33389d2
MG
1873 * for display or to use in a form <select> element
1874 *
9178bbbc
MG
1875 * List is cached for 10 minutes
1876 *
b33389d2
MG
1877 * For example, if you have a tree of categories like:
1878 * Miscellaneous (id = 1)
1879 * Subcategory (id = 2)
1880 * Sub-subcategory (id = 4)
1881 * Other category (id = 3)
1882 * Then after calling this function you will have
1883 * array(1 => 'Miscellaneous',
1884 * 2 => 'Miscellaneous / Subcategory',
1885 * 4 => 'Miscellaneous / Subcategory / Sub-subcategory',
1886 * 3 => 'Other category');
1887 *
1888 * If you specify $requiredcapability, then only categories where the current
1889 * user has that capability will be added to $list.
1890 * If you only have $requiredcapability in a child category, not the parent,
1891 * then the child catgegory will still be included.
1892 *
1893 * If you specify the option $excludeid, then that category, and all its children,
1894 * are omitted from the tree. This is useful when you are doing something like
1895 * moving categories, where you do not want to allow people to move a category
1896 * to be the child of itself.
1897 *
1898 * See also {@link make_categories_options()}
1899 *
1900 * @param string/array $requiredcapability if given, only categories where the current
1901 * user has this capability will be returned. Can also be an array of capabilities,
1902 * in which case they are all required.
1903 * @param integer $excludeid Exclude this category and its children from the lists built.
1904 * @param string $separator string to use as a separator between parent and child category. Default ' / '
1905 * @return array of strings
1906 */
1907 public static function make_categories_list($requiredcapability = '', $excludeid = 0, $separator = ' / ') {
9178bbbc
MG
1908 global $DB;
1909 $coursecatcache = cache::make('core', 'coursecat');
b33389d2 1910
9178bbbc
MG
1911 // Check if we cached the complete list of user-accessible category names ($baselist) or list of ids with requried cap ($thislist).
1912 $basecachekey = 'catlist';
1913 $baselist = $coursecatcache->get($basecachekey);
9178bbbc
MG
1914 $thislist = false;
1915 if (!empty($requiredcapability)) {
1916 $requiredcapability = (array)$requiredcapability;
1917 $thiscachekey = 'catlist:'. serialize($requiredcapability);
1918 if ($baselist !== false && ($thislist = $coursecatcache->get($thiscachekey)) !== false) {
1919 $thislist = preg_split('|,|', $thislist, -1, PREG_SPLIT_NO_EMPTY);
b33389d2 1920 }
9178bbbc
MG
1921 } else if ($baselist !== false) {
1922 $thislist = array_keys($baselist);
1923 }
1924
1925 if ($baselist === false) {
1926 // We don't have $baselist cached, retrieve it. Retrieve $thislist again in any case.
1927 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
1928 $sql = "SELECT cc.id, cc.sortorder, cc.name, cc.visible, cc.parent, cc.path, $ctxselect
1929 FROM {course_categories} cc
1930 JOIN {context} ctx ON cc.id = ctx.instanceid AND ctx.contextlevel = :contextcoursecat
1931 ORDER BY cc.sortorder";
1932 $rs = $DB->get_recordset_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1933 $baselist = array();
1934 $thislist = array();
1935 foreach ($rs as $record) {
1936 // If the category's parent is not visible to the user, it is not visible as well.
1937 if (!$record->parent || isset($baselist[$record->parent])) {
e4008e9d 1938 context_helper::preload_from_record($record);
9178bbbc
MG
1939 $context = context_coursecat::instance($record->id);
1940 if (!$record->visible && !has_capability('moodle/category:viewhiddencategories', $context)) {
1941 // No cap to view category, added to neither $baselist nor $thislist
1942 continue;
1943 }
1944 $baselist[$record->id] = array(
1945 'name' => format_string($record->name, true, array('context' => $context)),
1946 'path' => $record->path
1947 );
1948 if (!empty($requiredcapability) && !has_all_capabilities($requiredcapability, $context)) {
1949 // No required capability, added to $baselist but not to $thislist.
1950 continue;
1951 }
1952 $thislist[] = $record->id;
1953 }
1954 }
1955 $rs->close();
1956 $coursecatcache->set($basecachekey, $baselist);
1957 if (!empty($requiredcapability)) {
1958 $coursecatcache->set($thiscachekey, join(',', $thislist));
b33389d2 1959 }
9178bbbc
MG
1960 } else if ($thislist === false) {
1961 // We have $baselist cached but not $thislist. Simplier query is used to retrieve.
1962 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
deabf12e 1963 $sql = "SELECT ctx.instanceid AS id, $ctxselect
9178bbbc
MG
1964 FROM {context} ctx WHERE ctx.contextlevel = :contextcoursecat";
1965 $contexts = $DB->get_records_sql($sql, array('contextcoursecat' => CONTEXT_COURSECAT));
1966 $thislist = array();
1967 foreach (array_keys($baselist) as $id) {
1968 context_helper::preload_from_record($contexts[$id]);
1969 if (has_all_capabilities($requiredcapability, context_coursecat::instance($id))) {
1970 $thislist[] = $id;
1971 }
1972 }
1973 $coursecatcache->set($thiscachekey, join(',', $thislist));
b33389d2
MG
1974 }
1975
9178bbbc
MG
1976 // Now build the array of strings to return, mind $separator and $excludeid.
1977 $names = array();
1978 foreach ($thislist as $id) {
1979 $path = preg_split('|/|', $baselist[$id]['path'], -1, PREG_SPLIT_NO_EMPTY);
1980 if (!$excludeid || !in_array($excludeid, $path)) {
1981 $namechunks = array();
1982 foreach ($path as $parentid) {
1983 $namechunks[] = $baselist[$parentid]['name'];
1984 }
1985 $names[$id] = join($separator, $namechunks);
1986 }
b33389d2 1987 }
9178bbbc 1988 return $names;
b33389d2
MG
1989 }
1990
b33389d2
MG
1991 /**
1992 * Prepares the object for caching. Works like the __sleep method.
1993 *
9c6cfc08
MG
1994 * implementing method from interface cacheable_object
1995 *
b33389d2
MG
1996 * @return array ready to be cached
1997 */
1998 public function prepare_to_cache() {
1999 $a = array();
2000 foreach (self::$coursecatfields as $property => $cachedirectives) {
2001 if ($cachedirectives !== null) {
2002 list($shortname, $defaultvalue) = $cachedirectives;
2003 if ($this->$property !== $defaultvalue) {
2004 $a[$shortname] = $this->$property;
2005 }
2006 }
2007 }
2008 $context = context_coursecat::instance($this->id);
2009 $a['xi'] = $context->id;
2010 $a['xp'] = $context->path;
2011 return $a;
2012 }
2013
2014 /**
2015 * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
2016 *
9c6cfc08
MG
2017 * implementing method from interface cacheable_object
2018 *
b33389d2
MG
2019 * @param array $a
2020 * @return coursecat
2021 */
2022 public static function wake_from_cache($a) {
2023 $record = new stdClass;
2024 foreach (self::$coursecatfields as $property => $cachedirectives) {
2025 if ($cachedirectives !== null) {
2026 list($shortname, $defaultvalue) = $cachedirectives;
2027 if (array_key_exists($shortname, $a)) {
2028 $record->$property = $a[$shortname];
2029 } else {
2030 $record->$property = $defaultvalue;
2031 }
2032 }
2033 }
2034 $record->ctxid = $a['xi'];
2035 $record->ctxpath = $a['xp'];
2036 $record->ctxdepth = $record->depth + 1;
2037 $record->ctxlevel = CONTEXT_COURSECAT;
2038 $record->ctxinstance = $record->id;
2039 return new coursecat($record, true);
2040 }
2041}
93c544bd
MG
2042
2043/**
2044 * Class to store information about one course in a list of courses
2045 *
2046 * Not all information may be retrieved when object is created but
2047 * it will be retrieved on demand when appropriate property or method is
2048 * called.
2049 *
2050 * Instances of this class are usually returned by functions
2051 * {@link coursecat::search_courses()}
2052 * and
2053 * {@link coursecat::get_courses()}
2054 *
1eac2033
SH
2055 * @property-read int $id
2056 * @property-read int $category Category ID
2057 * @property-read int $sortorder
2058 * @property-read string $fullname
2059 * @property-read string $shortname
2060 * @property-read string $idnumber
85708da6
MG
2061 * @property-read string $summary Course summary. Field is present if coursecat::get_courses()
2062 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2063 * @property-read int $summaryformat Summary format. Field is present if coursecat::get_courses()
2064 * was called with option 'summary'. Otherwise will be retrieved from DB on first request
2065 * @property-read string $format Course format. Retrieved from DB on first request
2066 * @property-read int $showgrades Retrieved from DB on first request
85708da6 2067 * @property-read int $newsitems Retrieved from DB on first request
1eac2033 2068 * @property-read int $startdate
85708da6
MG
2069 * @property-read int $marker Retrieved from DB on first request
2070 * @property-read int $maxbytes Retrieved from DB on first request
2071 * @property-read int $legacyfiles Retrieved from DB on first request
2072 * @property-read int $showreports Retrieved from DB on first request
1eac2033 2073 * @property-read int $visible
85708da6
MG
2074 * @property-read int $visibleold Retrieved from DB on first request
2075 * @property-read int $groupmode Retrieved from DB on first request
2076 * @property-read int $groupmodeforce Retrieved from DB on first request
2077 * @property-read int $defaultgroupingid Retrieved from DB on first request
2078 * @property-read string $lang Retrieved from DB on first request
2079 * @property-read string $theme Retrieved from DB on first request
2080 * @property-read int $timecreated Retrieved from DB on first request
2081 * @property-read int $timemodified Retrieved from DB on first request
2082 * @property-read int $requested Retrieved from DB on first request
2083 * @property-read int $enablecompletion Retrieved from DB on first request
2084 * @property-read int $completionnotify Retrieved from DB on first request
4a3fb71c 2085 * @property-read int $cacherev
1eac2033 2086 *
93c544bd
MG
2087 * @package core
2088 * @subpackage course
2089 * @copyright 2013 Marina Glancy
2090 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2091 */
2092class course_in_list implements IteratorAggregate {
2093
2094 /** @var stdClass record retrieved from DB, may have additional calculated property such as managers and hassummary */
2095 protected $record;
2096
2097 /** @var array array of course contacts - stores result of call to get_course_contacts() */
2098 protected $coursecontacts;
2099
2100 /**
2101 * Creates an instance of the class from record
2102 *
2103 * @param stdClass $record except fields from course table it may contain
2104 * field hassummary indicating that summary field is not empty.
2105 * Also it is recommended to have context fields here ready for
2106 * context preloading
2107 */
2108 public function __construct(stdClass $record) {
db314f34 2109 context_helper::preload_from_record($record);
93c544bd
MG
2110 $this->record = new stdClass();
2111 foreach ($record as $key => $value) {
2112 $this->record->$key = $value;
2113 }
2114 }
2115
2116 /**
2117 * Indicates if the course has non-empty summary field
2118 *
2119 * @return bool
2120 */
2121 public function has_summary() {
2122 if (isset($this->record->hassummary)) {
2123 return !empty($this->record->hassummary);
2124 }
2125 if (!isset($this->record->summary)) {
2126 // we need to retrieve summary
2127 $this->__get('summary');
2128 }
2129 return !empty($this->record->summary);
2130 }
2131
2132 /**
2133 * Indicates if the course have course contacts to display
2134 *
2135 * @return bool
2136 */
2137 public function has_course_contacts() {
2138 if (!isset($this->record->managers)) {
2139 $courses = array($this->id => &$this->record);
2140 coursecat::preload_course_contacts($courses);
2141 }
2142 return !empty($this->record->managers);
2143 }
2144
2145 /**
2146 * Returns list of course contacts (usually teachers) to display in course link
2147 *
2148 * Roles to display are set up in $CFG->coursecontact
2149 *
2150 * The result is the list of users where user id is the key and the value
2151 * is an array with elements:
2152 * - 'user' - object containing basic user information
2153 * - 'role' - object containing basic role information (id, name, shortname, coursealias)
2154 * - 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS)
2155 * - 'username' => fullname($user, $canviewfullnames)
2156 *
2157 * @return array
2158 */
2159 public function get_course_contacts() {
2160 global $CFG;
2161 if (empty($CFG->coursecontact)) {
2162 // no roles are configured to be displayed as course contacts
2163 return array();
2164 }
2165 if ($this->coursecontacts === null) {
2166 $this->coursecontacts = array();
2167 $context = context_course::instance($this->id);
2168
2169 if (!isset($this->record->managers)) {
2170 // preload course contacts from DB
2171 $courses = array($this->id => &$this->record);
2172 coursecat::preload_course_contacts($courses);
2173 }
2174
2175 // build return array with full roles names (for this course context) and users names
2176 $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
2177 foreach ($this->record->managers as $ruser) {
2178 if (isset($this->coursecontacts[$ruser->id])) {
2179 // only display a user once with the highest sortorder role
2180 continue;
2181 }
2182 $user = new stdClass();
2183 $user->id = $ruser->id;
2184 $user->username = $ruser->username;
a327f25e
AG
2185 foreach (get_all_user_name_fields() as $addname) {
2186 $user->$addname = $ruser->$addname;
2187 }
93c544bd
MG
2188 $role = new stdClass();
2189 $role->id = $ruser->roleid;
2190 $role->name = $ruser->rolename;
2191 $role->shortname = $ruser->roleshortname;
2192 $role->coursealias = $ruser->rolecoursealias;
2193
2194 $this->coursecontacts[$user->id] = array(
2195 'user' => $user,
2196 'role' => $role,
2197 'rolename' => role_get_name($role, $context, ROLENAME_ALIAS),
2198 'username' => fullname($user, $canviewfullnames)
2199 );
2200 }
2201 }
2202 return $this->coursecontacts;
2203 }
2204
d1f8c1bd
MG
2205 /**
2206 * Checks if course has any associated overview files
2207 *
2208 * @return bool
2209 */
2210 public function has_course_overviewfiles() {
2211 global $CFG;
2212 if (empty($CFG->courseoverviewfileslimit)) {
961403c4 2213 return false;
d1f8c1bd 2214 }
d1f8c1bd
MG
2215 $fs = get_file_storage();
2216 $context = context_course::instance($this->id);
961403c4 2217 return !$fs->is_area_empty($context->id, 'course', 'overviewfiles');
d1f8c1bd
MG
2218 }
2219
2220 /**
2221 * Returns all course overview files
2222 *
2223 * @return array array of stored_file objects
2224 */
2225 public function get_course_overviewfiles() {
2226 global $CFG;
2227 if (empty($CFG->courseoverviewfileslimit)) {
2228 return array();
2229 }
2230 require_once($CFG->libdir. '/filestorage/file_storage.php');
473d5f74 2231 require_once($CFG->dirroot. '/course/lib.php');
d1f8c1bd
MG
2232 $fs = get_file_storage();
2233 $context = context_course::instance($this->id);
2234 $files = $fs->get_area_files($context->id, 'course', 'overviewfiles', false, 'filename', false);
2235 if (count($files)) {
2236 $overviewfilesoptions = course_overviewfiles_options($this->id);
2237 $acceptedtypes = $overviewfilesoptions['accepted_types'];
2238 if ($acceptedtypes !== '*') {
2239 // filter only files with allowed extensions
2240 require_once($CFG->libdir. '/filelib.php');
15f89e28
SH
2241 foreach ($files as $key => $file) {
2242 if (!file_extension_in_typegroup($file->get_filename(), $acceptedtypes)) {
2243 unset($files[$key]);
2244 }
2245 }
d1f8c1bd
MG
2246 }
2247 if (count($files) > $CFG->courseoverviewfileslimit) {
2248 // return no more than $CFG->courseoverviewfileslimit files
2249 $files = array_slice($files, 0, $CFG->courseoverviewfileslimit, true);
2250 }
2251 }
2252 return $files;
2253 }
2254
93c544bd
MG
2255 // ====== magic methods =======
2256
2257 public function __isset($name) {
2258 return isset($this->record->$name);
2259 }
2260
2261 /**
2262 * Magic method to get a course property
2263 *
2264 * Returns any field from table course (from cache or from DB) and/or special field 'hassummary'
2265 *
2266 * @param string $name
2267 * @return mixed
2268 */
2269 public function __get($name) {
2270 global $DB;
2271 if (property_exists($this->record, $name)) {
2272 return $this->record->$name;
2273 } else if ($name === 'summary' || $name === 'summaryformat') {
2274 // retrieve fields summary and summaryformat together because they are most likely to be used together
2275 $record = $DB->get_record('course', array('id' => $this->record->id), 'summary, summaryformat', MUST_EXIST);
2276 $this->record->summary = $record->summary;
2277 $this->record->summaryformat = $record->summaryformat;
2278 return $this->record->$name;
2279 } else if (array_key_exists($name, $DB->get_columns('course'))) {
2280 // another field from table 'course' that was not retrieved
2281 $this->record->$name = $DB->get_field('course', $name, array('id' => $this->record->id), MUST_EXIST);
2282 return $this->record->$name;
2283 }
2284 debugging('Invalid course property accessed! '.$name);
2285 return null;
2286 }
2287
2288 /**
2289 * ALl properties are read only, sorry.
2290 * @param string $name
2291 */
2292 public function __unset($name) {
2293 debugging('Can not unset '.get_class($this).' instance properties!');
2294 }
2295
2296 /**
2297 * Magic setter method, we do not want anybody to modify properties from the outside
2298 * @param string $name
2299 * @param mixed $value
2300 */
2301 public function __set($name, $value) {
2302 debugging('Can not change '.get_class($this).' instance properties!');
2303 }
2304
2305 // ====== implementing method from interface IteratorAggregate ======
2306
2307 /**
2308 * Create an iterator because magic vars can't be seen by 'foreach'.
2309 * Exclude context fields
2310 */
2311 public function getIterator() {
2312 $ret = array('id' => $this->record->id);
2313 foreach ($this->record as $property => $value) {
2314 $ret[$property] = $value;
2315 }
2316 return new ArrayIterator($ret);
2317 }
2318}
15f89e28
SH
2319
2320/**
2321 * An array of records that is sortable by many fields.
2322 *
2323 * For more info on the ArrayObject class have a look at php.net.
2324 *
2325 * @package core
2326 * @subpackage course
2327 * @copyright 2013 Sam Hemelryk
2328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2329 */
2330class coursecat_sortable_records extends ArrayObject {
2331
2332 /**
2333 * An array of sortable fields.
2334 * Gets set temporarily when sort is called.
2335 * @var array
2336 */
2337 protected $sortfields = array();
2338
2339 /**
2340 * Sorts this array using the given fields.
2341 *
2342 * @param array $records
2343 * @param array $fields
2344 * @return array
2345 */
2346 public static function sort(array $records, array $fields) {
2347 $records = new coursecat_sortable_records($records);
2348 $records->sortfields = $fields;
2349 $records->uasort(array($records, 'sort_by_many_fields'));
2350 return $records->getArrayCopy();
2351 }
2352
2353 /**
2354 * Sorts the two records based upon many fields.
2355 *
2356 * This method should not be called itself, please call $sort instead.
2357 * It has been marked as access private as such.
2358 *
2359 * @access private
2360 * @param stdClass $a
2361 * @param stdClass $b
2362 * @return int
2363 */
2364 public function sort_by_many_fields($a, $b) {
2365 foreach ($this->sortfields as $field => $mult) {
2366 // nulls first
2367 if (is_null($a->$field) && !is_null($b->$field)) {
2368 return -$mult;
2369 }
2370 if (is_null($b->$field) && !is_null($a->$field)) {
2371 return $mult;
2372 }
2373
2374 if (is_string($a->$field) || is_string($b->$field)) {
2375 // string fields
2376 if ($cmp = strcoll($a->$field, $b->$field)) {
2377 return $mult * $cmp;
2378 }
2379 } else {
2380 // int fields
2381 if ($a->$field > $b->$field) {
2382 return $mult;
2383 }
2384 if ($a->$field < $b->$field) {
2385 return -$mult;
2386 }
2387 }
2388 }
2389 return 0;
2390 }
36ba8fde 2391}