forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatslib.php
1832 lines (1498 loc) · 67.5 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
// 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/>.
/**
* @package core
* @subpackage stats
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/** THESE CONSTANTS ARE USED FOR THE REPORTING PAGE. */
define('STATS_REPORT_LOGINS',1); // double impose logins and unique 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, selected 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
// Output string when nodebug is on
define('STATS_PLACEHOLDER_OUTPUT', '.');
/**
* Print daily cron progress
* @param string $ident
*/
function stats_progress($ident) {
static $start = 0;
static $init = 0;
if ($ident == 'init') {
$init = $start = microtime(true);
return;
}
$elapsed = round(microtime(true) - $start);
$start = microtime(true);
if (debugging('', DEBUG_ALL)) {
mtrace("$ident:$elapsed ", '');
} else {
mtrace(STATS_PLACEHOLDER_OUTPUT, '');
}
}
/**
* Execute individual daily statistics queries
*
* @param string $sql The query to run
* @return boolean success
*/
function stats_run_query($sql, $parameters = array()) {
global $DB;
try {
$DB->execute($sql, $parameters);
} catch (dml_exception $e) {
if (debugging('', DEBUG_ALL)) {
mtrace($e->getMessage());
}
return false;
}
return true;
}
/**
* 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, $DB;
require_once($CFG->libdir.'/adminlib.php');
$now = time();
$fpcontext = context_course::instance(SITEID, MUST_EXIST);
// 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;
}
// first delete entries that should not be there yet
$DB->delete_records_select('stats_daily', "timeend > $timestart");
$DB->delete_records_select('stats_user_daily', "timeend > $timestart");
// Read in a few things we'll use later
$viewactions = stats_get_action_names('view');
$postactions = stats_get_action_names('post');
$guest = (int)$CFG->siteguest;
$guestrole = (int)$CFG->guestroleid;
$defaultfproleid = (int)$CFG->defaultfrontpageroleid;
mtrace("Running daily statistics gathering, starting at $timestart:");
cron_trace_time_and_memory();
$days = 0;
$total = 0;
$failed = false; // failed stats flag
$timeout = false;
if (!stats_temp_table_create()) {
$days = 1;
$failed = true;
}
mtrace('Temporary tables created');
if(!stats_temp_table_setup()) {
$days = 1;
$failed = true;
}
mtrace('Enrolments calculated');
$totalactiveusers = $DB->count_records('user', array('deleted' => '0'));
while (!$failed && ($now > $nextmidnight)) {
if ($days >= $maxdays) {
$timeout = true;
break;
}
$days++;
core_php_time_limit::raise($timeout - 200);
if ($days > 1) {
// move the lock
set_cron_lock('statsrunning', time() + $timeout, true);
}
$daystart = time();
stats_progress('init');
if (!stats_temp_table_fill($timestart, $nextmidnight)) {
$failed = true;
break;
}
// Find out if any logs available for this day
$sql = "SELECT 'x' FROM {temp_log1} l";
$logspresent = $DB->get_records_sql($sql, null, 0, 1);
if ($logspresent) {
// Insert blank record to force Query 10 to generate additional row when no logs for
// the site with userid 0 exist. Added for backwards compatibility.
$DB->insert_record('temp_log1', array('userid' => 0, 'course' => SITEID, 'action' => ''));
}
// Calculate the number of active users today
$sql = 'SELECT COUNT(DISTINCT u.id)
FROM {user} u
JOIN {temp_log1} l ON l.userid = u.id
WHERE u.deleted = 0';
$dailyactiveusers = $DB->count_records_sql($sql);
stats_progress('0');
// Process login info first
// Note: PostgreSQL doesn't like aliases in HAVING clauses
$sql = "INSERT INTO {temp_stats_user_daily}
(stattype, timeend, courseid, userid, statsreads)
SELECT 'logins', $nextmidnight AS timeend, ".SITEID." AS courseid,
userid, COUNT(id) AS statsreads
FROM {temp_log1} l
WHERE action = 'login'
GROUP BY userid
HAVING COUNT(id) > 0";
if ($logspresent && !stats_run_query($sql)) {
$failed = true;
break;
}
$DB->update_temp_table_stats();
stats_progress('1');
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'logins' AS stattype, $nextmidnight AS timeend, ".SITEID." AS courseid, 0,
COALESCE(SUM(statsreads), 0) as stat1, COUNT('x') as stat2
FROM {temp_stats_user_daily}
WHERE stattype = 'logins' AND timeend = $nextmidnight";
if ($logspresent && !stats_run_query($sql)) {
$failed = true;
break;
}
stats_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
// - SITEID is special case here, because it's all about default enrolment
// in that case, we'll count non-deleted users.
//
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments' as stattype, $nextmidnight as timeend, courseid, roleid,
COUNT(DISTINCT userid) as stat1, 0 as stat2
FROM {temp_enroled}
GROUP BY courseid, roleid";
if (!stats_run_query($sql)) {
$failed = true;
break;
}
stats_progress('3');
// Set stat2 to the number distinct users with role assignments in the course that were active
// using table alias in UPDATE does not work in pg < 8.2
$sql = "UPDATE {temp_stats_daily}
SET stat2 = (
SELECT COUNT(DISTINCT userid)
FROM {temp_enroled} te
WHERE roleid = {temp_stats_daily}.roleid
AND courseid = {temp_stats_daily}.courseid
AND EXISTS (
SELECT 'x'
FROM {temp_log1} l
WHERE l.course = {temp_stats_daily}.courseid
AND l.userid = te.userid
)
)
WHERE {temp_stats_daily}.stattype = 'enrolments'
AND {temp_stats_daily}.timeend = $nextmidnight
AND {temp_stats_daily}.courseid IN (
SELECT DISTINCT course FROM {temp_log2})";
if ($logspresent && !stats_run_query($sql, array('courselevel'=>CONTEXT_COURSE))) {
$failed = true;
break;
}
stats_progress('4');
// Now get course total enrolments (roleid==0) - except frontpage
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments', $nextmidnight AS timeend, te.courseid AS courseid, 0 AS roleid,
COUNT(DISTINCT userid) AS stat1, 0 AS stat2
FROM {temp_enroled} te
GROUP BY courseid
HAVING COUNT(DISTINCT userid) > 0";
if ($logspresent && !stats_run_query($sql)) {
$failed = true;
break;
}
stats_progress('5');
// Set stat 2 to the number of enrolled users who were active in the course
$sql = "UPDATE {temp_stats_daily}
SET stat2 = (
SELECT COUNT(DISTINCT te.userid)
FROM {temp_enroled} te
WHERE te.courseid = {temp_stats_daily}.courseid
AND EXISTS (
SELECT 'x'
FROM {temp_log1} l
WHERE l.course = {temp_stats_daily}.courseid
AND l.userid = te.userid
)
)
WHERE {temp_stats_daily}.stattype = 'enrolments'
AND {temp_stats_daily}.timeend = $nextmidnight
AND {temp_stats_daily}.roleid = 0
AND {temp_stats_daily}.courseid IN (
SELECT l.course
FROM {temp_log2} l
WHERE l.course <> ".SITEID.")";
if ($logspresent && !stats_run_query($sql, array())) {
$failed = true;
break;
}
stats_progress('6');
// Frontpage(==site) enrolments total
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments', $nextmidnight, ".SITEID.", 0, $totalactiveusers AS stat1,
$dailyactiveusers AS stat2" .
$DB->sql_null_from_clause();
if ($logspresent && !stats_run_query($sql)) {
$failed = true;
break;
}
// The steps up until this point, all add to {temp_stats_daily} and don't use new tables.
// There is no point updating statistics as they won't be used until the DELETE below.
$DB->update_temp_table_stats();
stats_progress('7');
// 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 {temp_stats_daily}
WHERE stattype = 'enrolments'
AND courseid = ".SITEID."
AND roleid = $defaultfproleid
AND timeend = $nextmidnight";
if ($logspresent && !stats_run_query($sql)) {
$failed = true;
break;
}
stats_progress('8');
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments', $nextmidnight, ".SITEID.", $defaultfproleid,
$totalactiveusers AS stat1, $dailyactiveusers AS stat2" .
$DB->sql_null_from_clause();
if ($logspresent && !stats_run_query($sql)) {
$failed = true;
break;
}
stats_progress('9');
} else {
stats_progress('x');
stats_progress('x');
}
/// individual user stats (including not-logged-in) in each course, this is slow - reuse this data if possible
list($viewactionssql, $params1) = $DB->get_in_or_equal($viewactions, SQL_PARAMS_NAMED, 'view');
list($postactionssql, $params2) = $DB->get_in_or_equal($postactions, SQL_PARAMS_NAMED, 'post');
$sql = "INSERT INTO {temp_stats_user_daily} (stattype, timeend, courseid, userid, statsreads, statswrites)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, course AS courseid, userid,
SUM(CASE WHEN action $viewactionssql THEN 1 ELSE 0 END) AS statsreads,
SUM(CASE WHEN action $postactionssql THEN 1 ELSE 0 END) AS statswrites
FROM {temp_log1} l
GROUP BY userid, course";
if ($logspresent && !stats_run_query($sql, array_merge($params1, $params2))) {
$failed = true;
break;
}
stats_progress('10');
/// How many view/post actions in each course total
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity' AS stattype, $nextmidnight AS timeend, c.id AS courseid, 0,
SUM(CASE WHEN l.action $viewactionssql THEN 1 ELSE 0 END) AS stat1,
SUM(CASE WHEN l.action $postactionssql THEN 1 ELSE 0 END) AS stat2
FROM {course} c, {temp_log1} l
WHERE l.course = c.id
GROUP BY c.id";
if ($logspresent && !stats_run_query($sql, array_merge($params1, $params2))) {
$failed = true;
break;
}
stats_progress('11');
/// how many view actions for each course+role - excluding guests and frontpage
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity', $nextmidnight AS timeend, courseid, roleid, SUM(statsreads), SUM(statswrites)
FROM (
SELECT pl.courseid, pl.roleid, sud.statsreads, sud.statswrites
FROM {temp_stats_user_daily} sud, (
SELECT DISTINCT te.userid, te.roleid, te.courseid
FROM {temp_enroled} te
WHERE te.roleid <> $guestrole
AND te.userid <> $guest
) pl
WHERE sud.userid = pl.userid
AND sud.courseid = pl.courseid
AND sud.timeend = $nextmidnight
AND sud.stattype='activity'
) inline_view
GROUP BY courseid, roleid
HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
if ($logspresent && !stats_run_query($sql, array('courselevel'=>CONTEXT_COURSE))) {
$failed = true;
break;
}
stats_progress('12');
/// how many view actions from guests only in each course - excluding frontpage
/// normal users may enter course with temporary guest access too
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity', $nextmidnight AS timeend, courseid, $guestrole AS roleid,
SUM(statsreads), SUM(statswrites)
FROM (
SELECT sud.courseid, sud.statsreads, sud.statswrites
FROM {temp_stats_user_daily} sud
WHERE sud.timeend = $nextmidnight
AND sud.courseid <> ".SITEID."
AND sud.stattype='activity'
AND (sud.userid = $guest OR sud.userid NOT IN (
SELECT userid
FROM {temp_enroled} te
WHERE te.courseid = sud.courseid
))
) inline_view
GROUP BY courseid
HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
if ($logspresent && !stats_run_query($sql, array())) {
$failed = true;
break;
}
stats_progress('13');
/// How many view actions for each role on frontpage - excluding guests, not-logged-in and default frontpage role
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity', $nextmidnight AS timeend, courseid, roleid,
SUM(statsreads), SUM(statswrites)
FROM (
SELECT pl.courseid, pl.roleid, sud.statsreads, sud.statswrites
FROM {temp_stats_user_daily} sud, (
SELECT DISTINCT ra.userid, ra.roleid, c.instanceid AS courseid
FROM {role_assignments} ra
JOIN {context} c ON c.id = ra.contextid
WHERE ra.contextid = :fpcontext
AND ra.roleid <> $defaultfproleid
AND ra.roleid <> $guestrole
AND ra.userid <> $guest
) pl
WHERE sud.userid = pl.userid
AND sud.courseid = pl.courseid
AND sud.timeend = $nextmidnight
AND sud.stattype='activity'
) inline_view
GROUP BY courseid, roleid
HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
if ($logspresent && !stats_run_query($sql, array('fpcontext'=>$fpcontext->id))) {
$failed = true;
break;
}
stats_progress('14');
// How many view actions for default frontpage role on frontpage only
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity', timeend, courseid, $defaultfproleid AS roleid,
SUM(statsreads), SUM(statswrites)
FROM (
SELECT sud.timeend AS timeend, sud.courseid, sud.statsreads, sud.statswrites
FROM {temp_stats_user_daily} sud
WHERE sud.timeend = :nextm
AND sud.courseid = :siteid
AND sud.stattype='activity'
AND sud.userid <> $guest
AND sud.userid <> 0
AND sud.userid NOT IN (
SELECT ra.userid
FROM {role_assignments} ra
WHERE ra.roleid <> $guestrole
AND ra.roleid <> $defaultfproleid
AND ra.contextid = :fpcontext)
) inline_view
GROUP BY timeend, courseid
HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
if ($logspresent && !stats_run_query($sql, array('fpcontext'=>$fpcontext->id, 'siteid'=>SITEID, 'nextm'=>$nextmidnight))) {
$failed = true;
break;
}
$DB->update_temp_table_stats();
stats_progress('15');
// How many view actions for guests or not-logged-in on frontpage
$sql = "INSERT INTO {temp_stats_daily} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT stattype, timeend, courseid, $guestrole AS roleid,
SUM(statsreads) AS stat1, SUM(statswrites) AS stat2
FROM (
SELECT sud.stattype, sud.timeend, sud.courseid,
sud.statsreads, sud.statswrites
FROM {temp_stats_user_daily} sud
WHERE (sud.userid = $guest OR sud.userid = 0)
AND sud.timeend = $nextmidnight
AND sud.courseid = ".SITEID."
AND sud.stattype='activity'
) inline_view
GROUP BY stattype, timeend, courseid
HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
if ($logspresent && !stats_run_query($sql)) {
$failed = true;
break;
}
stats_progress('16');
stats_temp_table_clean();
stats_progress('out');
// remember processed days
set_config('statslastdaily', $nextmidnight);
$elapsed = time()-$daystart;
mtrace(" finished until $nextmidnight: ".userdate($nextmidnight)." (in $elapsed s)");
$total += $elapsed;
$timestart = $nextmidnight;
$nextmidnight = stats_get_next_day_start($nextmidnight);
}
stats_temp_table_drop();
set_cron_lock('statsrunning', null);
if ($failed) {
$days--;
mtrace("...error occurred, completed $days days of statistics in {$total} s.");
return false;
} else if ($timeout) {
mtrace("...stopping early, reached maximum number of $maxdays days ({$total} s) - will continue next time.");
return false;
} else {
mtrace("...completed $days days of statistics in {$total} s.");
return true;
}
}
/**
* Execute weekly statistics gathering
* @return boolean success
*/
function stats_cron_weekly() {
global $CFG, $DB;
require_once($CFG->libdir.'/adminlib.php');
$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
$DB->delete_records_select('stats_weekly', "timeend > $timestart");
$DB->delete_records_select('stats_user_weekly', "timeend > $timestart");
mtrace("Running weekly statistics gathering, starting at $timestart:");
cron_trace_time_and_memory();
$weeks = 0;
while ($now > $nextstartweek) {
core_php_time_limit::raise($timeout - 200);
$weeks++;
if ($weeks > 1) {
// move the lock
set_cron_lock('statsrunning', time() + $timeout, true);
}
$stattimesql = "timeend > $timestart AND timeend <= $nextstartweek";
$weekstart = time();
stats_progress('init');
/// process login info first
$sql = "INSERT INTO {stats_user_weekly} (stattype, timeend, courseid, userid, statsreads)
SELECT 'logins', timeend, courseid, userid, SUM(statsreads)
FROM (
SELECT $nextstartweek AS timeend, courseid, userid, statsreads
FROM {stats_user_daily} sd
WHERE stattype = 'logins' AND $stattimesql
) inline_view
GROUP BY timeend, courseid, userid
HAVING SUM(statsreads) > 0";
$DB->execute($sql);
stats_progress('1');
$sql = "INSERT INTO {stats_weekly} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'logins' AS stattype, $nextstartweek AS timeend, ".SITEID." as courseid, 0,
COALESCE((SELECT SUM(statsreads)
FROM {stats_user_weekly} s1
WHERE s1.stattype = 'logins' AND timeend = $nextstartweek), 0) AS nstat1,
(SELECT COUNT('x')
FROM {stats_user_weekly} s2
WHERE s2.stattype = 'logins' AND timeend = $nextstartweek) AS nstat2" .
$DB->sql_null_from_clause();
$DB->execute($sql);
stats_progress('2');
/// now enrolments averages
$sql = "INSERT INTO {stats_weekly} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments', ntimeend, courseid, roleid, " . $DB->sql_ceil('AVG(stat1)') . ", " . $DB->sql_ceil('AVG(stat2)') . "
FROM (
SELECT $nextstartweek AS ntimeend, courseid, roleid, stat1, stat2
FROM {stats_daily} sd
WHERE stattype = 'enrolments' AND $stattimesql
) inline_view
GROUP BY ntimeend, courseid, roleid";
$DB->execute($sql);
stats_progress('3');
/// activity read/write averages
$sql = "INSERT INTO {stats_weekly} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity', ntimeend, courseid, roleid, SUM(stat1), SUM(stat2)
FROM (
SELECT $nextstartweek AS ntimeend, courseid, roleid, stat1, stat2
FROM {stats_daily}
WHERE stattype = 'activity' AND $stattimesql
) inline_view
GROUP BY ntimeend, courseid, roleid";
$DB->execute($sql);
stats_progress('4');
/// user read/write averages
$sql = "INSERT INTO {stats_user_weekly} (stattype, timeend, courseid, userid, statsreads, statswrites)
SELECT 'activity', ntimeend, courseid, userid, SUM(statsreads), SUM(statswrites)
FROM (
SELECT $nextstartweek AS ntimeend, courseid, userid, statsreads, statswrites
FROM {stats_user_daily}
WHERE stattype = 'activity' AND $stattimesql
) inline_view
GROUP BY ntimeend, courseid, userid";
$DB->execute($sql);
stats_progress('5');
set_config('statslastweekly', $nextstartweek);
$elapsed = time()-$weekstart;
mtrace(" finished until $nextstartweek: ".userdate($nextstartweek) ." (in $elapsed s)");
$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, $DB;
require_once($CFG->libdir.'/adminlib.php');
$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
$DB->delete_records_select('stats_monthly', "timeend > $timestart");
$DB->delete_records_select('stats_user_monthly', "timeend > $timestart");
$startmonth = stats_get_base_monthly($now);
mtrace("Running monthly statistics gathering, starting at $timestart:");
cron_trace_time_and_memory();
$months = 0;
while ($now > $nextstartmonth) {
core_php_time_limit::raise($timeout - 200);
$months++;
if ($months > 1) {
// move the lock
set_cron_lock('statsrunning', time() + $timeout, true);
}
$stattimesql = "timeend > $timestart AND timeend <= $nextstartmonth";
$monthstart = time();
stats_progress('init');
/// process login info first
$sql = "INSERT INTO {stats_user_monthly} (stattype, timeend, courseid, userid, statsreads)
SELECT 'logins', timeend, courseid, userid, SUM(statsreads)
FROM (
SELECT $nextstartmonth AS timeend, courseid, userid, statsreads
FROM {stats_user_daily} sd
WHERE stattype = 'logins' AND $stattimesql
) inline_view
GROUP BY timeend, courseid, userid
HAVING SUM(statsreads) > 0";
$DB->execute($sql);
stats_progress('1');
$sql = "INSERT INTO {stats_monthly} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'logins' AS stattype, $nextstartmonth AS timeend, ".SITEID." as courseid, 0,
COALESCE((SELECT SUM(statsreads)
FROM {stats_user_monthly} s1
WHERE s1.stattype = 'logins' AND timeend = $nextstartmonth), 0) AS nstat1,
(SELECT COUNT('x')
FROM {stats_user_monthly} s2
WHERE s2.stattype = 'logins' AND timeend = $nextstartmonth) AS nstat2" .
$DB->sql_null_from_clause();
$DB->execute($sql);
stats_progress('2');
/// now enrolments averages
$sql = "INSERT INTO {stats_monthly} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'enrolments', ntimeend, courseid, roleid, " . $DB->sql_ceil('AVG(stat1)') . ", " . $DB->sql_ceil('AVG(stat2)') . "
FROM (
SELECT $nextstartmonth AS ntimeend, courseid, roleid, stat1, stat2
FROM {stats_daily} sd
WHERE stattype = 'enrolments' AND $stattimesql
) inline_view
GROUP BY ntimeend, courseid, roleid";
$DB->execute($sql);
stats_progress('3');
/// activity read/write averages
$sql = "INSERT INTO {stats_monthly} (stattype, timeend, courseid, roleid, stat1, stat2)
SELECT 'activity', ntimeend, courseid, roleid, SUM(stat1), SUM(stat2)
FROM (
SELECT $nextstartmonth AS ntimeend, courseid, roleid, stat1, stat2
FROM {stats_daily}
WHERE stattype = 'activity' AND $stattimesql
) inline_view
GROUP BY ntimeend, courseid, roleid";
$DB->execute($sql);
stats_progress('4');
/// user read/write averages
$sql = "INSERT INTO {stats_user_monthly} (stattype, timeend, courseid, userid, statsreads, statswrites)
SELECT 'activity', ntimeend, courseid, userid, SUM(statsreads), SUM(statswrites)
FROM (
SELECT $nextstartmonth AS ntimeend, courseid, userid, statsreads, statswrites
FROM {stats_user_daily}
WHERE stattype = 'activity' AND $stattimesql
) inline_view
GROUP BY ntimeend, courseid, userid";
$DB->execute($sql);
stats_progress('5');
set_config('statslastmonthly', $nextstartmonth);
$elapsed = time() - $monthstart;
mtrace(" finished until $nextstartmonth: ".userdate($nextstartmonth) ." (in $elapsed s)");
$timestart = $nextstartmonth;
$nextstartmonth = stats_get_next_month_start($nextstartmonth);
}
set_cron_lock('statsrunning', null);
mtrace("...completed $months months of statistics.");
return true;
}
/**
* 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, $DB;
// are there any data in stats table? Should not be...
if ($timeend = $DB->get_field_sql('SELECT MAX(timeend) FROM {stats_'.$str.'}')) {
return $timeend;
}
// decide what to do based on our config setting (either all or none or a timestamp)
switch ($CFG->statsfirstrun) {
case 'all':
$manager = get_log_manager();
$stores = $manager->get_readers();
$firstlog = false;
foreach ($stores as $store) {
if ($store instanceof \core\log\sql_internal_table_reader) {
$logtable = $store->get_internal_log_table_name();
if (!$logtable) {
continue;
}
$first = $DB->get_field_sql("SELECT MIN(timecreated) FROM {{$logtable}}");
if ($first and (!$firstlog or $firstlog > $first)) {
$firstlog = $first;
}
}
}
$first = $DB->get_field_sql('SELECT MIN(time) FROM {log}');
if ($first and (!$firstlog or $firstlog > $first)) {
$firstlog = $first;
}
if ($firstlog) {
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 int start of day
*/
function stats_get_base_daily($time=0) {
if (empty($time)) {
$time = time();
}
core_date::set_default_server_timezone();
$time = strtotime(date('d-M-Y', $time));
return $time;
}
/**
* Start of week
* @param int $time timestamp
* @return int start of week
*/
function stats_get_base_weekly($time=0) {
global $CFG;
$time = stats_get_base_daily($time);
$startday = $CFG->calendar_startwday;
core_date::set_default_server_timezone();
$thisday = date('w', $time);
if ($thisday > $startday) {
$time = $time - (($thisday - $startday) * 60*60*24);
} else if ($thisday < $startday) {
$time = $time - ((7 + $thisday - $startday) * 60*60*24);
}