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