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