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