forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statslib.php
1662 lines (1369 loc) · 63.9 KB
/
statslib.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
// THESE CONSTANTS ARE USED FOR THE REPORTING PAGE.
define('STATS_REPORT_LOGINS',1); // double impose logins and unqiue logins on a line graph. site course only.
define('STATS_REPORT_READS',2); // double impose student reads and teacher reads on a line graph.
define('STATS_REPORT_WRITES',3); // double impose student writes and teacher writes on a line graph.
define('STATS_REPORT_ACTIVITY',4); // 2+3 added up, teacher vs student.
define('STATS_REPORT_ACTIVITYBYROLE',5); // all activity, reads vs writes, seleted by role.
// user level stats reports.
define('STATS_REPORT_USER_ACTIVITY',7);
define('STATS_REPORT_USER_ALLACTIVITY',8);
define('STATS_REPORT_USER_LOGINS',9);
define('STATS_REPORT_USER_VIEW',10); // this is the report you see on the user profile.
// admin only ranking stats reports
define('STATS_REPORT_ACTIVE_COURSES',11);
define('STATS_REPORT_ACTIVE_COURSES_WEIGHTED',12);
define('STATS_REPORT_PARTICIPATORY_COURSES',13);
define('STATS_REPORT_PARTICIPATORY_COURSES_RW',14);
// start after 0 = show dailies.
define('STATS_TIME_LASTWEEK',1);
define('STATS_TIME_LAST2WEEKS',2);
define('STATS_TIME_LAST3WEEKS',3);
define('STATS_TIME_LAST4WEEKS',4);
// start after 10 = show weeklies
define('STATS_TIME_LAST2MONTHS',12);
define('STATS_TIME_LAST3MONTHS',13);
define('STATS_TIME_LAST4MONTHS',14);
define('STATS_TIME_LAST5MONTHS',15);
define('STATS_TIME_LAST6MONTHS',16);
// start after 20 = show monthlies
define('STATS_TIME_LAST7MONTHS',27);
define('STATS_TIME_LAST8MONTHS',28);
define('STATS_TIME_LAST9MONTHS',29);
define('STATS_TIME_LAST10MONTHS',30);
define('STATS_TIME_LAST11MONTHS',31);
define('STATS_TIME_LASTYEAR',32);
// different modes for what reports to offer
define('STATS_MODE_GENERAL',1);
define('STATS_MODE_DETAILED',2);
define('STATS_MODE_RANKED',3); // admins only - ranks courses
/**
* Print daily cron progress
* @param string $ident
*/
function stats_daily_progress($ident) {
static $start = 0;
static $init = 0;
if ($ident == 'init') {
$init = $start = time();
return;
}
$elapsed = time() - $start;
$start = time();
if (debugging('', DEBUG_ALL)) {
mtrace("$ident:$elapsed ", '');
} else {
mtrace('.', '');
}
}
/**
* Execute daily statistics gathering
* @param int $maxdays maximum number of days to be processed
* @return boolean success
*/
function stats_cron_daily($maxdays=1) {
global $CFG;
$now = time();
// read last execution date from db
if (!$timestart = get_config(NULL, 'statslastdaily')) {
$timestart = stats_get_base_daily(stats_get_start_from('daily'));
set_config('statslastdaily', $timestart);
}
$nextmidnight = stats_get_next_day_start($timestart);
// are there any days that need to be processed?
if ($now < $nextmidnight) {
return true; // everything ok and up-to-date
}
$timeout = empty($CFG->statsmaxruntime) ? 60*60*24 : $CFG->statsmaxruntime;
if (!set_cron_lock('statsrunning', $now + $timeout)) {
return false;
}
// fisrt delete entries that should not be there yet
delete_records_select('stats_daily', "timeend > $timestart");
delete_records_select('stats_user_daily', "timeend > $timestart");
// Read in a few things we'll use later
$viewactions = implode(',', stats_get_action_names('view'));
$postactions = implode(',', stats_get_action_names('post'));
$guest = get_guest();
$guestrole = get_guest_role();
list($enroljoin, $enrolwhere) = stats_get_enrolled_sql($CFG->statscatdepth, true);
list($enroljoin_na, $enrolwhere_na) = stats_get_enrolled_sql($CFG->statscatdepth, false);
list($fpjoin, $fpwhere) = stats_get_enrolled_sql(0, true);
mtrace("Running daily statistics gathering, starting at $timestart:");
$days = 0;
$failed = false; // failed stats flag
while ($now > $nextmidnight) {
if ($days >= $maxdays) {
mtrace("...stopping early, reached maximum number of $maxdays days - will continue next time.");
set_cron_lock('statsrunning', null);
return false;
}
$days++;
@set_time_limit($timeout - 200);
if ($days > 1) {
// move the lock
set_cron_lock('statsrunning', time() + $timeout, true);
}
$daystart = time();
$timesql = "l.time >= $timestart AND l.time < $nextmidnight";
$timesql1 = "l1.time >= $timestart AND l1.time < $nextmidnight";
$timesql2 = "l2.time >= $timestart AND l2.time < $nextmidnight";
stats_daily_progress('init');
/// find out if any logs available for this day
$sql = "SELECT 'x'
FROM {$CFG->prefix}log l
WHERE $timesql";
$logspresent = get_records_sql($sql, 0, 1);
/// process login info first
$sql = "INSERT INTO {$CFG->prefix}stats_user_daily (stattype, timeend, courseid, userid, statsreads)
SELECT 'logins' AS stattype, $nextmidnight AS timeend, ".SITEID." AS courseid,
l.userid, count(l.id) AS statsreads
FROM {$CFG->prefix}log l
WHERE action = 'login' AND $timesql
GROUP BY stattype, timeend, courseid, userid
HAVING count(l.id) > 0";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('1');
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'logins' AS stattype, $nextmidnight AS timeend, ".SITEID." as courseid, 0,
COALESCE((SELECT SUM(statsreads)
FROM {$CFG->prefix}stats_user_daily s1
WHERE s1.stattype = 'logins' AND timeend = $nextmidnight), 0) AS stat1,
(SELECT COUNT('x')
FROM {$CFG->prefix}stats_user_daily s2
WHERE s2.stattype = 'logins' AND timeend = $nextmidnight) AS stat2";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('2');
// Enrolments and active enrolled users
//
// Unfortunately, we do not know how many users were registered
// at given times in history :-(
// - stat1: enrolled users
// - stat2: enrolled users active in this period
// - enrolment is defined now as having course:view capability in
// course context or above, we look 3 cats upwards only and ignore prevent
// and prohibit caps to simplify it
// - SITEID is specialcased here, because it's all about default enrolment
// in that case, we'll count non-deleted users.
//
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments' AS stattype, $nextmidnight AS timeend,
pl.courseid, pl.roleid, COUNT(DISTINCT pl.userid) AS stat1, 0 AS stat2
FROM (SELECT DISTINCT ra.roleid, ra.userid, c.id as courseid
FROM {$CFG->prefix}role_assignments ra $enroljoin_na
WHERE $enrolwhere_na
) pl
GROUP BY stattype, timeend, pl.courseid, pl.roleid, stat2";
if (!execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('3');
// using table alias in UPDATE does not work in pg < 8.2
$sql = "UPDATE {$CFG->prefix}stats_daily
SET stat2 = (SELECT COUNT(DISTINCT ra.userid)
FROM {$CFG->prefix}role_assignments ra $enroljoin_na
WHERE ra.roleid = {$CFG->prefix}stats_daily.roleid AND
c.id = {$CFG->prefix}stats_daily.courseid AND
$enrolwhere_na AND
EXISTS (SELECT 'x'
FROM {$CFG->prefix}log l
WHERE l.course = {$CFG->prefix}stats_daily.courseid AND
l.userid = ra.userid AND $timesql))
WHERE {$CFG->prefix}stats_daily.stattype = 'enrolments' AND
{$CFG->prefix}stats_daily.timeend = $nextmidnight AND
{$CFG->prefix}stats_daily.courseid IN
(SELECT DISTINCT l.course
FROM {$CFG->prefix}log l
WHERE $timesql)";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('4');
/// now get course total enrolments (roleid==0) - except frontpage
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments' AS stattype, $nextmidnight AS timeend,
c.id, 0 AS nroleid, COUNT(DISTINCT ra.userid) AS stat1, 0 AS stat2
FROM {$CFG->prefix}role_assignments ra $enroljoin_na
WHERE c.id <> ".SITEID." AND $enrolwhere_na
GROUP BY stattype, timeend, c.id, nroleid, stat2
HAVING COUNT(DISTINCT ra.userid) > 0";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('5');
$sql = "UPDATE {$CFG->prefix}stats_daily
SET stat2 = (SELECT COUNT(DISTINCT ra.userid)
FROM {$CFG->prefix}role_assignments ra $enroljoin_na
WHERE c.id = {$CFG->prefix}stats_daily.courseid AND
$enrolwhere_na AND
EXISTS (SELECT 'x'
FROM {$CFG->prefix}log l
WHERE l.course = {$CFG->prefix}stats_daily.courseid AND
l.userid = ra.userid AND $timesql))
WHERE {$CFG->prefix}stats_daily.stattype = 'enrolments' AND
{$CFG->prefix}stats_daily.timeend = $nextmidnight AND
{$CFG->prefix}stats_daily.roleid = 0 AND
{$CFG->prefix}stats_daily.courseid IN
(SELECT l.course
FROM {$CFG->prefix}log l
WHERE $timesql AND l.course <> ".SITEID.")";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('6');
/// frontapge(==site) enrolments total
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments', $nextmidnight, ".SITEID.", 0,
(SELECT COUNT('x')
FROM {$CFG->prefix}user u
WHERE u.deleted = 0) AS stat1,
(SELECT COUNT(DISTINCT u.id)
FROM {$CFG->prefix}user u
JOIN {$CFG->prefix}log l ON l.userid = u.id
WHERE u.deleted = 0 AND $timesql) AS stat2";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('7');
if (empty($CFG->defaultfrontpageroleid)) { // 1.9 only, so far
$defaultfproleid = 0;
} else {
$defaultfproleid = $CFG->defaultfrontpageroleid;
}
/// Default frontpage role enrolments are all site users (not deleted)
if ($defaultfproleid) {
// first remove default frontpage role counts if created by previous query
$sql = "DELETE
FROM {$CFG->prefix}stats_daily
WHERE stattype = 'enrolments' AND courseid = ".SITEID." AND
roleid = $defaultfproleid AND timeend = $nextmidnight";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('8');
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments', $nextmidnight, ".SITEID.", $defaultfproleid,
(SELECT COUNT('x')
FROM {$CFG->prefix}user u
WHERE u.deleted = 0) AS stat1,
(SELECT COUNT(DISTINCT u.id)
FROM {$CFG->prefix}user u
JOIN {$CFG->prefix}log l ON l.userid = u.id
WHERE u.deleted = 0 AND $timesql) AS stat2";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('9');
} else {
stats_daily_progress('x');
stats_daily_progress('x');
}
/// individual user stats (including not-logged-in) in each course, this is slow - reuse this data if possible
$sql = "INSERT INTO {$CFG->prefix}stats_user_daily (stattype, timeend, courseid, userid, statsreads, statswrites)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, d.courseid, d.userid,
(SELECT COUNT('x')
FROM {$CFG->prefix}log l
WHERE l.userid = d.userid AND
l.course = d.courseid AND $timesql AND
l.action IN ($viewactions)) AS statsreads,
(SELECT COUNT('x')
FROM {$CFG->prefix}log l
WHERE l.userid = d.userid AND
l.course = d.courseid AND $timesql AND
l.action IN ($postactions)) AS statswrites
FROM (SELECT DISTINCT u.id AS userid, l.course AS courseid
FROM {$CFG->prefix}user u, {$CFG->prefix}log l
WHERE u.id = l.userid AND $timesql
UNION
SELECT 0 AS userid, ".SITEID." AS courseid) d";
// can not use group by here because pg can not handle it :-(
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('10');
/// how many view/post actions in each course total
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, c.id AS courseid, 0,
(SELECT COUNT('x')
FROM {$CFG->prefix}log l1
WHERE l1.course = c.id AND l1.action IN ($viewactions) AND
$timesql1) AS stat1,
(SELECT COUNT('x')
FROM {$CFG->prefix}log l2
WHERE l2.course = c.id AND l2.action IN ($postactions) AND
$timesql2) AS stat2
FROM {$CFG->prefix}course c
WHERE EXISTS (SELECT 'x'
FROM {$CFG->prefix}log l
WHERE l.course = c.id and $timesql)";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('11');
/// how many view actions for each course+role - excluding guests and frontpage
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, pl.courseid, pl.roleid,
SUM(sud.statsreads) AS stat1, SUM(sud.statswrites) AS stat2
FROM {$CFG->prefix}stats_user_daily sud,
(SELECT DISTINCT ra.userid, ra.roleid, c.id AS courseid
FROM {$CFG->prefix}role_assignments ra $enroljoin
WHERE c.id <> ".SITEID." AND
ra.roleid <> $guestrole->id AND ra.userid <> $guest->id AND
$enrolwhere
) pl
WHERE sud.userid = pl.userid AND sud.courseid = pl.courseid AND
sud.timeend = $nextmidnight AND sud.stattype='activity'
GROUP BY stattype, timeend, pl.courseid, pl.roleid
HAVING SUM(sud.statsreads) > 0 OR SUM(sud.statswrites) > 0";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('12');
/// how many view actions from guests only in each course - excluding frontpage
/// (guest is anybody with guest role or no role with course:view in course - this may not work properly if category limit too low)
/// normal users may enter course with temporary guest acces too
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, sud.courseid, $guestrole->id AS nroleid,
SUM(sud.statsreads) AS stat1, SUM(sud.statswrites) AS stat2
FROM {$CFG->prefix}stats_user_daily sud
WHERE sud.timeend = $nextmidnight AND sud.courseid <> ".SITEID." AND
sud.stattype='activity' AND
(sud.userid = $guest->id OR sud.userid
NOT IN (SELECT ra.userid
FROM {$CFG->prefix}role_assignments ra $enroljoin
WHERE c.id <> ".SITEID." AND ra.roleid <> $guestrole->id AND
$enrolwhere))
GROUP BY stattype, timeend, sud.courseid, nroleid
HAVING SUM(sud.statsreads) > 0 OR SUM(sud.statswrites) > 0";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('13');
/// how many view actions for each role on frontpage - excluding guests, not-logged-in and default frontpage role
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, pl.courseid, pl.roleid,
SUM(sud.statsreads) AS stat1, SUM(sud.statswrites) AS stat2
FROM {$CFG->prefix}stats_user_daily sud,
(SELECT DISTINCT ra.userid, ra.roleid, c.id AS courseid
FROM {$CFG->prefix}role_assignments ra $enroljoin
WHERE c.id = ".SITEID." AND
ra.roleid <> $defaultfproleid AND
ra.roleid <> $guestrole->id AND ra.userid <> $guest->id AND
$enrolwhere
) pl
WHERE sud.userid = pl.userid AND sud.courseid = pl.courseid AND
sud.timeend = $nextmidnight AND sud.stattype='activity'
GROUP BY stattype, timeend, pl.courseid, pl.roleid
HAVING SUM(sud.statsreads) > 0 OR SUM(sud.statswrites) > 0";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('14');
/// how many view actions for default frontpage role on frontpage only
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, sud.courseid, $defaultfproleid AS nroleid,
SUM(sud.statsreads) AS stat1, SUM(sud.statswrites) AS stat2
FROM {$CFG->prefix}stats_user_daily sud
WHERE sud.timeend = $nextmidnight AND sud.courseid = ".SITEID." AND
sud.stattype='activity' AND
sud.userid <> $guest->id AND sud.userid <> 0 AND sud.userid
NOT IN (SELECT ra.userid
FROM {$CFG->prefix}role_assignments ra $fpjoin
WHERE c.id = ".SITEID." AND ra.roleid <> $guestrole->id AND
ra.roleid <> $defaultfproleid AND $fpwhere)
GROUP BY stattype, timeend, sud.courseid, nroleid
HAVING SUM(sud.statsreads) > 0 OR SUM(sud.statswrites) > 0";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('15');
/// how many view actions for guests or not-logged-in on frontpage
$sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, ".SITEID." AS courseid, $guestrole->id AS nroleid,
SUM(pl.statsreads) AS stat1, SUM(pl.statswrites) AS stat2
FROM (SELECT sud.statsreads, sud.statswrites
FROM {$CFG->prefix}stats_user_daily sud
WHERE (sud.userid = $guest->id OR sud.userid = 0) AND
sud.timeend = $nextmidnight AND sud.courseid = ".SITEID." AND
sud.stattype='activity'
) pl
GROUP BY stattype, timeend, courseid, nroleid
HAVING SUM(pl.statsreads) > 0 OR SUM(pl.statswrites) > 0";
if ($logspresent and !execute_sql($sql, false)) {
$failed = true;
break;
}
stats_daily_progress('16');
// remember processed days
set_config('statslastdaily', $nextmidnight);
mtrace(" finished until $nextmidnight: ".userdate($nextmidnight)." (in ".(time()-$daystart)." s)");
$timestart = $nextmidnight;
$nextmidnight = stats_get_next_day_start($nextmidnight);
}
set_cron_lock('statsrunning', null);
if ($failed) {
$days--;
mtrace("...error occured, completed $days days of statistics.");
return false;
} else {
mtrace("...completed $days days of statistics.");
return true;
}
}
/**
* Execute weekly statistics gathering
* @return boolean success
*/
function stats_cron_weekly() {
global $CFG;
$now = time();
// read last execution date from db
if (!$timestart = get_config(NULL, 'statslastweekly')) {
$timestart = stats_get_base_daily(stats_get_start_from('weekly'));
set_config('statslastweekly', $timestart);
}
$nextstartweek = stats_get_next_week_start($timestart);
// are there any weeks that need to be processed?
if ($now < $nextstartweek) {
return true; // everything ok and up-to-date
}
$timeout = empty($CFG->statsmaxruntime) ? 60*60*24 : $CFG->statsmaxruntime;
if (!set_cron_lock('statsrunning', $now + $timeout)) {
return false;
}
// fisrt delete entries that should not be there yet
delete_records_select('stats_weekly', "timeend > $timestart");
delete_records_select('stats_user_weekly', "timeend > $timestart");
mtrace("Running weekly statistics gathering, starting at $timestart:");
$weeks = 0;
while ($now > $nextstartweek) {
@set_time_limit($timeout - 200);
$weeks++;
if ($weeks > 1) {
// move the lock
set_cron_lock('statsrunning', time() + $timeout, true);
}
$logtimesql = "l.time >= $timestart AND l.time < $nextstartweek";
$stattimesql = "timeend > $timestart AND timeend <= $nextstartweek";
/// process login info first
$sql = "INSERT INTO {$CFG->prefix}stats_user_weekly (stattype, timeend, courseid, userid, statsreads)
SELECT 'logins' AS stattype, $nextstartweek AS timeend, ".SITEID." as courseid,
l.userid, count(l.id) AS statsreads
FROM {$CFG->prefix}log l
WHERE action = 'login' AND $logtimesql
GROUP BY stattype, timeend, courseid, userid
HAVING count(l.id) > 0";
execute_sql($sql, false);
$sql = "INSERT INTO {$CFG->prefix}stats_weekly (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'logins' AS stattype, $nextstartweek AS timeend, ".SITEID." as courseid, 0,
COALESCE((SELECT SUM(statsreads)
FROM {$CFG->prefix}stats_user_weekly s1
WHERE s1.stattype = 'logins' AND timeend = $nextstartweek), 0) AS nstat1,
(SELECT COUNT('x')
FROM {$CFG->prefix}stats_user_weekly s2
WHERE s2.stattype = 'logins' AND timeend = $nextstartweek) AS nstat2";
execute_sql($sql, false);
/// now enrolments averages
$sql = "INSERT INTO {$CFG->prefix}stats_weekly (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments' AS nstattype, $nextstartweek AS ntimeend, courseid, roleid,
CEIL(AVG(stat1)) AS nstat1, CEIL(AVG(stat2)) AS nstat2
FROM {$CFG->prefix}stats_daily sd
WHERE stattype = 'enrolments' AND $stattimesql
GROUP BY nstattype, ntimeend, courseid, roleid";
execute_sql($sql, false);
/// activity read/write averages
$sql = "INSERT INTO {$CFG->prefix}stats_weekly (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS nstattype, $nextstartweek AS ntimeend, courseid, roleid,
SUM(stat1) AS nstat1, SUM(stat2) AS nstat2
FROM {$CFG->prefix}stats_daily
WHERE stattype = 'activity' AND $stattimesql
GROUP BY nstattype, ntimeend, courseid, roleid";
execute_sql($sql, false);
/// user read/write averages
$sql = "INSERT INTO {$CFG->prefix}stats_user_weekly (stattype, timeend, courseid, userid, statsreads, statswrites)
SELECT 'activity' AS nstattype, $nextstartweek AS ntimeend, courseid, userid,
SUM(statsreads) AS nstatsreads, SUM(statswrites) AS nstatswrites
FROM {$CFG->prefix}stats_user_daily
WHERE stattype = 'activity' AND $stattimesql
GROUP BY nstattype, ntimeend, courseid, userid";
execute_sql($sql, false);
set_config('statslastweekly', $nextstartweek);
mtrace(" finished until $nextstartweek: ".userdate($nextstartweek));
$timestart = $nextstartweek;
$nextstartweek = stats_get_next_week_start($nextstartweek);
}
set_cron_lock('statsrunning', null);
mtrace("...completed $weeks weeks of statistics.");
return true;
}
/**
* Execute monthly statistics gathering
* @return boolean success
*/
function stats_cron_monthly() {
global $CFG;
$now = time();
// read last execution date from db
if (!$timestart = get_config(NULL, 'statslastmonthly')) {
$timestart = stats_get_base_monthly(stats_get_start_from('monthly'));
set_config('statslastmonthly', $timestart);
}
$nextstartmonth = stats_get_next_month_start($timestart);
// are there any months that need to be processed?
if ($now < $nextstartmonth) {
return true; // everything ok and up-to-date
}
$timeout = empty($CFG->statsmaxruntime) ? 60*60*24 : $CFG->statsmaxruntime;
if (!set_cron_lock('statsrunning', $now + $timeout)) {
return false;
}
// fisr delete entries that should not be there yet
delete_records_select('stats_monthly', "timeend > $timestart");
delete_records_select('stats_user_monthly', "timeend > $timestart");
$startmonth = stats_get_base_monthly($now);
mtrace("Running monthly statistics gathering, starting at $timestart:");
$months = 0;
while ($now > $nextstartmonth) {
@set_time_limit($timeout - 200);
$months++;
if ($months > 1) {
// move the lock
set_cron_lock('statsrunning', time() + $timeout, true);
}
$logtimesql = "l.time >= $timestart AND l.time < $nextstartmonth";
$stattimesql = "timeend > $timestart AND timeend <= $nextstartmonth";
/// process login info first
$sql = "INSERT INTO {$CFG->prefix}stats_user_monthly (stattype, timeend, courseid, userid, statsreads)
SELECT 'logins' AS stattype, $nextstartmonth AS timeend, ".SITEID." as courseid,
l.userid, count(l.id) AS statsreads
FROM {$CFG->prefix}log l
WHERE action = 'login' AND $logtimesql
GROUP BY stattype, timeend, courseid, userid";
execute_sql($sql, false);
$sql = "INSERT INTO {$CFG->prefix}stats_monthly (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'logins' AS stattype, $nextstartmonth AS timeend, ".SITEID." as courseid, 0,
COALESCE((SELECT SUM(statsreads)
FROM {$CFG->prefix}stats_user_monthly s1
WHERE s1.stattype = 'logins' AND timeend = $nextstartmonth), 0) AS nstat1,
(SELECT COUNT('x')
FROM {$CFG->prefix}stats_user_monthly s2
WHERE s2.stattype = 'logins' AND timeend = $nextstartmonth) AS nstat2";
execute_sql($sql, false);
/// now enrolments averages
$sql = "INSERT INTO {$CFG->prefix}stats_monthly (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments' AS nstattype, $nextstartmonth AS ntimeend, courseid, roleid,
CEIL(AVG(stat1)) AS nstat1, CEIL(AVG(stat2)) AS nstat2
FROM {$CFG->prefix}stats_daily sd
WHERE stattype = 'enrolments' AND $stattimesql
GROUP BY nstattype, ntimeend, courseid, roleid";
execute_sql($sql, false);
/// activity read/write averages
$sql = "INSERT INTO {$CFG->prefix}stats_monthly (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS nstattype, $nextstartmonth AS ntimeend, courseid, roleid,
SUM(stat1) AS nstat1, SUM(stat2) AS nstat2
FROM {$CFG->prefix}stats_daily
WHERE stattype = 'activity' AND $stattimesql
GROUP BY nstattype, ntimeend, courseid, roleid";
execute_sql($sql, false);
/// user read/write averages
$sql = "INSERT INTO {$CFG->prefix}stats_user_monthly (stattype, timeend, courseid, userid, statsreads, statswrites)
SELECT 'activity' AS nstattype, $nextstartmonth AS ntimeend, courseid, userid,
SUM(statsreads) AS nstatsreads, SUM(statswrites) AS nstatswrites
FROM {$CFG->prefix}stats_user_daily
WHERE stattype = 'activity' AND $stattimesql
GROUP BY nstattype, ntimeend, courseid, userid";
execute_sql($sql, false);
set_config('statslastmonthly', $nextstartmonth);
mtrace(" finished until $nextstartmonth: ".userdate($nextstartmonth));
$timestart = $nextstartmonth;
$nextstartmonth = stats_get_next_month_start($nextstartmonth);
}
set_cron_lock('statsrunning', null);
mtrace("...completed $months months of statistics.");
return true;
}
/**
* Returns simplified enrolment sql join data
* @param int $limit number of max parent course categories
* @param bool $includedoanything include also admins
* @return array ra join and where string
*/
function stats_get_enrolled_sql($limit, $includedoanything) {
global $CFG;
$adm = $includedoanything ? " OR rc.capability = 'moodle/site:doanything'" : "";
$join = "JOIN {$CFG->prefix}context ctx
ON ctx.id = ra.contextid
CROSS JOIN {$CFG->prefix}course c
JOIN {$CFG->prefix}role_capabilities rc
ON rc.roleid = ra.roleid";
$where = "((rc.capability = 'moodle/course:view' $adm)
AND rc.permission = 1 AND rc.contextid = ".SYSCONTEXTID."
AND (ctx.contextlevel = ".CONTEXT_SYSTEM."
OR (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE.")";
for($i=1; $i<=$limit; $i++) {
if ($i == 1) {
$join .= " LEFT OUTER JOIN {$CFG->prefix}course_categories cc1
ON cc1.id = c.category";
$where .= " OR (cc1.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT.")";
} else {
$j = $i-1;
$join .= " LEFT OUTER JOIN {$CFG->prefix}course_categories cc$i
ON cc$i.id = cc$j.parent";
$where .= " OR (cc$i.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT.")";
}
}
$where .= "))";
return array($join, $where);
}
/**
* Return starting date of stats processing
* @param string $str name of table - daily, weekly or monthly
* @return int timestamp
*/
function stats_get_start_from($str) {
global $CFG;
// are there any data in stats table? Should not be...
if ($timeend = get_field_sql('SELECT timeend FROM '.$CFG->prefix.'stats_'.$str.' ORDER BY timeend DESC')) {
return $timeend;
}
// decide what to do based on our config setting (either all or none or a timestamp)
switch ($CFG->statsfirstrun) {
case 'all':
if ($firstlog = get_field_sql('SELECT time FROM '.$CFG->prefix.'log ORDER BY time ASC')) {
return $firstlog;
}
default:
if (is_numeric($CFG->statsfirstrun)) {
return time() - $CFG->statsfirstrun;
}
// not a number? use next instead
case 'none':
return strtotime('-3 day', time());
}
}
/**
* Start of day
* @param int $time timestamp
* @return start of day
*/
function stats_get_base_daily($time=0) {
global $CFG;
if (empty($time)) {
$time = time();
}
if ($CFG->timezone == 99) {
$time = strtotime(date('d-M-Y', $time));
return $time;
} else {
$offset = get_timezone_offset($CFG->timezone);
$gtime = $time + $offset;
$gtime = intval($gtime / (60*60*24)) * 60*60*24;
return $gtime - $offset;
}
}
/**
* Start of week
* @param int $time timestamp
* @return start of week
*/
function stats_get_base_weekly($time=0) {
global $CFG;
$time = stats_get_base_daily($time);
$startday = $CFG->calendar_startwday;
if ($CFG->timezone == 99) {
$thisday = date('w', $time);
} else {
$offset = get_timezone_offset($CFG->timezone);
$gtime = $time + $offset;
$thisday = gmdate('w', $gtime);
}
if ($thisday > $startday) {
$time = $time - (($thisday - $startday) * 60*60*24);
} else if ($thisday < $startday) {
$time = $time - ((7 + $thisday - $startday) * 60*60*24);
}
return $time;
}
/**
* Start of month
* @param int $time timestamp
* @return start of month
*/
function stats_get_base_monthly($time=0) {
global $CFG;
if (empty($time)) {
$time = time();
}
if ($CFG->timezone == 99) {
return strtotime(date('1-M-Y', $time));
} else {
$time = stats_get_base_daily($time);
$offset = get_timezone_offset($CFG->timezone);
$gtime = $time + $offset;
$day = gmdate('d', $gtime);
if ($day == 1) {
return $time;
}
return $gtime - (($day-1) * 60*60*24);
}
}
/**
* Start of next day
* @param int $time timestamp
* @return start of next day
*/
function stats_get_next_day_start($time) {
$next = stats_get_base_daily($time);
$next = $next + 60*60*26;
$next = stats_get_base_daily($next);
if ($next <= $time) {
//DST trouble - prevent infinite loops
$next = $next + 60*60*24;
}
return $next;
}
/**
* Start of next week
* @param int $time timestamp
* @return start of next week
*/
function stats_get_next_week_start($time) {
$next = stats_get_base_weekly($time);
$next = $next + 60*60*24*9;
$next = stats_get_base_weekly($next);
if ($next <= $time) {
//DST trouble - prevent infinite loops
$next = $next + 60*60*24*7;
}
return $next;
}
/**
* Start of next month
* @param int $time timestamp
* @return start of next month
*/
function stats_get_next_month_start($time) {
$next = stats_get_base_monthly($time);
$next = $next + 60*60*24*33;
$next = stats_get_base_monthly($next);
if ($next <= $time) {
//DST trouble - prevent infinite loops
$next = $next + 60*60*24*31;
}
return $next;
}
/**
* Remove old stats data
*/
function stats_clean_old() {
mtrace("Running stats cleanup tasks...");
$deletebefore = stats_get_base_monthly();
// delete dailies older than 3 months (to be safe)
$deletebefore = strtotime('-3 months', $deletebefore);
delete_records_select('stats_daily', "timeend < $deletebefore");
delete_records_select('stats_user_daily', "timeend < $deletebefore");
// delete weeklies older than 9 months (to be safe)
$deletebefore = strtotime('-6 months', $deletebefore);
delete_records_select('stats_weekly', "timeend < $deletebefore");
delete_records_select('stats_user_weekly', "timeend < $deletebefore");
// don't delete monthlies
mtrace("...stats cleanup finished");
}
function stats_get_parameters($time,$report,$courseid,$mode,$roleid=0) {
global $CFG,$db;
$param = new object();
if ($time < 10) { // dailies
// number of days to go back = 7* time
$param->table = 'daily';
$param->timeafter = strtotime("-".($time*7)." days",stats_get_base_daily());
} elseif ($time < 20) { // weeklies
// number of weeks to go back = time - 10 * 4 (weeks) + base week
$param->table = 'weekly';
$param->timeafter = strtotime("-".(($time - 10)*4)." weeks",stats_get_base_weekly());
} else { // monthlies.
// number of months to go back = time - 20 * months + base month
$param->table = 'monthly';
$param->timeafter = strtotime("-".($time - 20)." months",stats_get_base_monthly());
}
$param->extras = '';
// compatibility - if we're in postgres, cast to real for some reports.