-
Notifications
You must be signed in to change notification settings - Fork 6
/
locallib.php
1411 lines (1261 loc) · 56.1 KB
/
locallib.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/>.
/**
* Master block class for use_stats compiler
*
* @package block_use_stats
* @author Valery Fremaux ([email protected])
* @copyright Valery Fremaux ([email protected])
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot.'/blocks/use_stats/classes/engine/session_manager.class.php');
/**
* Wraps the external debug trace.
*
* @param string $msg
* @params int $tracelevel
* @param string $label tag for grouping trace outputs
* @param int $backtracelevel
*/
function block_use_stats_debug_trace($msg, $tracelevel = 0, $label = '', $backtracelevel = 1) {
if (function_exists('debug_trace')) {
debug_trace($msg, $tracelevel, $label, $backtracelevel);
}
}
define('DISPLAY_FULL_COURSE', 0);
define('DISPLAY_TIME_ACTIVITIES', 1);
function use_stats_get_reader() {
return '\core\log\sql_reader';
}
/**
* Extracts a log thread from the first accessible logstore.
*
* @param int $from
* @param int $to
* @param mixed $for a user ID or an array of user IDs
* @param int $course a course object or array of courses // Not used anymore.
*/
function use_stats_extract_logs($from, $to, $for = null, $course = null) {
global $USER, $DB;
$config = get_config('block_use_stats');
$logmanager = get_log_manager();
$readers = $logmanager->get_readers(use_stats_get_reader());
$reader = reset($readers);
if (empty($reader)) {
return false; // No log reader found.
}
if ($reader instanceof \logstore_standard\log\store) {
$courseparm = 'courseid';
} else if ($reader instanceof \logstore_legacy\log\store) {
$courseparm = 'course';
} else {
return;
}
if (!isset($config->lastpingcredit)) {
set_config('lastpingcredit', 15, 'block_use_stats');
$config->lastpingcredit = 15;
}
$for = (is_null($for)) ? $USER->id : $for;
if (is_array($for)) {
$userlist = implode("','", $for);
$userclause = " AND userid IN ('{$userlist}') ";
} else {
$userclause = " AND userid = {$for} ";
}
$courseclause = ''; // not used any more. Get all logs of user.
$courseenrolclause = '';
$inparams = [];
if (!empty($config->enrolmentfilter)) {
/*
* We search last enrol period before "to".
* This is supposed as being the last "valid" working time, other workign time being
* in past sessions.
*/
$sql = "
SELECT
MAX(timestart) as timestart
FROM
{enrol} e,
{user_enrolments} ue
WHERE
$courseenrolclause
e.id = ue.enrolid AND
ue.timestart < ".$to." AND
ue.status = 0
$userclause
";
$lastenrolbeforenow = $DB->get_record_sql($sql, $inparams);
if ($lastenrolbeforenow) {
$from = max($from, $lastenrolbeforenow->timestart);
}
}
if ($reader instanceof \logstore_standard\log\store) {
$sql = "
SELECT
id,
courseid as course,
action,
target,
timecreated as time,
userid,
contextid,
contextinstanceid,
contextlevel,
ip
FROM
{logstore_standard_log}
WHERE
origin != 'cli' AND
timecreated > ? AND
timecreated < ? AND
action != 'failed' AND
((courseid = 0 AND action = 'loggedin') OR
(courseid = 0 AND action = 'loggedout') OR
(1=1
$courseclause))
$userclause AND realuserid IS NULL
ORDER BY
timecreated
";
} else if ($reader instanceof \logstore_legacy\log\store) {
$sql = "
SELECT
id,
course,
action,
time,
module,
userid,
cmid,
ip
FROM
{log}
WHERE
time > ? AND
time < ? AND
((course = 1 AND action = 'login') OR
(course = 1 AND action = 'logout') OR
(1=1
$courseclause))
$userclause
ORDER BY
time
";
} else {
assert(false);
// External DB logs is NOT supported.
}
if ($rs = $DB->get_recordset_sql($sql, [$from, $to])) {
$logs = [];
foreach ($rs as $log) {
$logs[] = $log;
}
$rs->close($rs);
return $logs;
}
return [];
}
/**
* Given an array of log records, make a displayable aggregate. Needs a single
* user log extraction. User will be guessed out from log records.
* @param array $logs
* @param string $from
* @param string $to
* @param string $progress
* @param string $nosessions
* @param object $currentcourse for use with learningtimecheck module only, to integrate time overrides from LTC credit time model.
*/
function use_stats_aggregate_logs($logs, $from = 0, $to = 0, $progress = '', $nosessions = false, $currentcourse = null) {
global $CFG, $DB, $OUTPUT, $USER, $COURSE;
static $cmsections = [];
if (is_null($currentcourse)) {
$currentcourse = $COURSE;
}
$config = get_config('block_use_stats');
$logbuffer = '';
$backdebug = 0;
$dimension = 'module';
$sessionmanager = \block_use_stats\engine\session_manager::instance();
$sessionmanager->set_log_buffer($logbuffer);
if ($config->onesessionpercourse) {
$sessionmanager->set_mode('single');
} else {
$sessionmanager->set_mode('multiple');
}
if (file_exists($CFG->dirroot.'/mod/learningtimecheck/xlib.php')) {
$ltcconfig = get_config('learningtimecheck');
}
if (!empty($config->capturemodules)) {
$modulelist = explode(',', $config->capturemodules);
}
if (isset($config->ignoremodules)) {
$ignoremodulelist = explode(',', $config->ignoremodules);
} else {
$ignoremodulelist = [];
}
$threshold = (0 + @$config->threshold) * MINSECS;
$lastpingcredit = (0 + @$config->lastpingcredit) * MINSECS;
$currentuser = 0;
$automatondebug = optional_param('debug', 0, PARAM_BOOL) && (is_siteadmin() || !empty($USER->realuser));
// Initialise agregation
$aggregate = [];
$aggregate['sessions'] = [];
$aggregate['activities'] = [];
$aggregate['sections'] = [];
$logmanager = get_log_manager();
$readers = $logmanager->get_readers(use_stats_get_reader());
$reader = reset($readers);
$logbuffer = '';
$lastcourseid = 0;
$now = time();
$logbuffer .= "Compiling in course {$currentcourse->id} context \n";
if (!empty($logs)) {
$logs = array_values($logs);
$memlap = 0; // Will store the accumulated time for in the way but out of scope laps.
$logsize = count($logs);
if ($logsize > 15000) {
raise_memory_limit(MEMORY_EXTRA);
}
// Log records loop.
for ($i = 0; $i < $logsize; $i = $nexti) {
$log = $logs[$i];
if ($progress) {
$logbuffer .= "\r".str_replace('%%PROGRESS%%', '('.(0 + @$nexti).'/'.$logsize.')', $progress);
} else {
$logbuffer .= "Log id: {$log->id}\n";
}
// We "guess" here the real identity of the log's owner.
$currentuser = $log->userid;
// Let's get lap time to next log in track.
$nexti = $i + 1;
$lognext = false;
if (isset($logs[$i + 1])) {
/*
* Fetch ahead possible jumps over some non significant logs
* that will be counted within the current log context.
*/
list($lognext, $lap, $nexti) = use_stats_fetch_ahead($logs, $i, $reader);
} else {
// Cap the lastpingcredit to "passed" time only.
$endtime = $log->time + $lastpingcredit;
if ($endtime < $now) {
$lap = $lastpingcredit;
} else {
$lap = $lastpingcredit - ($endtime - $now);
}
}
// Adjust "module" for new logstore if using the standard log. Do it only for current course.
// Other logs deeper info not needed.
if ($reader instanceof \logstore_standard\log\store) {
if (($log->course == $currentcourse->id) || ($log->contextlevel != CONTEXT_MODULE)) {
use_stats_add_module_from_context($log);
} else {
$log->module = 'outoftargetcourse';
$log->cmid = 0;
}
}
if ($automatondebug || $backdebug) {
if ($log->module != 'course') {
$logbuffer .= "[S-$sessionid/$log->id:{$log->module}>{$log->cmid}:";
} else {
$logbuffer .= "[S-$sessionid/$log->id:course>{$log->course}:";
}
$logbuffer .= "{$log->action}] (".date('Y-m-d H:i:s', $log->time)." | $lap) ";
}
$isactionlogin = block_use_stats_is_login_event($log->action);
$isnextactionlogin = block_use_stats_is_login_event(@$lognext->action);
$isovertimed = $lap > $threshold;
// Fix session breaks over the threshold time.
if ($isovertimed) {
$endtime = $log->time + $lastpingcredit;
if ($endtime < $now) {
$lap = $lastpingcredit;
} else {
$lap = $lastpingcredit - ($endtime - $now);
}
}
// Discard unsignificant cases.
if (block_use_stats_is_logout_event($log->action)) {
$memlap = 0;
continue;
}
if ($log->$dimension == 'system' && $log->action == 'failed') {
// Failed login. Non significant.
$memlap = 0;
continue;
}
// This is the most usual case... not a login.
if ($dimension == 'module' && !$isactionlogin) {
$continue = false;
if (!empty($config->capturemodules) && !in_array($log->$dimension, $modulelist)) {
// If not eligible module for aggregation, just add the intermediate laps.
$memlap = $memlap + $lap;
if ($automatondebug || $backdebug) {
$logbuffer .= " ... (I) Not in accepted, time lapped \n";
}
$continue = true;
}
if (!empty($config->ignoremodules) && in_array($log->$dimension, $ignoremodulelist)) {
// If ignored module for aggregations, just add the intermediate time.
$memlap = $memlap + $lap;
if ($automatondebug || $backdebug) {
$logbuffer .= " ... (I) Ignored, time lapped \n";
}
$continue = true;
}
if ($continue) {
continue;
}
}
if (!empty($dimension) && !isset($log->$dimension)) {
if ($automatondebug || $backdebug) {
$logbuffer .= " ...Unkown dimension $dimension \n";
}
}
if ($isactionlogin) {
// We are explicit login.
$memlap = 0;
if ($automatondebug || $backdebug) {
$logbuffer .= " ...Starting session \n";
}
$sessionmanager->start_session($log->userid, $log->time, $log->course);
} else {
// All other cases.
$lap = $lap + $memlap;
if ($automatondebug || $backdebug) {
$logbuffer .= " ...Register in session \n";
}
$sessionmanager->register_event($log->userid, $log->time, $log->course, $lap);
}
// *** Aggegation Start. ***
// Standard global lap aggregation.
if ($log->$dimension == 'course') {
// Those are time assigned to the global course context, outside activities.
if (!array_key_exists('course', $aggregate)) {
$aggregate['course'] = [];
}
if (!array_key_exists($log->course, $aggregate['course'])) {
// Initiate course agregator.
$obj = new StdClass;
$obj->elapsed = $lap;
$obj->events = 1;
$obj->firstaccess = $log->time;
$obj->lastaccess = $log->time;
$obj->firstaccessip = $log->ip;
$obj->lastaccessip = $log->ip;
$aggregate['course'][$log->course] = $obj;
} else {
// Update course agregator.
$aggregate['course'][$log->course]->elapsed += $lap;
$aggregate['course'][$log->course]->events += 1;
$aggregate['course'][$log->course]->lastaccess = $log->time;
$aggregate['course'][$log->course]->lastaccessip = $log->ip;
}
} else {
// All other "activity bound" times.
// 'Real' counters WILL NOT be affected by LTC reports.
if (!array_key_exists('realmodule', $aggregate)) {
$aggregate['realmodule'] = [];
}
if (!array_key_exists(''.$log->$dimension, $aggregate)) {
$aggregate[$log->$dimension] = [];
}
if (!array_key_exists($log->cmid, $aggregate[$log->$dimension])) {
$obj = new StdClass;
$obj->elapsed = $lap;
$obj->events = 1;
$obj->firstaccess = $log->time;
$obj->lastaccess = $log->time;
$aggregate[$log->$dimension][$log->cmid] = $obj;
} else {
$aggregate[$log->$dimension][$log->cmid]->elapsed += $lap;
$aggregate[$log->$dimension][$log->cmid]->events += 1;
$aggregate[$log->$dimension][$log->cmid]->lastaccess = $log->time;
}
if (!array_key_exists($log->cmid, $aggregate['realmodule'])) {
$obj = new StdClass;
$obj->elapsed = $lap;
$obj->events = 1;
$obj->firstaccess = $log->time;
$obj->lastaccess = $log->time;
$aggregate['realmodule'][$log->cmid] = $obj;
} else {
$aggregate['realmodule'][$log->cmid]->elapsed += $lap;
$aggregate['realmodule'][$log->cmid]->events += 1;
$aggregate['realmodule'][$log->cmid]->lastaccess = $log->time;
}
}
// Standard non course level aggregation.
if ($log->$dimension != 'course') {
if ($log->cmid) {
$key = 'activities';
if (!array_key_exists($log->cmid, $cmsections)) {
// Put in static cache.
$cmsections[$log->cmid] = $DB->get_field('course_modules', 'section', ['id' => $log->cmid]);
}
} else {
$key = 'other';
}
if (!array_key_exists($key, $aggregate)) {
$aggregate[$key] = [];
}
if (!array_key_exists($log->course, $aggregate[$key])) {
$obj = new StdClass();
$obj->elapsed = $lap;
$obj->events = 1;
$aggregate[$key][$log->course] = $obj;
} else {
$aggregate[$key][$log->course]->elapsed += $lap;
$aggregate[$key][$log->course]->events += 1;
}
if ($key == 'activities') {
// Aggregate by section.
$sectionid = $cmsections[0 + $log->cmid];
if (!array_key_exists('section', $aggregate)) {
$aggregate['section'] = [];
}
if (!array_key_exists('realsection', $aggregate)) {
$aggregate['realsection'] = [];
}
if (!array_key_exists('coursesection', $aggregate)) {
$aggregate['coursesection'] = [];
}
if (is_numeric($sectionid)) {
if (!array_key_exists($log->course, $aggregate['coursesection'])) {
$aggregate['coursesection'][$log->course] = [];
}
if (!array_key_exists($sectionid, $aggregate['coursesection'][$log->course])) {
$obj = new StdClass();
$obj->elapsed = $lap;
$obj->events = 1;
$aggregate['coursesection'][$log->course][$sectionid] = $obj;
} else {
$aggregate['coursesection'][$log->course][$sectionid]->elapsed += $lap;
$aggregate['coursesection'][$log->course][$sectionid]->events += 1;
}
if (!array_key_exists($sectionid, $aggregate['section'])) {
$obj = new StdClass();
$obj->elapsed = $lap;
$obj->events = 1;
$aggregate['section'][$sectionid] = $obj;
} else {
$aggregate['section'][$sectionid]->elapsed += $lap;
$aggregate['section'][$sectionid]->events += 1;
}
if (!array_key_exists($sectionid, $aggregate['realsection'])) {
$obj = new StdClass();
$obj->elapsed = $lap;
$obj->events = 1;
$aggregate['realsection'][$sectionid] = $obj;
} else {
$aggregate['realsection'][$sectionid]->elapsed += $lap;
$aggregate['realsection'][$sectionid]->events += 1;
}
}
}
}
// Standard course level lap aggregation.
if (!array_key_exists('coursetotal', $aggregate)) {
$aggregate['coursetotal'] = [];
}
if (!array_key_exists($log->course, $aggregate['coursetotal'])) {
$obj = new StdClass;
$obj->elapsed = $lap;
$obj->events = 1;
$obj->firstaccess = $log->time;
$obj->lastaccess = $log->time;
$aggregate['coursetotal'][$log->course] = $obj;
} else {
$aggregate['coursetotal'][$log->course]->elapsed += $lap;
$aggregate['coursetotal'][$log->course]->events += 1;
$aggregate['coursetotal'][$log->course]->lastaccess = $log->time;
}
$origintime = $log->time;
$lastcourseid = $log->course;
}
}
// Check assertions.
if (!empty($aggregate['coursetotal'])) {
foreach (array_keys($aggregate['coursetotal']) as $courseid) {
if ($courseid == 0) {
continue;
}
$c = $aggregate['course'][$courseid]->events ?? 0;
$a = $aggregate['activities'][$courseid]->events ?? 0;
$o = $aggregate['other'][$courseid]->events ?? 0;
if ($aggregate['coursetotal'][$courseid]->events != $c + $a + $o) {
echo "Bad sumcheck on events for course $courseid <br/>";
}
$ct = $aggregate['course'][$courseid]->elapsed ?? 0;
$at = $aggregate['activities'][$courseid]->elapsed ?? 0;
$ot = $aggregate['other'][$courseid]->elapsed ?? 0;
$tot = $aggregate['coursetotal'][$courseid]->elapsed ?? 0;
if ($tot != ($ct + $at + $ot)) {
echo "Bad sumcheck on time for course $courseid <br/>";
}
// Sum of section times should be activity time. this is valid for single course...
$st = 0;
if (array_key_exists('coursesection', $aggregate) && array_key_exists($courseid, $aggregate['coursesection'])) {
foreach ($aggregate['coursesection'][$courseid] as $s) {
$st += $s->elapsed;
}
}
if ($st != $at) {
throw new Exception("Bad sumcheck on section time for course $courseid : section time is $st / activities time is $at <br/>");
}
}
}
if (!$nosessions) {
$sessionmanager->save();
$sessionmanager->aggregate($aggregate);
}
// This is our last change to guess a user when no logs available.
if (empty($currentuser)) {
$currentuser = optional_param('userid', $USER->id, PARAM_INT);
}
// We need check if time credits are used and override by credit earned.
if (!empty($ltcconfig->allowoverrideusestats)) {
if (file_exists($CFG->dirroot.'/mod/learningtimecheck/xlib.php')) {
include_once($CFG->dirroot.'/mod/learningtimecheck/xlib.php');
$checklists = learningtimecheck_get_instances($currentcourse->id, true); // Get timecredit enabled ones.
if ($checklists) {
foreach ($checklists as $ckl) {
if ($currentuser == 0) {
continue;
}
if ($credittimes = learningtimecheck_get_credittimes($ckl->id, 0, $currentuser)) {
foreach ($credittimes as $credittime) {
if (empty($credittime->enablecredit)) {
continue;
}
// If credit time is assigned to NULL course module, we assign it to the checklist itself.
if (!$credittime->cmid) {
$cklcm = get_coursemodule_from_instance('learningtimecheck', $ckl->id);
$credittime->cmid = $cklcm->id;
}
if (!array_key_exists($credittime->cmid, $cmsections)) {
$params = ['id' => $credittime->cmid];
$cmsections[$credittime->cmid] = $DB->get_field('course_modules', 'section', $params);
}
$sectionid = @$cmsections[$credittime->cmid];
$cond = 0;
if (!empty($ltcconfig->strictcredits)) {
/*
* If strict credits, the reported time cannot be higher to the standard time credit for the
* item. The user is credited with the real time if lower then the credit, or the credit
* as peak cutoff. This does not care of the item being checked or not.
*/
if (isset($aggregate[$credittime->modname][$credittime->cmid])) {
$cmelapsed = $aggregate[$credittime->modname][$credittime->cmid]->elapsed ?? 0;
if ($ltcconfig->strictcredits == 1) {
// if credit is over real time, apply credit.
$cond = ($credittime->credittime >= $cmelapsed) &&
!empty($cmelapsed);
} else if ($ltcconfig->strictcredits == 2) {
// if credit is under real time, apply credit.
$cond = $credittime->credittime <= $cmelapsed;
} else {
// Apply cedit anyway.
if (!empty($cmelapsed)) {
$cond = 1;
}
}
} else {
// Course module counter never initialized, but it has been marked as completed.
if ($credittime->credittime && $credittime->ismarked) {
$cond = 1;
$aggregate[$credittime->modname][$credittime->cmid] = new StdClass;
$aggregate[$credittime->modname][$credittime->cmid]->elapsed = 0;
$aggregate[$credittime->modname][$credittime->cmid]->events = 0;
}
}
if ($cond) {
// Cut over with credit time.
$diff = $credittime->credittime - $cmelapsed ?? 0;
@$aggregate[$credittime->modname][$credittime->cmid]->real = $cmelapsed ?? 0;
@$aggregate[$credittime->modname][$credittime->cmid]->elapsed = $credittime->credittime;
@$aggregate[$credittime->modname][$credittime->cmid]->timesource = 'credit';
// Fix the global aggregators accordingly.
debug_trace("Fixing globals ltccutover {$ckl->course}: ".$diff);
@$aggregate['coursetotal'][$ckl->course]->elapsed += $diff;
@$aggregate['activities'][$ckl->course]->elapsed += $diff;
@$aggregate['section'][$sectionid]->elapsed += $diff;
} else {
if (!empty($credittime->credittime)) {
$aggregate[$credittime->modname][$credittime->cmid]->credit = $credittime->credittime;
}
}
} else {
$cmelapsed = $aggregate[$credittime->modname][$credittime->cmid]->elapsed ?? 0;
if ($credittime->ismarked) {
// This processes validated modules that although have no logs.
if (!isset($aggregate[$credittime->modname][$credittime->cmid])) {
// Initiate value.
$diff = $credittime->credittime;
$aggregate[$credittime->modname][$credittime->cmid] = new StdClass;
$aggregate[$credittime->modname][$credittime->cmid]->elapsed = 0;
$aggregate[$credittime->modname][$credittime->cmid]->events = 0;
$fa = @$aggregate[$credittime->modname][$credittime->cmid]->firstaccess;
$aggregate[$credittime->modname][$credittime->cmid]->firstaccess = $fa;
$aggregate[$credittime->modname][$credittime->cmid]->lastaccess = 0;
// Fix the global aggregators accordingly.
debug_trace("Fixing globals ltccutover no logs {$ckl->course}: ".$diff);
@$aggregate['coursetotal'][$ckl->course]->elapsed += $diff;
$aggregate['activities'][$ckl->course]->elapsed += $diff;
@$aggregate['section'][$sectionid]->elapsed += $diff;
}
if ($cmelapsed <= $credittime->credittime) {
// Override value if not enough spent time.
$diff = $credittime->credittime - $cmelapsed;
$aggregate[$credittime->modname][$credittime->cmid]->elapsed = $credittime->credittime;
$aggregate[$credittime->modname][$credittime->cmid]->timesource = 'credit';
$fa = @$aggregate[$credittime->modname][$credittime->cmid]->lastaccess;
$aggregate[$credittime->modname][$credittime->cmid]->lastaccess = $fa;
// Fix the global aggregators accordingly.
// debug_trace("Fixing globals ltccutunder no logs {$ckl->course}: ".$diff);
@$aggregate['coursetotal'][$ckl->course]->elapsed += $diff;
$aggregate['activities'][$ckl->course]->elapsed += $diff;
@$aggregate['section'][$sectionid]->elapsed += $diff;
}
}
}
}
}
if ($declarativetimes = learningtimecheck_get_declaredtimes($ckl->id, 0, $currentuser)) {
foreach ($declarativetimes as $declaredtime) {
// If declared time is assigned to NULL course module, we assign it to the checklist itself.
if (!$declaredtime->cmid) {
$cklcm = get_coursemodule_from_instance('learningtimecheck', $ckl->id);
$declaredtime->cmid = $cklcm->id;
}
$cmelapsed = $aggregate[$declaredtime->modname][$declaredtime->cmid]->elapsed;
if (!empty($ltcconfig->strict_declared)) {
// If strict declared, do override time even if real time is higher.
$diff = $declaredtime->declaredtime - $cmelapsed;
$aggregate[$declaredtime->modname][$declaredtime->cmid]->elapsed = $declaredtime->declaredtime;
$aggregate[$declaredtime->modname][$declaredtime->cmid]->timesource = 'declared';
// Fix the global aggregators accordingly.
@$aggregate['coursetotal'][$ckl->course]->elapsed += $diff;
$aggregate['activities'][$ckl->course]->elapsed += $diff;
@$aggregate['section'][$sectionid]->elapsed += $diff;
} else {
// This processes validated modules that although have no logs.
if (!isset($aggregate[$declaredtime->modname][$declaredtime->cmid])) {
$diff = $declaredtime->declaredtime;
$aggregate[$declaredtime->modname][$declaredtime->cmid] = new StdClass;
$aggregate[$declaredtime->modname][$declaredtime->cmid]->elapsed = 0;
$aggregate[$declaredtime->modname][$declaredtime->cmid]->events = 0;
$fa = @$aggregate[$credittime->modname][$credittime->cmid]->firstaccess;
$aggregate[$declaredtime->modname][$declaredtime->cmid]->firstaccess = $fa;
$aggregate[$declaredtime->modname][$declaredtime->cmid]->lastaccess = 0;
// Fix the global aggregators accordingly.
// debug_trace("Fixing globals declared cutover no logs {$ckl->course}: ".$diff);
@$aggregate['coursetotal'][$ckl->course]->elapsed += $diff;
$aggregate['activities'][$ckl->course]->elapsed += $diff;
@$aggregate['section'][$sectionid]->elapsed += $diff;
}
if ($aggregate[$declaredtime->modname][$declaredtime->cmid]->elapsed <= $declaredtime->declaredtime) {
$aggregate[$declaredtime->modname][$declaredtime->cmid]->elapsed = $declaredtime->declaredtime;
$aggregate[$declaredtime->modname][$declaredtime->cmid]->timesource = 'declared';
$fa = @$aggregate[$credittime->modname][$credittime->cmid]->lastaccess;
$aggregate[$declaredtime->modname][$declaredtime->cmid]->lastaccess = $fa;
// Fix the global aggregators accordingly.
// debug_trace("Fixing globals declared cutunder no logs {$ckl->course}: ".$diff);
@$aggregate['coursetotal'][$ckl->course]->elapsed += $diff;
$aggregate['activities'][$ckl->course]->elapsed += $diff;
@$aggregate['section'][$sectionid]->elapsed += $diff;
}
}
}
}
}
} else {
if (function_exists('debug_trace')) {
debug_trace("Trainingsessions : No checklist found ");
}
}
}
}
// We need finally adjust some times from time recording activities.
if (array_key_exists('scorm', $aggregate)) {
foreach (array_keys($aggregate['scorm']) as $cmid) {
if ($cm = $DB->get_record('course_modules', ['id' => $cmid])) {
// These are all scorms.
// Scorm activities have their accurate recorded time.
$realtotaltime = 0;
$select = "
element = 'cmi.core.total_time' AND
scormid = $cm->instance AND
userid = $currentuser
";
if ($from) {
$select .= " AND timemodified >= $from ";
}
if ($to) {
$select .= " AND timemodified <= $to ";
}
if ($realtimes = $DB->get_records_select('scorm_scoes_track', $select, [], 'id, element, value')) {
foreach ($realtimes as $rt) {
preg_match("/(\d\d):(\d\d):(\d\d)\./", $rt->value, $matches);
$realtotaltime += $matches[1] * 3600 + $matches[2] * 60 + $matches[3];
}
}
if ($aggregate['scorm'][$cmid]->elapsed < $realtotaltime) {
$diff = $realtotaltime - $aggregate['scorm'][$cmid]->elapsed;
$aggregate['scorm'][$cmid]->elapsed += $diff;
if (!array_key_exists($cm->course, $aggregate['coursetotal'])) {
$obj = new StdClass();
$obj->elapsed = 0;
$aggregate['coursetotal'][$cm->course] = $obj;
$aggregate['activities'][$cm->course] = $obj;
}
$aggregate['coursetotal'][$cm->course]->elapsed += $diff;
$aggregate['activities'][$cm->course]->elapsed += $diff;
}
}
}
}
// Add some control values.
if (!empty($aggregate['coursetotal'])) {
foreach ($aggregate['coursetotal'] as $courseid => $stat) {
$t = block_use_stats_format_time($aggregate['coursetotal'][$courseid]->elapsed);
$aggregate['coursetotal'][$courseid]->elapsedhtml = $t;
}
}
if (!empty($aggregate['activities'])) {
foreach ($aggregate['activities'] as $courseid => $stat) {
$t = block_use_stats_format_time($aggregate['activities'][$courseid]->elapsed);
$aggregate['activities'][$courseid]->elapsedhtml = $t;
}
}
if (!empty($aggregate['other'])) {
foreach ($aggregate['other'] as $courseid => $stat) {
$t = block_use_stats_format_time($aggregate['other'][$courseid]->elapsed);
$aggregate['other'][$courseid]->elapsedhtml = $t;
}
}
if (!empty($aggregate['course'])) {
foreach ($aggregate['course'] as $courseid => $stat) {
$t = block_use_stats_format_time($aggregate['course'][$courseid]->elapsed);
$aggregate['course'][$courseid]->elapsedhtml = $t;
}
}
if ($backdebug) {
debug_trace($logbuffer);
}
if ($automatondebug) {
echo '<pre>';
echo $logbuffer;
echo '</pre>';
}
if ($automatondebug) {
echo '<h2>Aggregator output</h2>';
block_use_stats_render_aggregate($aggregate);
}
// Pass compilation boundaries for further use.
$aggregate['from'] = $from;
$aggregate['to'] = $to;
return $aggregate;
}
/**
* fetch ahead the next valid log to be considered
* @param arrayref $logs the logs track array
* @param int $i the current log track index
* @param object $reader the actual valid log reader
* @return an array containing the next log record, the cumulated lap time for the current
* processed record and the next log index
*/
function use_stats_fetch_ahead(&$logs, $i, $reader) {
$log = $logs[$i];
$lastlog = $logs[$i + 1];
$lognext = @$logs[$i + 2];
$j = $i + 1;
// Resolve the "graded" bias.
if ($reader instanceof \logstore_standard\log\store) {
while (isset($lognext) && ($lastlog->action == 'graded') && ($lastlog->target == 'user')) {
$j++;
$lastlog = $logs[$j];
$lognext = @$logs[$j + 1];
}
}
$lap = $lastlog->time - $log->time;
return [$lastlog, $lap, $j];
}
/**
* this new function uses the log storage enhancement with precalculated gaps
* in order to extract multicourse time aggregations
* @param objectref &$result to be filled in
* @param string $from
* @param string $to
* @param string $users
* @param string $courses
* @param string $dimensions
*/
function use_stats_site_aggregate_time(&$result, $from = 0, $to = 0, $users = null, $courses = null,
$dimensions = 'course,user,institution') {
global $DB;
$config = get_config('block_use_stats');
$logmanager = get_log_manager();
$readers = $logmanager->get_readers(use_stats_get_reader());
$reader = reset($readers);
if (empty($reader)) {
return false; // No log reader found.
}
if ($reader instanceof \logstore_standard\log\store) {
$coursefield = 'courseid';
} else if ($reader instanceof \logstore_legacy\log\store) {
$coursefield = 'course';
}
// Make quick accessible memory variables to test.
$dimensionsarr = explode(',', $dimensions);
$courseresult = in_array('course', $dimensionsarr);
$userresult = in_array('user', $dimensionsarr);
$institutionresult = in_array('institution', $dimensionsarr);
if ($to == 0) {
$to = time();
}
$userclause = '';
if (!empty($users)) {
$userclause = ' AND userid IN ('.implode(',', $users).' )';
}
$courseclause = '';
if (!empty($courses)) {
$courseclause = ' AND '.$coursefield.' IN ('.implode(',', $courses).' )';
}
if ($reader instanceof \logstore_standard\log\store) {
$sql = "
SELECT
l.id,
l.timecreated as time,
l.userid,
l.courseid as course,
usl.gap,
u.institution,
u.department,
u.city,
u.country
FROM
{logstore_standard_log} l,
{use_stats_log} usl,
{user} u
WHERE
u.id = l.userid AND
time >= ? AND
time <= ?
$courseclause
$userclause
";
} else if ($reader instanceof \logstore_legacy\log\store) {
$sql = "
SELECT
l.id,
l.time,
l.userid,
l.course,
usl.gap,
u.institution,
u.department,
u.city,
u.country
FROM
{log} l,
{use_stats_log} usl,
{user} u
WHERE
u.id = l.userid AND
time >= ? AND
time <= ?
$courseclause
$userclause
";
}
// Pre_loop structure inits.
if ($institutionresult) {
$result->institutions = [];
$institutionid = 1;
}