forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodinfolib.php
3583 lines (3257 loc) · 138 KB
/
modinfolib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* modinfolib.php - Functions/classes relating to cached information about module instances on
* a course.
* @package core
* @subpackage lib
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author sam marshall
*/
// Maximum number of modinfo items to keep in memory cache. Do not increase this to a large
// number because:
// a) modinfo can be big (megabyte range) for some courses
// b) performance of cache will deteriorate if there are very many items in it
if (!defined('MAX_MODINFO_CACHE_SIZE')) {
define('MAX_MODINFO_CACHE_SIZE', 10);
}
use core_courseformat\output\activitybadge;
use core_courseformat\sectiondelegate;
/**
* Information about a course that is cached in the course table 'modinfo' field (and then in
* memory) in order to reduce the need for other database queries.
*
* This includes information about the course-modules and the sections on the course. It can also
* include dynamic data that has been updated for the current user.
*
* Use {@link get_fast_modinfo()} to retrieve the instance of the object for particular course
* and particular user.
*
* @property-read int $courseid Course ID
* @property-read int $userid User ID
* @property-read array $sections Array from section number (e.g. 0) to array of course-module IDs in that
* section; this only includes sections that contain at least one course-module
* @property-read cm_info[] $cms Array from course-module instance to cm_info object within this course, in
* order of appearance
* @property-read cm_info[][] $instances Array from string (modname) => int (instance id) => cm_info object
* @property-read array $groups Groups that the current user belongs to. Calculated on the first request.
* Is an array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
*/
class course_modinfo {
/** @var int Maximum time the course cache building lock can be held */
const COURSE_CACHE_LOCK_EXPIRY = 180;
/** @var int Time to wait for the course cache building lock before throwing an exception */
const COURSE_CACHE_LOCK_WAIT = 60;
/**
* List of fields from DB table 'course' that are cached in MUC and are always present in course_modinfo::$course
* @var array
*/
public static $cachedfields = array('shortname', 'fullname', 'format',
'enablecompletion', 'groupmode', 'groupmodeforce', 'cacherev');
/**
* For convenience we store the course object here as it is needed in other parts of code
* @var stdClass
*/
private $course;
/**
* Array of section data from cache indexed by section number.
* @var section_info[]
*/
private $sectioninfobynum;
/**
* Array of section data from cache indexed by id.
* @var section_info[]
*/
private $sectioninfobyid;
/**
* Index of delegated sections (indexed by component and itemid)
* @var array
*/
private $delegatedsections;
/**
* User ID
* @var int
*/
private $userid;
/**
* Array indexed by section num (e.g. 0) => array of course-module ids
* This list only includes sections that actually contain at least one course-module
* @var array
*/
private $sectionmodules;
/**
* Array from int (cm id) => cm_info object
* @var cm_info[]
*/
private $cms;
/**
* Array from string (modname) => int (instance id) => cm_info object
* @var cm_info[][]
*/
private $instances;
/**
* Groups that the current user belongs to. This value is calculated on first
* request to the property or function.
* When set, it is an array of grouping id => array of group id => group id.
* Includes grouping id 0 for 'all groups'.
* @var int[][]
*/
private $groups;
/**
* List of class read-only properties and their getter methods.
* Used by magic functions __get(), __isset(), __empty()
* @var array
*/
private static $standardproperties = array(
'courseid' => 'get_course_id',
'userid' => 'get_user_id',
'sections' => 'get_sections',
'cms' => 'get_cms',
'instances' => 'get_instances',
'groups' => 'get_groups_all',
);
/**
* Magic method getter
*
* @param string $name
* @return mixed
*/
public function __get($name) {
if (isset(self::$standardproperties[$name])) {
$method = self::$standardproperties[$name];
return $this->$method();
} else {
debugging('Invalid course_modinfo property accessed: '.$name);
return null;
}
}
/**
* Magic method for function isset()
*
* @param string $name
* @return bool
*/
public function __isset($name) {
if (isset(self::$standardproperties[$name])) {
$value = $this->__get($name);
return isset($value);
}
return false;
}
/**
* Magic method for function empty()
*
* @param string $name
* @return bool
*/
public function __empty($name) {
if (isset(self::$standardproperties[$name])) {
$value = $this->__get($name);
return empty($value);
}
return true;
}
/**
* Magic method setter
*
* Will display the developer warning when trying to set/overwrite existing property.
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value) {
debugging("It is not allowed to set the property course_modinfo::\${$name}", DEBUG_DEVELOPER);
}
/**
* Returns course object that was used in the first {@link get_fast_modinfo()} call.
*
* It may not contain all fields from DB table {course} but always has at least the following:
* id,shortname,fullname,format,enablecompletion,groupmode,groupmodeforce,cacherev
*
* @return stdClass
*/
public function get_course() {
return $this->course;
}
/**
* @return int Course ID
*/
public function get_course_id() {
return $this->course->id;
}
/**
* @return int User ID
*/
public function get_user_id() {
return $this->userid;
}
/**
* @return array Array from section number (e.g. 0) to array of course-module IDs in that
* section; this only includes sections that contain at least one course-module
*/
public function get_sections() {
return $this->sectionmodules;
}
/**
* @return cm_info[] Array from course-module instance to cm_info object within this course, in
* order of appearance
*/
public function get_cms() {
return $this->cms;
}
/**
* Obtains a single course-module object (for a course-module that is on this course).
* @param int $cmid Course-module ID
* @return cm_info Information about that course-module
* @throws moodle_exception If the course-module does not exist
*/
public function get_cm($cmid) {
if (empty($this->cms[$cmid])) {
throw new moodle_exception('invalidcoursemoduleid', 'error', '', $cmid);
}
return $this->cms[$cmid];
}
/**
* Obtains all module instances on this course.
* @return cm_info[][] Array from module name => array from instance id => cm_info
*/
public function get_instances() {
return $this->instances;
}
/**
* Returns array of localised human-readable module names used in this course
*
* @param bool $plural if true returns the plural form of modules names
* @return array
*/
public function get_used_module_names($plural = false) {
$modnames = get_module_types_names($plural);
$modnamesused = array();
foreach ($this->get_cms() as $cmid => $mod) {
if (!isset($modnamesused[$mod->modname]) && isset($modnames[$mod->modname]) && $mod->uservisible) {
$modnamesused[$mod->modname] = $modnames[$mod->modname];
}
}
return $modnamesused;
}
/**
* Obtains all instances of a particular module on this course.
* @param string $modname Name of module (not full frankenstyle) e.g. 'label'
* @return cm_info[] Array from instance id => cm_info for modules on this course; empty if none
*/
public function get_instances_of($modname) {
if (empty($this->instances[$modname])) {
return array();
}
return $this->instances[$modname];
}
/**
* Groups that the current user belongs to organised by grouping id. Calculated on the first request.
* @return int[][] array of grouping id => array of group id => group id. Includes grouping id 0 for 'all groups'
*/
private function get_groups_all() {
if (is_null($this->groups)) {
$this->groups = groups_get_user_groups($this->course->id, $this->userid);
}
return $this->groups;
}
/**
* Returns groups that the current user belongs to on the course. Note: If not already
* available, this may make a database query.
* @param int $groupingid Grouping ID or 0 (default) for all groups
* @return int[] Array of int (group id) => int (same group id again); empty array if none
*/
public function get_groups($groupingid = 0) {
$allgroups = $this->get_groups_all();
if (!isset($allgroups[$groupingid])) {
return array();
}
return $allgroups[$groupingid];
}
/**
* Gets all sections as array from section number => data about section.
*
* The method will return all sections of the course, including the ones
* delegated to a component.
*
* @return section_info[] Array of section_info objects organised by section number
*/
public function get_section_info_all() {
return $this->sectioninfobynum;
}
/**
* Gets all sections listed in course page as array from section number => data about section.
*
* The method is similar to get_section_info_all but filtering all sections delegated to components.
*
* @return section_info[] Array of section_info objects organised by section number
*/
public function get_listed_section_info_all() {
if (empty($this->delegatedsections)) {
return $this->sectioninfobynum;
}
$sections = [];
foreach ($this->sectioninfobynum as $section) {
if (!$section->is_delegated()) {
$sections[$section->section] = $section;
}
}
return $sections;
}
/**
* Gets data about specific numbered section.
* @param int $sectionnumber Number (not id) of section
* @param int $strictness Use MUST_EXIST to throw exception if it doesn't
* @return ?section_info Information for numbered section or null if not found
*/
public function get_section_info($sectionnumber, $strictness = IGNORE_MISSING) {
if (!array_key_exists($sectionnumber, $this->sectioninfobynum)) {
if ($strictness === MUST_EXIST) {
throw new moodle_exception('sectionnotexist');
} else {
return null;
}
}
return $this->sectioninfobynum[$sectionnumber];
}
/**
* Gets data about specific section ID.
* @param int $sectionid ID (not number) of section
* @param int $strictness Use MUST_EXIST to throw exception if it doesn't
* @return section_info|null Information for numbered section or null if not found
*/
public function get_section_info_by_id(int $sectionid, int $strictness = IGNORE_MISSING): ?section_info {
if (!array_key_exists($sectionid, $this->sectioninfobyid)) {
if ($strictness === MUST_EXIST) {
throw new moodle_exception('sectionnotexist');
} else {
return null;
}
}
return $this->sectioninfobyid[$sectionid];
}
/**
* Gets data about specific delegated section.
* @param string $component Component name
* @param int $itemid Item id
* @param int $strictness Use MUST_EXIST to throw exception if it doesn't
* @return section_info|null Information for numbered section or null if not found
*/
public function get_section_info_by_component(
string $component,
int $itemid,
int $strictness = IGNORE_MISSING
): ?section_info {
if (!isset($this->delegatedsections[$component][$itemid])) {
if ($strictness === MUST_EXIST) {
throw new moodle_exception('sectionnotexist');
} else {
return null;
}
}
return $this->delegatedsections[$component][$itemid];
}
/**
* Check if the course has delegated sections.
* @return bool
*/
public function has_delegated_sections(): bool {
return !empty($this->delegatedsections);
}
/**
* Static cache for generated course_modinfo instances
*
* @see course_modinfo::instance()
* @see course_modinfo::clear_instance_cache()
* @var course_modinfo[]
*/
protected static $instancecache = array();
/**
* Timestamps (microtime) when the course_modinfo instances were last accessed
*
* It is used to remove the least recent accessed instances when static cache is full
*
* @var float[]
*/
protected static $cacheaccessed = array();
/**
* Store a list of known course cacherev values. This is in case people reuse a course object
* (with an old cacherev value) within the same request when calling things like
* get_fast_modinfo, after rebuild_course_cache.
*
* @var int[]
*/
protected static $mincacherevs = [];
/**
* Clears the cache used in course_modinfo::instance()
*
* Used in {@link get_fast_modinfo()} when called with argument $reset = true
* and in {@link rebuild_course_cache()}
*
* If the cacherev for the course is known to have updated (i.e. when doing
* rebuild_course_cache), it should be specified here.
*
* @param null|int|stdClass $courseorid if specified removes only cached value for this course
* @param int $newcacherev If specified, the known cache rev for this course id will be updated
*/
public static function clear_instance_cache($courseorid = null, int $newcacherev = 0) {
if (empty($courseorid)) {
self::$instancecache = array();
self::$cacheaccessed = array();
// This is called e.g. in phpunit when we just want to reset the caches, so also
// reset the mincacherevs static cache.
self::$mincacherevs = [];
return;
}
if (is_object($courseorid)) {
$courseorid = $courseorid->id;
}
if (isset(self::$instancecache[$courseorid])) {
// Unsetting static variable in PHP is peculiar, it removes the reference,
// but data remain in memory. Prior to unsetting, the varable needs to be
// set to empty to remove its remains from memory.
self::$instancecache[$courseorid] = '';
unset(self::$instancecache[$courseorid]);
unset(self::$cacheaccessed[$courseorid]);
}
// When clearing cache for a course, we record the new cacherev version, to make
// sure that any future requests for the cache use at least this version.
if ($newcacherev) {
self::$mincacherevs[(int)$courseorid] = $newcacherev;
}
}
/**
* Returns the instance of course_modinfo for the specified course and specified user
*
* This function uses static cache for the retrieved instances. The cache
* size is limited by MAX_MODINFO_CACHE_SIZE. If instance is not found in
* the static cache or it was created for another user or the cacherev validation
* failed - a new instance is constructed and returned.
*
* Used in {@link get_fast_modinfo()}
*
* @param int|stdClass $courseorid object from DB table 'course' (must have field 'id'
* and recommended to have field 'cacherev') or just a course id
* @param int $userid User id to populate 'availble' and 'uservisible' attributes of modules and sections.
* Set to 0 for current user (default). Set to -1 to avoid calculation of dynamic user-depended data.
* @return course_modinfo
*/
public static function instance($courseorid, $userid = 0) {
global $USER;
if (is_object($courseorid)) {
$course = $courseorid;
} else {
$course = (object)array('id' => $courseorid);
}
if (empty($userid)) {
$userid = $USER->id;
}
if (!empty(self::$instancecache[$course->id])) {
if (self::$instancecache[$course->id]->userid == $userid &&
(!isset($course->cacherev) ||
$course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
// This course's modinfo for the same user was recently retrieved, return cached.
self::$cacheaccessed[$course->id] = microtime(true);
return self::$instancecache[$course->id];
} else {
// Prevent potential reference problems when switching users.
self::clear_instance_cache($course->id);
}
}
$modinfo = new course_modinfo($course, $userid);
// We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
// Find the course that was the least recently accessed.
asort(self::$cacheaccessed, SORT_NUMERIC);
$courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
self::clear_instance_cache($courseidtoremove);
}
// Add modinfo to the static cache.
self::$instancecache[$course->id] = $modinfo;
self::$cacheaccessed[$course->id] = microtime(true);
return $modinfo;
}
/**
* Constructs based on course.
* Note: This constructor should not usually be called directly.
* Use get_fast_modinfo($course) instead as this maintains a cache.
* @param stdClass $course course object, only property id is required.
* @param int $userid User ID
* @throws moodle_exception if course is not found
*/
public function __construct($course, $userid) {
global $CFG, $COURSE, $SITE, $DB;
if (!isset($course->cacherev)) {
// We require presence of property cacherev to validate the course cache.
// No need to clone the $COURSE or $SITE object here because we clone it below anyway.
$course = get_course($course->id, false);
}
// If we have rebuilt the course cache in this request, ensure that requested cacherev is
// at least that value. This ensures that we're not reusing a course object with old
// cacherev, which could result in using old cached data.
if (array_key_exists($course->id, self::$mincacherevs) &&
$course->cacherev < self::$mincacherevs[$course->id]) {
$course->cacherev = self::$mincacherevs[$course->id];
}
$cachecoursemodinfo = cache::make('core', 'coursemodinfo');
// Retrieve modinfo from cache. If not present or cacherev mismatches, call rebuild and retrieve again.
$coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
// Note the version comparison using the data in the cache should not be necessary, but the
// partial rebuild logic sometimes sets the $coursemodinfo->cacherev to -1 which is an
// indicator that it needs rebuilding.
if ($coursemodinfo === false || ($course->cacherev > $coursemodinfo->cacherev)) {
$coursemodinfo = self::build_course_cache($course);
}
// Set initial values
$this->userid = $userid;
$this->sectionmodules = [];
$this->cms = [];
$this->instances = [];
$this->groups = null;
// If we haven't already preloaded contexts for the course, do it now
// Modules are also cached here as long as it's the first time this course has been preloaded.
context_helper::preload_course($course->id);
// Quick integrity check: as a result of race conditions modinfo may not be regenerated after the change.
// It is especially dangerous if modinfo contains the deleted course module, as it results in fatal error.
// We can check it very cheap by validating the existence of module context.
if ($course->id == $COURSE->id || $course->id == $SITE->id) {
// Only verify current course (or frontpage) as pages with many courses may not have module contexts cached.
// (Uncached modules will result in a very slow verification).
foreach ($coursemodinfo->modinfo as $mod) {
if (!context_module::instance($mod->cm, IGNORE_MISSING)) {
debugging('Course cache integrity check failed: course module with id '. $mod->cm.
' does not have context. Rebuilding cache for course '. $course->id);
// Re-request the course record from DB as well, don't use get_course() here.
$course = $DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST);
$coursemodinfo = self::build_course_cache($course, true);
break;
}
}
}
// Overwrite unset fields in $course object with cached values, store the course object.
$this->course = fullclone($course);
foreach ($coursemodinfo as $key => $value) {
if ($key !== 'modinfo' && $key !== 'sectioncache' &&
(!isset($this->course->$key) || $key === 'cacherev')) {
$this->course->$key = $value;
}
}
// Loop through each piece of module data, constructing it
static $modexists = array();
foreach ($coursemodinfo->modinfo as $mod) {
if (!isset($mod->name) || strval($mod->name) === '') {
// something is wrong here
continue;
}
// Skip modules which don't exist
if (!array_key_exists($mod->mod, $modexists)) {
$modexists[$mod->mod] = file_exists("$CFG->dirroot/mod/$mod->mod/lib.php");
}
if (!$modexists[$mod->mod]) {
continue;
}
// Construct info for this module
$cm = new cm_info($this, null, $mod, null);
// Store module in instances and cms array
if (!isset($this->instances[$cm->modname])) {
$this->instances[$cm->modname] = array();
}
$this->instances[$cm->modname][$cm->instance] = $cm;
$this->cms[$cm->id] = $cm;
// Reconstruct sections. This works because modules are stored in order
if (!isset($this->sectionmodules[$cm->sectionnum])) {
$this->sectionmodules[$cm->sectionnum] = [];
}
$this->sectionmodules[$cm->sectionnum][] = $cm->id;
}
// Expand section objects
$this->sectioninfobynum = [];
$this->sectioninfobyid = [];
$this->delegatedsections = [];
foreach ($coursemodinfo->sectioncache as $data) {
$sectioninfo = new section_info($data, $data->section, null, null,
$this, null);
$this->sectioninfobynum[$data->section] = $sectioninfo;
$this->sectioninfobyid[$data->id] = $sectioninfo;
if (!empty($sectioninfo->component)) {
if (!isset($this->delegatedsections[$sectioninfo->component])) {
$this->delegatedsections[$sectioninfo->component] = [];
}
$this->delegatedsections[$sectioninfo->component][$sectioninfo->itemid] = $sectioninfo;
}
}
ksort($this->sectioninfobynum);
}
/**
* This method can not be used anymore.
*
* @see course_modinfo::build_course_cache()
* @deprecated since 2.6
*/
public static function build_section_cache($courseid) {
throw new coding_exception('Function course_modinfo::build_section_cache() can not be used anymore.' .
' Please use course_modinfo::build_course_cache() whenever applicable.');
}
/**
* Builds a list of information about sections on a course to be stored in
* the course cache. (Does not include information that is already cached
* in some other way.)
*
* @param stdClass $course Course object (must contain fields id and cacherev)
* @param boolean $usecache use cached section info if exists, use true for partial course rebuild
* @return array Information about sections, indexed by section id (not number)
*/
protected static function build_course_section_cache(\stdClass $course, bool $usecache = false): array {
global $DB;
// Get section data.
$sections = $DB->get_records(
'course_sections',
['course' => $course->id],
'section',
'id, section, course, name, summary, summaryformat, sequence, visible, availability, component, itemid'
);
$compressedsections = [];
$courseformat = course_get_format($course);
if ($usecache) {
$cachecoursemodinfo = cache::make('core', 'coursemodinfo');
$coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
if ($coursemodinfo !== false) {
$compressedsections = $coursemodinfo->sectioncache;
}
}
$formatoptionsdef = course_get_format($course)->section_format_options();
// Remove unnecessary data and add availability.
foreach ($sections as $section) {
$sectionid = $section->id;
$sectioninfocached = isset($compressedsections[$sectionid]);
if ($sectioninfocached) {
continue;
}
// Add cached options from course format to $section object.
foreach ($formatoptionsdef as $key => $option) {
if (!empty($option['cache'])) {
$formatoptions = $courseformat->get_format_options($section);
if (!array_key_exists('cachedefault', $option) || $option['cachedefault'] !== $formatoptions[$key]) {
$section->$key = $formatoptions[$key];
}
}
}
// Clone just in case it is reused elsewhere.
$compressedsections[$sectionid] = clone($section);
section_info::convert_for_section_cache($compressedsections[$sectionid]);
}
return $compressedsections;
}
/**
* Builds and stores in MUC object containing information about course
* modules and sections together with cached fields from table course.
*
* @param stdClass $course object from DB table course. Must have property 'id'
* but preferably should have all cached fields.
* @param boolean $partialrebuild Indicate if it's partial course cache rebuild or not
* @return stdClass object with all cached keys of the course plus fields modinfo and sectioncache.
* The same object is stored in MUC
* @throws moodle_exception if course is not found (if $course object misses some of the
* necessary fields it is re-requested from database)
*/
public static function build_course_cache(\stdClass $course, bool $partialrebuild = false): \stdClass {
if (empty($course->id)) {
throw new coding_exception('Object $course is missing required property \id\'');
}
$cachecoursemodinfo = cache::make('core', 'coursemodinfo');
$cachekey = $course->id;
$cachecoursemodinfo->acquire_lock($cachekey);
try {
// Only actually do the build if it's still needed after getting the lock (not if
// somebody else, who might have been holding the lock, built it already).
$coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
if ($coursemodinfo === false || ($course->cacherev > $coursemodinfo->cacherev)) {
$coursemodinfo = self::inner_build_course_cache($course);
}
} finally {
$cachecoursemodinfo->release_lock($cachekey);
}
return $coursemodinfo;
}
/**
* Called to build course cache when there is already a lock obtained.
*
* @param stdClass $course object from DB table course
* @param bool $partialrebuild Indicate if it's partial course cache rebuild or not
* @return stdClass Course object that has been stored in MUC
*/
protected static function inner_build_course_cache(\stdClass $course, bool $partialrebuild = false): \stdClass {
global $DB, $CFG;
require_once("{$CFG->dirroot}/course/lib.php");
$cachekey = $course->id;
$cachecoursemodinfo = cache::make('core', 'coursemodinfo');
if (!$cachecoursemodinfo->check_lock_state($cachekey)) {
throw new coding_exception('You must acquire a lock on the course ID before calling inner_build_course_cache');
}
// Always reload the course object from database to ensure we have the latest possible
// value for cacherev.
$course = $DB->get_record('course', ['id' => $course->id],
implode(',', array_merge(['id'], self::$cachedfields)), MUST_EXIST);
// Retrieve all information about activities and sections.
$coursemodinfo = new stdClass();
$coursemodinfo->modinfo = self::get_array_of_activities($course, $partialrebuild);
$coursemodinfo->sectioncache = self::build_course_section_cache($course, $partialrebuild);
foreach (self::$cachedfields as $key) {
$coursemodinfo->$key = $course->$key;
}
// Set the accumulated activities and sections information in cache, together with cacherev.
$cachecoursemodinfo->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
return $coursemodinfo;
}
/**
* Purge the cache of a course section by its id.
*
* @param int $courseid The course to purge cache in
* @param int $sectionid The section _id_ to purge
*/
public static function purge_course_section_cache_by_id(int $courseid, int $sectionid): void {
$course = get_course($courseid);
$cache = cache::make('core', 'coursemodinfo');
$cachekey = $course->id;
$cache->acquire_lock($cachekey);
try {
$coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
if ($coursemodinfo !== false && array_key_exists($sectionid, $coursemodinfo->sectioncache)) {
$coursemodinfo->cacherev = -1;
unset($coursemodinfo->sectioncache[$sectionid]);
$cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
}
} finally {
$cache->release_lock($cachekey);
}
}
/**
* Purge the cache of a course section by its number.
*
* @param int $courseid The course to purge cache in
* @param int $sectionno The section number to purge
*/
public static function purge_course_section_cache_by_number(int $courseid, int $sectionno): void {
$course = get_course($courseid);
$cache = cache::make('core', 'coursemodinfo');
$cachekey = $course->id;
$cache->acquire_lock($cachekey);
try {
$coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
if ($coursemodinfo !== false) {
foreach ($coursemodinfo->sectioncache as $sectionid => $sectioncache) {
if ($sectioncache->section == $sectionno) {
$coursemodinfo->cacherev = -1;
unset($coursemodinfo->sectioncache[$sectionid]);
$cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
break;
}
}
}
} finally {
$cache->release_lock($cachekey);
}
}
/**
* Purge the cache of a course module.
*
* @param int $courseid Course id
* @param int $cmid Course module id
*/
public static function purge_course_module_cache(int $courseid, int $cmid): void {
self::purge_course_modules_cache($courseid, [$cmid]);
}
/**
* Purges the coursemodinfo caches stored in MUC.
*
* @param int[] $courseids Array of course ids to purge the course caches
* for (or all courses if empty array).
*
*/
public static function purge_course_caches(array $courseids = []): void {
global $DB;
// Purging might purge all course caches, so use a recordset and close it.
$select = '';
$params = null;
if (!empty($courseids)) {
[$sql, $params] = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
$select = 'id ' . $sql;
}
$courses = $DB->get_recordset_select(
table: 'course',
select: $select,
params: $params,
fields: 'id',
);
// Purge each course's cache to make sure cache is recalculated next time
// the course is viewed.
foreach ($courses as $course) {
self::purge_course_cache($course->id);
}
$courses->close();
}
/**
* Purge the cache of multiple course modules.
*
* @param int $courseid Course id
* @param int[] $cmids List of course module ids
* @return void
*/
public static function purge_course_modules_cache(int $courseid, array $cmids): void {
$course = get_course($courseid);
$cache = cache::make('core', 'coursemodinfo');
$cachekey = $course->id;
$cache->acquire_lock($cachekey);
try {
$coursemodinfo = $cache->get_versioned($cachekey, $course->cacherev);
$hascache = ($coursemodinfo !== false);
$updatedcache = false;
if ($hascache) {
foreach ($cmids as $cmid) {
if (array_key_exists($cmid, $coursemodinfo->modinfo)) {
unset($coursemodinfo->modinfo[$cmid]);
$updatedcache = true;
}
}
if ($updatedcache) {
$coursemodinfo->cacherev = -1;
$cache->set_versioned($cachekey, $course->cacherev, $coursemodinfo);
$cache->get_versioned($cachekey, $course->cacherev);
}
}
} finally {
$cache->release_lock($cachekey);
}
}
/**
* For a given course, returns an array of course activity objects
*
* @param stdClass $course Course object
* @param bool $usecache get activities from cache if modinfo exists when $usecache is true
* @return array list of activities
*/
public static function get_array_of_activities(stdClass $course, bool $usecache = false): array {
global $CFG, $DB;
if (empty($course)) {
throw new moodle_exception('courseidnotfound');
}
$rawmods = get_course_mods($course->id);
if (empty($rawmods)) {
return [];
}
$mods = [];
if ($usecache) {
// Get existing cache.
$cachecoursemodinfo = cache::make('core', 'coursemodinfo');
$coursemodinfo = $cachecoursemodinfo->get_versioned($course->id, $course->cacherev);
if ($coursemodinfo !== false) {
$mods = $coursemodinfo->modinfo;
}
}
$courseformat = course_get_format($course);
if ($sections = $DB->get_records('course_sections', ['course' => $course->id],
'section ASC', 'id,section,sequence,visible')) {
// First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
if ($errormessages = course_integrity_check($course->id, $rawmods, $sections)) {
debugging(join('<br>', $errormessages));
$rawmods = get_course_mods($course->id);
$sections = $DB->get_records('course_sections', ['course' => $course->id],
'section ASC', 'id,section,sequence,visible');
}
// Build array of activities.
foreach ($sections as $section) {
if (!empty($section->sequence)) {
$cmids = explode(",", $section->sequence);
$numberofmods = count($cmids);
foreach ($cmids as $cmid) {
// Activity does not exist in the database.
$notexistindb = empty($rawmods[$cmid]);
$activitycached = isset($mods[$cmid]);
if ($activitycached || $notexistindb) {
continue;
}
// Adjust visibleoncoursepage, value in DB may not respect format availability.
$rawmods[$cmid]->visibleoncoursepage = (!$rawmods[$cmid]->visible
|| $rawmods[$cmid]->visibleoncoursepage
|| empty($CFG->allowstealth)
|| !$courseformat->allow_stealth_module_visibility($rawmods[$cmid], $section)) ? 1 : 0;
$mods[$cmid] = new stdClass();
$mods[$cmid]->id = $rawmods[$cmid]->instance;
$mods[$cmid]->cm = $rawmods[$cmid]->id;
$mods[$cmid]->mod = $rawmods[$cmid]->modname;
// Oh dear. Inconsistent names left 'section' here for backward compatibility,
// but also save sectionid and sectionnumber.
$mods[$cmid]->section = $section->section;
$mods[$cmid]->sectionnumber = $section->section;
$mods[$cmid]->sectionid = $rawmods[$cmid]->section;
$mods[$cmid]->module = $rawmods[$cmid]->module;
$mods[$cmid]->added = $rawmods[$cmid]->added;
$mods[$cmid]->score = $rawmods[$cmid]->score;
$mods[$cmid]->idnumber = $rawmods[$cmid]->idnumber;
$mods[$cmid]->visible = $rawmods[$cmid]->visible;
$mods[$cmid]->visibleoncoursepage = $rawmods[$cmid]->visibleoncoursepage;
$mods[$cmid]->visibleold = $rawmods[$cmid]->visibleold;
$mods[$cmid]->groupmode = $rawmods[$cmid]->groupmode;
$mods[$cmid]->groupingid = $rawmods[$cmid]->groupingid;
$mods[$cmid]->indent = $rawmods[$cmid]->indent;
$mods[$cmid]->completion = $rawmods[$cmid]->completion;