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