statistics.php 197 KB
Newer Older
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
<?php
/**
 *
 * @package    mahara
 * @subpackage core
 * @author     Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
 * @file Statistics for a mahara site
 */

defined('INTERNAL') || die();

function site_data_current() {
    return array(
        'users' => count_records_select('usr', 'id > 0 AND deleted = 0'),
        'groups' => count_records('group', 'deleted', 0),
        'views' => count_records_select('view', 'owner != 0 OR owner IS NULL'),
    );
}

function site_statistics($full=false) {
    $data = array();

    if ($full) {
        $data = site_data_current();
        $data['weekly'] = true;

        if (is_postgres()) {
            $weekago = "CURRENT_DATE - INTERVAL '1 week'";
            $thisweeksql = "(lastaccess > $weekago)::int";
            $todaysql = '(lastaccess > CURRENT_DATE)::int';
            $eversql = "(NOT lastaccess IS NULL)::int";
        }
        else {
            $weekago = 'CURRENT_DATE - INTERVAL 1 WEEK';
            $thisweeksql = "lastaccess > $weekago";
            $todaysql = 'lastaccess > CURRENT_DATE';
            $eversql = "NOT lastaccess IS NULL";
        }
        $sql = "SELECT SUM($todaysql) AS today, SUM($thisweeksql) AS thisweek, $weekago AS weekago, SUM($eversql) AS ever FROM {usr}";
        $active = get_record_sql($sql);
43
        $data['usersloggedin'] = get_string('loggedinsince', 'admin', $active->today, $active->thisweek, format_date(strtotime($active->weekago), 'strftimedate'), $active->ever);
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

        $memberships = count_records_sql("
            SELECT COUNT(*)
            FROM {group_member} m JOIN {group} g ON g.id = m.group
            WHERE g.deleted = 0
        ");
        $data['groupmemberaverage'] = round($memberships/$data['users'], 1);
        $data['strgroupmemberaverage'] = get_string('groupmemberaverage', 'admin', $data['groupmemberaverage']);
        $data['viewsperuser'] = get_field_sql("
            SELECT (0.0 + COUNT(id)) / NULLIF(COUNT(DISTINCT \"owner\"), 0)
            FROM {view}
            WHERE NOT \"owner\" IS NULL AND \"owner\" > 0
        ");
        $data['viewsperuser'] = round($data['viewsperuser'], 1);
        $data['strviewsperuser'] = get_string('viewsperuser', 'admin', $data['viewsperuser']);
    }

    $data['displayname'] = get_config('sitename');
    $data['name']        = 'all';
    $data['release']     = get_config('release');
    $data['version']     = get_config('version');
    $data['installdate'] = format_date(strtotime(get_config('installation_time')), 'strftimedate');
    $data['dbsize']      = db_total_size();
    $data['diskusage']   = get_field('site_data', 'value', 'type', 'disk-usage');
    $data['cronrunning'] = !record_exists_select('cron', 'nextrun IS NULL OR nextrun < CURRENT_DATE');
    $data['siteclosedbyadmin'] = get_config('siteclosedbyadmin');
70
    $data['institution'] = 'all';
71
72
73
74
75
76
77
78
79
80
81
82

    if ($latestversion = get_config('latest_version')) {
        $data['latest_version'] = $latestversion;
        if ($data['release'] == $latestversion) {
            $data['strlatestversion'] = get_string('uptodate', 'admin');
        }
        else {
            $download_page = 'https://launchpad.net/mahara/+download';
            $data['strlatestversion'] = get_string('latestversionis', 'admin', $download_page, $latestversion);
        }
    }

83
84
85
86
87
    if ($full) {
        // Add the other overall graphs here
        // Group graph
        $smarty = smarty_core();
        $smarty->assign('grouptypecounts', get_records_sql_array("
88
            SELECT grouptype, COUNT(id) AS groupcount
89
90
91
            FROM {group}
            WHERE deleted = 0
            GROUP BY grouptype
92
            ORDER BY groupcount DESC", array()
93
94
        ));
        $smarty->assign('jointypecounts', get_records_sql_array("
95
            SELECT jointype, COUNT(id) AS groupcount
96
97
98
            FROM {group}
            WHERE deleted = 0
            GROUP BY jointype
99
            ORDER BY groupcount DESC", array()
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
        ));
        $smarty->assign('groupgraph', true);
        $data['groupinfo'] = $smarty->fetch('admin/groupstatssummary.tpl');

        // Users graph
        $maxfriends = get_records_sql_array("
            SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, SUM(f.friends) AS friends
            FROM {usr} u INNER JOIN (
                SELECT DISTINCT(usr1) AS id, COUNT(usr1) AS friends
                FROM {usr_friend}
                GROUP BY usr1
                UNION SELECT DISTINCT(usr2) AS id, COUNT(usr2) AS friends
                FROM {usr_friend}
                GROUP BY usr2
            ) f ON u.id = f.id
            GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
            ORDER BY friends DESC
            LIMIT 1", array());
        $maxfriends = $maxfriends[0];
        $meanfriends = 2 * count_records('usr_friend') / $data['users'];
        if ($maxfriends) {
            $data['strmaxfriends'] = get_string(
                'statsmaxfriends1',
                'admin',
                $maxfriends->friends,
                round($meanfriends, 1),
                profile_url($maxfriends),
                hsc(display_name($maxfriends, null, true))
            );
        }
        else {
            $data['strmaxfriends'] = get_string('statsnofriends', 'admin');
        }
        $maxviews = get_records_sql_array("
            SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(v.id) AS views
            FROM {usr} u JOIN {view} v ON u.id = v.owner
            WHERE \"owner\" <> 0
            GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
            ORDER BY views DESC
            LIMIT 1", array());
        $maxviews = $maxviews[0];
        if ($maxviews) {
            $data['strmaxviews'] = get_string(
                'statsmaxviews1',
                'admin',
                $maxviews->views,
                $data['viewsperuser'],
                profile_url($maxviews),
                hsc(display_name($maxviews, null, true))
            );
        }
        else {
            $data['strmaxviews'] = get_string('statsnoviews', 'admin');
        }
        $maxgroups = get_records_sql_array("
155
            SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(m.group) AS groupcount
156
157
158
            FROM {usr} u JOIN {group_member} m ON u.id = m.member JOIN {group} g ON m.group = g.id
            WHERE g.deleted = 0
            GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
159
            ORDER BY groupcount DESC
160
161
162
163
164
165
            LIMIT 1", array());
        $maxgroups = $maxgroups[0];
        if ($maxgroups) {
            $data['strmaxgroups'] = get_string(
                'statsmaxgroups1',
                'admin',
166
                $maxgroups->groupcount,
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
                $data['groupmemberaverage'],
                profile_url($maxgroups),
                hsc(display_name($maxgroups, null, true))
            );
        }
        else {
            $data['strmaxgroups'] = get_string('statsnogroups', 'admin');
        }
        $maxquotaused = get_records_sql_array("
            SELECT id, firstname, lastname, preferredname, urlid, quotaused
            FROM {usr}
            WHERE deleted = 0 AND id > 0
            ORDER BY quotaused DESC
            LIMIT 1", array());
        $maxquotaused = $maxquotaused[0];
        $data['strmaxquotaused'] = get_string(
            'statsmaxquotaused1',
            'admin',
            display_size(get_field('usr', 'AVG(quotaused)', 'deleted', 0)),
            profile_url($maxquotaused),
            hsc(display_name($maxquotaused, null, true)),
            display_size($maxquotaused->quotaused)
        );

        $smarty = smarty_core();
        $smarty->assign('data', $data);
        $data['usersinfo'] = $smarty->fetch('admin/userstatssummary.tpl');

        // Views graph
        $smarty = smarty_core();
        $maxblocktypes = 5;
198
        $blocktypecounts = get_records_sql_array("
199
200
201
202
203
204
            SELECT
                b.blocktype,
                COUNT(b.id) AS blocks
            FROM {block_instance} b
            JOIN {blocktype_installed} bi ON (b.blocktype = bi.name)
            JOIN {view} v ON (b.view = v.id AND v.type = 'portfolio')
205
            GROUP BY b.blocktype
206
207
            ORDER BY blocks DESC",
            array(), 0, $maxblocktypes
208
        );
209
210
211
212
213
214
        if (is_array($blocktypecounts)) {
            foreach ($blocktypecounts as $blocktype) {
                safe_require('blocktype', $blocktype->blocktype);
                $classname = generate_class_name('blocktype', $blocktype->blocktype);
                $blocktype->title = $classname::get_title();
            }
215
216
217
        }
        $smarty->assign('blocktypecounts', $blocktypecounts);

218
219
220
221
        $smarty->assign('viewtypes', true);
        $smarty->assign('viewcount', $data['views']);
        $data['viewsinfo'] = $smarty->fetch('admin/viewstatssummary.tpl');
    }
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
    return($data);
}

function institution_data_current($institution) {
    $data = array();
    if ($institution == 'mahara') {
        $membersquery = 'SELECT id FROM {usr}
                WHERE deleted = 0 AND id > 0 AND id NOT IN
                (SELECT usr FROM {usr_institution})';
        $membersqueryparams = array();
    }
    else {
        $membersquery = 'SELECT usr FROM {usr_institution} ui
                JOIN {usr} u ON (u.id = ui.usr)
                WHERE u.deleted = 0 AND ui.institution = ?';
        $membersqueryparams = array($institution);
    }
    $data['memberssql'] = $membersquery;
    $data['memberssqlparams'] = $membersqueryparams;
    $data['users'] = get_field_sql('SELECT COUNT(*) FROM (' . $membersquery . ') AS members', $membersqueryparams);
    if (!$data['users']) {
        $data['views'] = 0;
    }
    else {
        $data['viewssql'] = '
                SELECT id FROM {view}
                    WHERE owner IS NOT NULL AND owner IN (' . $membersquery . ')
                UNION
                    SELECT id FROM {view}
                    WHERE institution IS NOT NULL AND institution = ?';
        $data['viewssqlparam'] = array_merge($membersqueryparams, array($institution));
        $data['views'] = count_records_sql('SELECT COUNT(*) FROM (' . $data['viewssql'] . ') AS members',   $data['viewssqlparam']);
    }
    return $data;
}

function institution_statistics($institution, $full=false) {
    $data = array();

    if ($full) {
        $data = institution_data_current($institution);
        $data['weekly'] = true;
        $data['institution'] = $institution;

        if (is_postgres()) {
            $weekago = "CURRENT_DATE - INTERVAL '1 week'";
            $thisweeksql = "COALESCE((lastaccess > $weekago)::int, 0)::int";
            $todaysql = 'COALESCE((lastaccess > CURRENT_DATE)::int, 0)::int';
            $eversql = "(NOT lastaccess IS NULL)::int";
        }
        else {
            $weekago = 'CURRENT_DATE - INTERVAL 1 week';
            $thisweeksql = "COALESCE(lastaccess > $weekago, 0)";
            $todaysql = 'COALESCE(lastaccess > CURRENT_DATE, 0)';
            $eversql = "NOT lastaccess IS NULL";
        }
        if (!$data['users']) {
            $active = get_record_sql("SELECT 0 AS today, 0 AS thisweek, $weekago AS weekago, 0 AS ever");
        }
        else {
            $sql = "SELECT SUM($todaysql) AS today, SUM($thisweeksql) AS thisweek, $weekago AS weekago, SUM($eversql) AS ever FROM {usr}
                    WHERE id IN (" . $data['memberssql'] . ")";
            $active = get_record_sql($sql, $data['memberssqlparams']);
        }
286
        $data['usersloggedin'] = get_string('loggedinsince', 'admin', $active->today, $active->thisweek, format_date(strtotime($active->weekago), 'strftimedate'), $active->ever);
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

        if (!$data['users']) {
            $data['groupmemberaverage'] = 0;
        }
        else {
            $memberships = count_records_sql("
                SELECT COUNT(*)
                FROM {group_member} m JOIN {group} g ON g.id = m.group
                WHERE g.deleted = 0 AND m.member IN (" . $data['memberssql'] . ")
            ", $data['memberssqlparams']);
            $data['groupmemberaverage'] = round($memberships/$data['users'], 1);
        }
        $data['strgroupmemberaverage'] = get_string('groupmemberaverage', 'admin', $data['groupmemberaverage']);
        if (!$data['views']) {
            $data['viewsperuser'] = 0;
        }
        else {
            $data['viewsperuser'] = get_field_sql("
                SELECT (0.0 + COUNT(id)) / NULLIF(COUNT(DISTINCT \"owner\"), 0)
                        FROM {view}
                        WHERE id IN (" . $data['viewssql'] . ")
                    ", $data['viewssqlparam']);
            $data['viewsperuser'] = round($data['viewsperuser'], 1);
        }
        $data['strviewsperuser'] = get_string('viewsperuser', 'admin', $data['viewsperuser']);
    }

    $data['name']        = $institution;
    $data['release']     = get_config('release');
    $data['version']     = get_config('version');
    if ($institution == 'mahara') {
        $data['installdate'] = format_date(strtotime(get_config('installation_time')), 'strftimedate');
    }
    else {
        // *** FIXME: See if better way to get this
        $data['installdate'] = format_date(strtotime(get_field_sql('SELECT MIN(ui.ctime) FROM {usr_institution} ui WHERE ui.institution = ?', array($institution))), 'strftimedate');
    }
    if ($data['users']) {
        $data['diskusage']   = get_field_sql("
            SELECT SUM(quotaused)
            FROM {usr}
            WHERE deleted = 0 AND id IN (" . $data['memberssql'] . ")
            ", $data['memberssqlparams']);
    }

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
    if ($full) {
        // Add the other overall graphs here
        // Users for institution graph
        if (!$data['users']) {
            $data['strmaxfriends'] = get_string('statsnofriends', 'admin');
            $data['strmaxviews'] = get_string('statsnoviews', 'admin');
            $data['strmaxgroups'] = get_string('statsnogroups', 'admin');
            $data['strmaxquotaused'] = get_string('statsnoquota', 'admin');

            $smarty = smarty_core();
            $smarty->assign('data', $data);
            $data['summary'] = $smarty->fetch('admin/institutionuserstatssummary.tpl');

        }
        else {
            $maxfriends = get_records_sql_array("
                SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, SUM(f.friends) AS friends
                FROM {usr} u INNER JOIN (
                    SELECT DISTINCT(usr1) AS id, COUNT(usr1) AS friends
                    FROM {usr_friend}
                    GROUP BY usr1
                    UNION SELECT DISTINCT(usr2) AS id, COUNT(usr2) AS friends
                    FROM {usr_friend}
                    GROUP BY usr2
                ) f ON u.id = f.id
                WHERE u.id IN (" . $data['memberssql'] . ")
                GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
                ORDER BY friends DESC
                LIMIT 1", $data['memberssqlparams']);
            $maxfriends = $maxfriends[0];
            $meanfriends = count_records_sql('SELECT COUNT(*) FROM
                        (SELECT * FROM {usr_friend}
                            WHERE usr1 IN (' . $data['memberssql'] . ')
                        UNION ALL SELECT * FROM {usr_friend}
                            WHERE usr2 IN (' . $data['memberssql'] . ')
                        ) tmp', array_merge($data['memberssqlparams'], $data['memberssqlparams'])) /
                        $data['users'];
            if ($maxfriends) {
                $data['strmaxfriends'] = get_string(
                    'statsmaxfriends1',
                    'admin',
                    $maxfriends->friends,
                    round($meanfriends, 1),
                    profile_url($maxfriends),
                    hsc(display_name($maxfriends, null, true))
                );
            }
            else {
                $data['strmaxfriends'] = get_string('statsnofriends', 'admin');
            }
            $maxviews = get_records_sql_array("
                SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(v.id) AS views
                FROM {usr} u JOIN {view} v ON u.id = v.owner
                WHERE \"owner\" IN (" . $data['memberssql'] . ")
                GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
                ORDER BY views DESC
                LIMIT 1", $data['memberssqlparams']);
            $maxviews = $maxviews[0];
            if ($maxviews) {
                $data['strmaxviews'] = get_string(
                    'statsmaxviews1',
                    'admin',
                    $maxviews->views,
                    $data['viewsperuser'],
                    profile_url($maxviews),
                    hsc(display_name($maxviews, null, true))
                );
            }
            else {
                $data['strmaxviews'] = get_string('statsnoviews', 'admin');
            }
            $maxgroups = get_records_sql_array("
404
                SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(m.group) AS groupcount
405
406
407
                FROM {usr} u JOIN {group_member} m ON u.id = m.member JOIN {group} g ON m.group = g.id
                WHERE g.deleted = 0 AND u.id IN (" . $data['memberssql'] . ")
                GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
408
                ORDER BY groupcount DESC
409
410
411
412
413
414
                LIMIT 1", $data['memberssqlparams']);
            $maxgroups = $maxgroups[0];
            if ($maxgroups) {
                $data['strmaxgroups'] = get_string(
                    'statsmaxgroups1',
                    'admin',
415
                    $maxgroups->groupcount,
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
                    $data['groupmemberaverage'],
                    profile_url($maxgroups),
                    hsc(display_name($maxgroups, null, true))
                );
            }
            else {
                $data['strmaxgroups'] = get_string('statsnogroups', 'admin');
            }
            $maxquotaused = get_records_sql_array("
                SELECT id, firstname, lastname, preferredname, urlid, quotaused
                FROM {usr}
                WHERE id IN (" . $data['memberssql'] . ")
                ORDER BY quotaused DESC
                LIMIT 1", $data['memberssqlparams']);
            $maxquotaused = $maxquotaused[0];
            $avgquota = get_field_sql("
                SELECT AVG(quotaused)
                FROM {usr}
                WHERE id IN (" . $data['memberssql'] . ")
                ", $data['memberssqlparams']);
            $data['strmaxquotaused'] = get_string(
                'statsmaxquotaused1',
                'admin',
                display_size($avgquota),
                profile_url($maxquotaused),
                hsc(display_name($maxquotaused, null, true)),
                display_size($maxquotaused->quotaused)
            );

            $smarty = smarty_core();
            $smarty->assign('data', $data);
            $data['usersinfo'] = $smarty->fetch('admin/institutionuserstatssummary.tpl');
        }
        // Views for institution graph
        $smarty = smarty_core();
        $maxblocktypes = 5;
        if ($data['views']) {
            $smarty->assign('blocktypecounts', get_records_sql_array("
                SELECT
                    b.blocktype,
                    CASE WHEN bi.artefactplugin IS NULL THEN b.blocktype
                        ELSE bi.artefactplugin || '/' || b.blocktype END AS langsection,
                    COUNT(b.id) AS blocks
                FROM {block_instance} b
                JOIN {blocktype_installed} bi ON (b.blocktype = bi.name)
                JOIN {view} v ON (b.view = v.id AND v.type = 'portfolio')
                WHERE v.id IN (" . $data['viewssql'] . ")
                GROUP BY b.blocktype, langsection
                ORDER BY blocks DESC",
                $data['viewssqlparam'], 0, $maxblocktypes
            ));
        }
        $smarty->assign('viewtypes', true);
        $smarty->assign('institution', $data['name']);
        $smarty->assign('viewcount', $data['views']);
        $data['viewsinfo'] = $smarty->fetch('admin/institutionviewstatssummary.tpl');
    }

474
475
476
    return($data);
}

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
function get_heading_html($heading) {
    $smarty = smarty_core();
    $smarty->assign('heading', $heading);
    return $smarty->fetch('admin/users/statsheading.tpl');
}

function get_active_columns(&$data, $extra) {
    $activeheadings = array();
    foreach ($data['tableheadings'] as $key => $heading) {
        $data['tableheadings'][$key]['selected'] = in_array($heading['id'], $extra['columns']);
        // make sure the required ones are always selected
        if (!empty($data['tableheadings'][$key]['required'])) {
            $data['tableheadings'][$key]['selected'] = true;
        }
        if ($data['tableheadings'][$key]['selected']) {
            $activeheadings[$data['tableheadings'][$key]['id']] = $data['tableheadings'][$key]['name'];
            // To add the accessibility info
            $data['tableheadings'][$key]['sr'] = get_string('sortby') . ' ' . get_string('ascending');
            if (!empty($extra['sortdesc']) && $extra['sort'] == $heading['id']) {
                $data['tableheadings'][$key]['sr'] = get_string('sortby') . ' ' . get_string('descending');
            }
            $data['tableheadings'][$key]['html'] = get_heading_html($data['tableheadings'][$key]);
        }
    }
    // Make sure the all active columns are selected
    return $activeheadings;
}

function userdetails_statistics_headers($extra, $urllink) {
    return array(
        array('id' => 'rownum', 'name' => '#'),
        array(
              'id' => 'firstname', 'required' => true,
              'name' => get_string('firstname'),
              'class' => format_class($extra, 'firstname'),
              'link' => format_goto($urllink . '&sort=firstname', $extra, array('sort'), 'firstname')
        ),
        array(
              'id' => 'lastname', 'required' => true,
              'name' => get_string('lastname'),
              'class' => format_class($extra, 'lastname'),
              'link' => format_goto($urllink . '&sort=lastname', $extra, array('sort'), 'lastname')
        ),
        array(
              'id' => 'email', 'required' => true,
              'name' => get_string('email'),
              'class' => format_class($extra, 'email'),
              'link' => format_goto($urllink . '&sort=email', $extra, array('sort'), 'email')
        ),
        array(
527
              'id' => 'studentid',
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
              'name' => get_string('studentid'),
              'class' => format_class($extra, 'studentid'),
              'link' => format_goto($urllink . '&sort=studentid', $extra, array('sort'), 'studentid')
        ),
        array(
              'id' => 'displayname', 'required' => true,
              'name' => get_string('displayname'),
              'class' => format_class($extra, 'displayname'),
              'link' => format_goto($urllink . '&sort=displayname', $extra, array('sort'), 'displayname')
        ),
        array(
              'id' => 'username', 'required' => true,
              'name' => get_string('username'),
              'class' => format_class($extra, 'username'),
              'link' => format_goto($urllink . '&sort=username', $extra, array('sort'), 'username')
        ),
        array(
545
              'id' => 'remotename',
546
547
548
549
              'name' => get_string('remoteuser', 'admin'),
              'class' => format_class($extra, 'remotename'),
              'link' => format_goto($urllink . '&sort=remotename', $extra, array('sort'), 'remotename')
        ),
550
551
552
553
554
555
        array(
              'id' => 'quotapercent',
              'name' => get_string('quotapercent', 'admin'),
              'class' => format_class($extra, 'quotapercent'),
              'link' => format_goto($urllink . '&sort=quotapercent', $extra, array('sort'), 'quotapercent')
        ),
556
        array(
557
              'id' => 'lastlogin',
558
559
560
561
562
563
564
565
              'name' => get_string('lastlogin', 'admin'),
              'class' => format_class($extra, 'lastlogin'),
              'link' => format_goto($urllink . '&sort=lastlogin', $extra, array('sort'), 'lastlogin')
        ),
    );
}

function userdetails_statistics($limit, $offset, $extra, $institution = null) {
566
    userhasaccess($institution, 'userdetails');
567
    $data = array();
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
    $urllink = get_config('wwwroot') . 'admin/users/statistics.php?type=users&subtype=userdetails';
    if ($institution) {
        $urllink .= '&institution=' . $institution;
    }
    $data['tableheadings'] = userdetails_statistics_headers($extra, $urllink);

    $activeheadings = get_active_columns($data, $extra);
    $extra['columns'] = array_keys($activeheadings);

    $data['table'] = userdetails_stats_table($limit, $offset, $extra, $institution, $urllink);
    $data['table']['activeheadings'] = $activeheadings;

    $data['summary'] = $data['table']['count'] == 0 ? get_string('nostats', 'admin') : null;

    return $data;
}

function userdetails_stats_table($limit, $offset, $extra, $institution, $urllink) {
    global $USER, $SESSION;

    $start = !empty($extra['start']) ? $extra['start'] : null;
    $end = !empty($extra['end']) ? $extra['end'] : date('Y-m-d', strtotime('now'));
    $users = $SESSION->get('usersforstats');

    $fromsql = " FROM {usr} u";
    $wheresql = " WHERE u.deleted = 0 AND id != 0";
    $where = array();
    if ($institution) {
        $fromsql .= " JOIN {usr_institution} ui ON (ui.usr = u.id AND ui.institution = ?)";
        $where = array($institution);
    }
    if ($users) {
        $wheresql .= " AND u.id IN (" . join(',', array_map('db_quote', array_values((array)$users))) . ")";
    }
    if ($start) {
        $wheresql .= " AND u.ctime >= DATE(?) AND u.ctime <= DATE(?)";
        $where[] = $start;
        $where[] = $end;
    }
    $count = count_records_sql("SELECT COUNT(*) " . $fromsql . $wheresql, $where);

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => $urllink,
        'jsonscript' => 'admin/users/statistics.json.php',
        'datatable' => 'statistics_table',
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
        'setlimit' => true,
        'extradata' => $extra,
    ));

    $result = array(
        'count'         => $count,
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

    $result['settings']['start'] = ($start) ? $start : null;
    $result['settings']['end'] = $end;
    $result['settings']['users'] = count($users);

    if ($count < 1) {
        return $result;
    }

    $sorttype = !empty($extra['sort']) ? $extra['sort'] : '';
    switch ($sorttype) {
        case "lastlogin":
        case "displayname":
        case "username":
        case "email":
        case "remotename":
643
        case "quotapercent":
644
645
646
647
648
649
650
651
652
653
654
655
656
        case "studentid":
            $orderby = " " . $sorttype . " " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC') . ", CONCAT (u.firstname, ' ', u.lastname)";
            break;
        case "lastname":
            $orderby = " u.lastname " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC') . ", u.firstname " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "firstname":
        default:
            $orderby = " u.firstname " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC') . ", u.lastname " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
    }

    $sql = "SELECT u.id, u.firstname, u.lastname, u.username, u.preferredname AS displayname,
            u.lastlogin, u.email, u.studentid, u.ctime,
657
658
            (SELECT remoteusername FROM {auth_remote_user} aru WHERE aru.localusr = u.id LIMIT 1) AS remotename,
            ((u.quotaused * 1.0)/ u.quota) AS quotapercent, u.quota, u.quotaused
659
            " . $fromsql . $wheresql . "
660
661
662
663
            ORDER BY " . $orderby;
    if (empty($extra['csvdownload'])) {
        $sql .= " LIMIT $limit OFFSET $offset";
    }
664
665
666
667
668
669
670
    $data = get_records_sql_array($sql, $where);
    $daterange = array_map(function ($obj) { return $obj->ctime; }, $data);
    $result['settings']['start'] = ($start) ? $start : min($daterange);

    foreach ($data as $item) {
        $item->profileurl = profile_url($item->id);
        $item->lastlogin = $item->lastlogin ? format_date(strtotime($item->lastlogin)) : ' ';
671
672
673
        $item->quotapercent_format = round($item->quotapercent * 100);
        $item->quota_format = display_size($item->quota);
        $item->quotaused_format = !empty($item->quotaused) ? display_size($item->quotaused) : 0;
674
675
676
        // Map statistics page column headers to CSV column headers to allow for easier user update CSV import
        $item->preferredname = $item->displayname;
        $item->remoteuser = $item->remotename;
677
    }
678
679
    if (!empty($extra['csvdownload'])) {
        $csvfields = array('firstname', 'lastname', 'email', 'studentid',
680
                           'preferredname', 'username', 'remoteuser', 'quotapercent_format', 'lastlogin');
681
682
        $USER->set_download_file(generate_csv($data, $csvfields), $institution . 'userdetailsstatistics.csv', 'text/csv');
    }
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
    $result['csv'] = true;
    $columnkeys = array();
    foreach ($extra['columns'] as $column) {
        $columnkeys[$column] = 1;
    }

    $smarty = smarty_core();
    $smarty->assign('data', $data);
    $smarty->assign('columns', $columnkeys);
    $smarty->assign('offset', $offset);

    $result['tablerows'] = $smarty->fetch('admin/users/userdetailsstats.tpl');

    return $result;
}

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
function useragreement_statistics_headers($extra, $urllink) {
    return array(
        array('id' => 'rownum', 'name' => '#'),
        array(
              'id' => 'firstname', 'required' => true,
              'name' => get_string('firstname'),
              'class' => format_class($extra, 'firstname'),
              'link' => format_goto($urllink . '&sort=firstname', $extra, array('sort'), 'firstname')
        ),
        array(
              'id' => 'lastname', 'required' => true,
              'name' => get_string('lastname'),
              'class' => format_class($extra, 'lastname'),
              'link' => format_goto($urllink . '&sort=lastname', $extra, array('sort'), 'lastname')
        ),
        array(
              'id' => 'displayname',
              'name' => get_string('displayname'),
              'class' => format_class($extra, 'displayname'),
              'link' => format_goto($urllink . '&sort=displayname', $extra, array('sort'), 'displayname')
        ),
        array(
              'id' => 'email',
              'name' => get_string('email'),
              'class' => format_class($extra, 'email'),
              'link' => format_goto($urllink . '&sort=email', $extra, array('sort'), 'email')
        ),
        array(
              'id' => 'username',
              'name' => get_string('username'),
              'class' => format_class($extra, 'username'),
              'link' => format_goto($urllink . '&sort=username', $extra, array('sort'), 'username')
        ),
        array(
              'id' => 'siteprivacy', 'required' => true,
              'name' => get_string('siteprivacy', 'admin'),
              'class' => format_class($extra, 'siteprivacy'),
              'link' => format_goto($urllink . '&sort=siteprivacy', $extra, array('sort'), 'siteprivacy')
        ),
        array(
              'id' => 'siteprivacyconsentdate',
              'name' => get_string('siteprivacyconsentdate', 'admin'),
              'class' => format_class($extra, 'siteprivacyconsentdate'),
              'link' => format_goto($urllink . '&sort=siteprivacyconsentdate', $extra, array('sort'), 'siteprivacyconsentdate')
        ),
        array(
              'id' => 'siteterms', 'required' => true,
              'name' => get_string('sitetermsandconditions', 'admin'),
              'class' => format_class($extra, 'siteterms'),
              'link' => format_goto($urllink . '&sort=siteterms', $extra, array('sort'), 'siteterms')
        ),
        array(
              'id' => 'sitetermsconsentdate',
              'name' => get_string('sitetermsconsentdate', 'admin'),
              'class' => format_class($extra, 'sitetermsconsentdate'),
              'link' => format_goto($urllink . '&sort=sitetermsconsentdate', $extra, array('sort'), 'sitetermsconsentdate')
        ),
        array(
              'id' => 'institutionprivacy', 'required' => true,
              'name' => get_string('institutionprivacystatement', 'admin'),
              'class' => format_class($extra, 'institutionprivacy'),
              'link' => format_goto($urllink . '&sort=institutionprivacy', $extra, array('sort'), 'institutionprivacy')
        ),
        array(
              'id' => 'institutionprivacyconsentdate',
              'name' => get_string('institutionprivacyconsentdate', 'admin'),
              'class' => format_class($extra, 'institutionprivacyconsentdate'),
              'link' => format_goto($urllink . '&sort=institutionprivacyconsentdate', $extra, array('sort'), 'institutionprivacyconsentdate')
        ),
        array(
              'id' => 'institutionterms', 'required' => true,
              'name' => get_string('institutiontermsandconditions', 'admin'),
              'class' => format_class($extra, 'institutionterms'),
              'link' => format_goto($urllink . '&sort=institutionterms', $extra, array('sort'), 'institutionterms')
        ),
        array(
              'id' => 'institutiontermsconsentdate',
              'name' => get_string('institutiontermsconsentdate', 'admin'),
              'class' => format_class($extra, 'institutiontermsconsentdate'),
              'link' => format_goto($urllink . '&sort=institutiontermsconsentdate', $extra, array('sort'), 'institutiontermsconsentdate')
        ),
        array(
              'id' => 'institution',
              'name' => get_string('institution', 'admin'),
              'class' => format_class($extra, 'institution'),
              'link' => format_goto($urllink . '&sort=institution', $extra, array('sort'), 'institution')
        ),
    );
}

function useragreement_statistics($limit, $offset, $extra, $institution = null) {
    userhasaccess($institution, 'useragreement');
    $data = array();
    $urllink = get_config('wwwroot') . 'admin/users/statistics.php?type=users&subtype=useragreement';
    if ($institution) {
        $urllink .= '&institution=' . $institution;
    }
    $data['tableheadings'] = useragreement_statistics_headers($extra, $urllink);

    $activeheadings = get_active_columns($data, $extra);
    $extra['columns'] = array_keys($activeheadings);

    $data['table'] = useragreement_stats_table($limit, $offset, $extra, $institution, $urllink);
    $data['table']['activeheadings'] = $activeheadings;

    $data['summary'] = $data['table']['count'] == 0 ? get_string('nostats', 'admin') : null;

    return $data;
}

function useragreement_stats_table($limit, $offset, $extra, $institution, $urllink) {
    global $USER, $SESSION;

    $start = !empty($extra['start']) ? $extra['start'] : null;
    $end = !empty($extra['end']) ? $extra['end'] : date('Y-m-d', strtotime('now'));
    $users = $SESSION->get('usersforstats');

    $fromsql = "
        FROM {usr_agreement} ua
        JOIN {usr} u ON u.id = ua.usr
        LEFT JOIN {usr_institution} ui ON ui.usr = ua.usr
        LEFT JOIN {institution} i ON i.name = ui.institution
        LEFT JOIN (
            SELECT MAX(ua.sitecontentid) AS siteprivacyid, MAX(ua.ctime) AS ctime, ua.usr
            FROM {usr_agreement} ua
            JOIN {site_content_version} s ON (s.id = ua.sitecontentid AND s.type = 'privacy' AND s.institution = 'mahara')
            GROUP BY ua.usr
        ) sp ON ua.usr = sp.usr
        LEFT JOIN (
            SELECT MAX(ua.sitecontentid) AS sitetermsid, MAX(ua.ctime) AS ctime, ua.usr
            FROM {usr_agreement} ua
            JOIN {site_content_version} s ON (s.id = ua.sitecontentid AND s.type = 'termsandconditions' AND s.institution = 'mahara')
            GROUP BY ua.usr
        ) st ON ua.usr = st.usr
        LEFT JOIN (
            SELECT MAX(ua.sitecontentid) AS institutionprivacyid, MAX(ua.ctime) AS ctime, ua.usr
            FROM {usr_agreement} ua
            JOIN {site_content_version} s ON (s.id = ua.sitecontentid AND s.type = 'privacy' AND s.institution != 'mahara')
            JOIN {usr_institution} ui ON (ui.institution = s.institution AND ui.usr = ua.usr)
            GROUP BY ua.usr
        ) ip ON ua.usr = ip.usr
        LEFT JOIN (
            SELECT MAX(ua.sitecontentid) AS institutiontermsid, MAX(ua.ctime) AS ctime, ua.usr
            FROM {usr_agreement} ua
            JOIN {site_content_version} s ON (s.id = ua.sitecontentid AND s.type = 'termsandconditions' AND s.institution != 'mahara')
            JOIN {usr_institution} ui ON (ui.institution = s.institution AND ui.usr = ua.usr)
            GROUP BY ua.usr
        ) it ON ua.usr = it.usr";
    $wheresql = " WHERE u.deleted = 0 AND u.id != 0";
    $where = array();
    if ($institution) {
        if ($institution == 'mahara') {
            $wheresql .= " AND ui.institution IS NULL";
        }
        else {
            $wheresql .= " AND ui.institution = ?";
            $where = array($institution);
        }
    }
    if ($users) {
        $wheresql .= " AND u.id IN (" . join(',', array_map('db_quote', array_values((array)$users))) . ")";
    }
    if ($start) {
        $wheresql .= " AND COALESCE(it.ctime, ip.ctime, st.ctime, sp.ctime) >= DATE(?) AND COALESCE(it.ctime, ip.ctime, st.ctime, sp.ctime) <= DATE(?)";
        $where[] = $start;
        $where[] = $end;
    }

    $count = count_records_sql("SELECT COUNT(DISTINCT(ua.usr)) " . $fromsql . $wheresql, $where);

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => $urllink,
        'jsonscript' => 'admin/users/statistics.json.php',
        'datatable' => 'statistics_table',
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
        'setlimit' => true,
        'extradata' => $extra,
    ));

    $result = array(
        'count'         => $count,
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

    $result['settings']['start'] = ($start) ? $start : null;
    $result['settings']['end'] = $end;
    $result['settings']['users'] = count($users);

    if ($count < 1) {
        return $result;
    }

    $sorttype = !empty($extra['sort']) ? $extra['sort'] : '';
    switch ($sorttype) {
        case "siteprivacy":
            $orderby = " (SELECT version FROM {site_content_version} WHERE id = sp.siteprivacyid) " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "siteterms":
            $orderby = " (SELECT version FROM {site_content_version} WHERE id = st.sitetermsid) " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "institutionprivacy":
            $orderby = " (SELECT version FROM {site_content_version} WHERE id = ip.institutionprivacyid) " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "institutionterms":
            $orderby = " (SELECT version FROM {site_content_version} WHERE id = it.institutiontermsid) " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "siteprivacyconsentdate":
            $orderby = " sp.ctime " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "sitetermsconsentdate":
            $orderby = " st.ctime " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "institutionprivacyconsentdate":
            $orderby = " ip.ctime " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "institutiontermsconsentdate":
            $orderby = " it.ctime " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "username":
        case "displayname":
        case "email":
            $orderby = " " . $sorttype . " " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC') . ", CONCAT (u.firstname, ' ', u.lastname)";
            break;
        case "lastname":
            $orderby = " u.lastname " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC') . ", u.firstname " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
            break;
        case "firstname":
        default:
            $orderby = " u.firstname " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC') . ", u.lastname " . (!empty($extra['sortdesc']) ? 'DESC' : 'ASC');
    }

    $sql = "SELECT DISTINCT ua.usr, sp.siteprivacyid, sp.ctime AS siteprivacyconsentdate, (SELECT version FROM {site_content_version} WHERE id = sp.siteprivacyid) AS siteprivacy,
            st.sitetermsid, st.ctime AS sitetermsconsentdate, (SELECT version FROM {site_content_version} WHERE id = st.sitetermsid) AS siteterms,
            ip.institutionprivacyid, ip.ctime AS institutionprivacyconsentdate, (SELECT version FROM {site_content_version} WHERE id = ip.institutionprivacyid) AS institutionprivacy,
            it.institutiontermsid, it.ctime AS institutiontermsconsentdate, (SELECT version FROM {site_content_version} WHERE id = it.institutiontermsid) AS institutionterms,
            u.id, u.username, u.firstname, u.lastname, u.preferredname AS displayname, u.email,
            i.name, i.displayname AS instname, COALESCE(it.ctime, ip.ctime, st.ctime, sp.ctime) AS defaulttime
            " . $fromsql . $wheresql . "
            ORDER BY " . $orderby;

    if (empty($extra['csvdownload'])) {
        $sql .= " LIMIT $limit OFFSET $offset";
    }
    $data = get_records_sql_array($sql, $where);

    foreach ($data as $item) {
        $item->profileurl = profile_url($item->id);
        $item->siteprivacyconsentdate = $item->siteprivacyconsentdate ? format_date(strtotime($item->siteprivacyconsentdate)) : ' ';
        $item->sitetermsconsentdate = $item->sitetermsconsentdate ? format_date(strtotime($item->sitetermsconsentdate)) : ' ';
        $item->institutionprivacyconsentdate = $item->institutionprivacyconsentdate ? format_date(strtotime($item->institutionprivacyconsentdate)) : ' ';
        $item->institutiontermsconsentdate = $item->institutiontermsconsentdate ? format_date(strtotime($item->institutiontermsconsentdate)) : ' ';
    }

    if (!empty($extra['csvdownload'])) {
        $csvfields = array('username', 'firstname', 'lastname', 'displayname', 'email',
                           'siteprivacy', 'siteprivacyconsentdate', 'siteterms', 'sitetermsconsentdate',
                           'institutionprivacy', 'institutionprivacyconsentdate', 'institutionterms', 'institutiontermsconsentdate',
                           'instname');
        $USER->set_download_file(generate_csv($data, $csvfields), $institution . 'useragreementsstatistics.csv', 'text/csv');
    }
    $result['csv'] = true;
    $columnkeys = array();
    foreach ($extra['columns'] as $column) {
        $columnkeys[$column] = 1;
    }

    $smarty = smarty_core();
    $smarty->assign('data', $data);
    $smarty->assign('columns', $columnkeys);
    $smarty->assign('offset', $offset);

    $result['tablerows'] = $smarty->fetch('admin/users/useragreementstats.tpl');

    return $result;
}

980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function useractivity_statistics_headers($extra, $urllink) {
    return array(
        array('id' => 'rownum', 'name' => '#'),
        array(
              'id' => 'firstname', 'required' => true,
              'name' => get_string('firstname'),
              'class' => format_class($extra, 'firstname'),
              'link' => format_goto($urllink . '&sort=firstname', $extra, array('sort'), 'firstname')
        ),
        array(
              'id' => 'lastname', 'required' => true,
              'name' => get_string('lastname'),
              'class' => format_class($extra, 'lastname'),
              'link' => format_goto($urllink . '&sort=lastname', $extra, array('sort'), 'lastname')
        ),
        array(
              'id' => 'displayname',
              'name' => get_string('displayname'),
              'class' => format_class($extra, 'displayname'),
              'link' => format_goto($urllink . '&sort=displayname', $extra, array('sort'), 'displayname')
        ),
For faster browsing, not all history is shown. View entire blame