statistics.php 173 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
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
<?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);
        $data['usersloggedin'] = get_string('loggedinsince', 'admin', $active->today, $active->thisweek, format_date(strtotime($active->weekago), 'strftimedateshort'), $active->ever);

        $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
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
    if ($full) {
        // Add the other overall graphs here
        // Group graph
        $smarty = smarty_core();
        $smarty->assign('grouptypecounts', get_records_sql_array("
            SELECT grouptype, COUNT(id) AS groups
            FROM {group}
            WHERE deleted = 0
            GROUP BY grouptype
            ORDER BY groups DESC", array()
        ));
        $smarty->assign('jointypecounts', get_records_sql_array("
            SELECT jointype, COUNT(id) AS groups
            FROM {group}
            WHERE deleted = 0
            GROUP BY jointype
            ORDER BY groups DESC", array()
        ));
        $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("
            SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(m.group) AS groups
            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
            ORDER BY groups DESC
            LIMIT 1", array());
        $maxgroups = $maxgroups[0];
        if ($maxgroups) {
            $data['strmaxgroups'] = get_string(
                'statsmaxgroups1',
                'admin',
                $maxgroups->groups,
                $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
215
        );
        foreach ($blocktypecounts as $blocktype) {
            safe_require('blocktype', $blocktype->blocktype);
            $classname = generate_class_name('blocktype', $blocktype->blocktype);
            $blocktype->title = $classname::get_title();
        }
        $smarty->assign('blocktypecounts', $blocktypecounts);

216
217
218
219
        $smarty->assign('viewtypes', true);
        $smarty->assign('viewcount', $data['views']);
        $data['viewsinfo'] = $smarty->fetch('admin/viewstatssummary.tpl');
    }
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
    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']);
        }
        $data['usersloggedin'] = get_string('loggedinsince', 'admin', $active->today, $active->thisweek, format_date(strtotime($active->weekago), 'strftimedateshort'), $active->ever);

        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']);
    }

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
    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("
                SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(m.group) AS groups
                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
                ORDER BY groups DESC
                LIMIT 1", $data['memberssqlparams']);
            $maxgroups = $maxgroups[0];
            if ($maxgroups) {
                $data['strmaxgroups'] = get_string(
                    'statsmaxgroups1',
                    'admin',
                    $maxgroups->groups,
                    $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');
    }

472
473
474
    return($data);
}

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
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(
525
              'id' => 'studentid',
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
              '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(
543
              'id' => 'remotename',
544
545
546
547
548
              'name' => get_string('remoteuser', 'admin'),
              'class' => format_class($extra, 'remotename'),
              'link' => format_goto($urllink . '&sort=remotename', $extra, array('sort'), 'remotename')
        ),
        array(
549
              'id' => 'lastlogin',
550
551
552
553
554
555
556
557
              '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) {
558
    userhasaccess($institution, 'userdetails');
559
    $data = array();
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
    $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":
        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,
            (SELECT remoteusername FROM {auth_remote_user} aru WHERE aru.localusr = u.id LIMIT 1) AS remotename
            " . $fromsql . $wheresql . "
650
651
652
653
            ORDER BY " . $orderby;
    if (empty($extra['csvdownload'])) {
        $sql .= " LIMIT $limit OFFSET $offset";
    }
654
655
656
657
658
659
660
661
    $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)) : ' ';
    }
662
663
664
665
666
    if (!empty($extra['csvdownload'])) {
        $csvfields = array('firstname', 'lastname', 'email', 'studentid',
                           'displayname', 'username', 'remotename', 'lastlogin');
        $USER->set_download_file(generate_csv($data, $csvfields), $institution . 'userdetailsstatistics.csv', 'text/csv');
    }
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
    $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;
}

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')
        ),
        array(
              'id' => 'username',
              'name' => get_string('username'),
              'class' => format_class($extra, 'username'),
              'link' => format_goto($urllink . '&sort=username', $extra, array('sort'), 'username')
        ),
        array(
              'id' => 'artefacts', 'required' => true,
              'name' => get_string('artefacts'),
              'class' => format_class($extra, 'artefacts'),
714
715
              'link' => format_goto($urllink . '&sort=artefacts', $extra, array('sort'), 'artefacts'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'artefacts')
716
717
718
719
720
        ),
        array(
              'id' => 'pages', 'required' => true,
              'name' => get_string('Views', 'view'),
              'class' => format_class($extra, 'pages'),
721
722
              'link' => format_goto($urllink . '&sort=pages', $extra, array('sort'), 'pages'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'pages')
723
724
725
726
727
        ),
        array(
              'id' => 'collections', 'required' => true,
              'name' => get_string('Collections', 'collection'),
              'class' => format_class($extra, 'collections'),
728
729
              'link' => format_goto($urllink . '&sort=collections', $extra, array('sort'), 'collections'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'collections')
730
731
732
733
734
        ),
        array(
              'id' => 'groups', 'required' => true,
              'name' => get_string('groups'),
              'class' => format_class($extra, 'groups'),
735
736
              'link' => format_goto($urllink . '&sort=groups', $extra, array('sort'), 'groups'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'groups')
737
738
739
740
741
        ),
        array(
              'id' => 'logins', 'required' => true,
              'name' => get_string('logins'),
              'class' => format_class($extra, 'logins'),
742
743
              'link' => format_goto($urllink . '&sort=logins', $extra, array('sort'), 'logins'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'logins')
744
745
746
747
748
        ),
        array(
              'id' => 'actions',
              'name' => get_string('actions', 'statistics'),
              'class' => format_class($extra, 'actions'),
749
750
              'link' => format_goto($urllink . '&sort=actions', $extra, array('sort'), 'actions'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'actions')
751
752
753
        ),
        array(
              'id' => 'lastlogin', 'required' => true,
Robert Lyon's avatar
Robert Lyon committed
754
              'name' => get_string('lastactiontime', 'statistics'),
755
              'class' => format_class($extra, 'lastlogin'),
756
757
              'link' => format_goto($urllink . '&sort=lastlogin', $extra, array('sort'), 'lastlogin'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'lastlogin')
758
759
760
        ),
        array(
              'id' => 'lastactivity',
Robert Lyon's avatar
Robert Lyon committed
761
              'name' => get_string('lastaction', 'statistics'),
762
              'class' => format_class($extra, 'lastactivity'),
763
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'lastactivity'),
764
//              'link' => format_goto($urllink . '&sort=lastactivity', $extra, array('sort'), 'lastactivity')
765
766
767
768
769
        ),
    );
}

function useractivity_statistics($limit, $offset, $extra, $institution = null) {
770
771
772
773
    userhasaccess($institution, 'useractivity');
    if (!get_config('eventlogenhancedsearch')) {
        return array('notvalid_errorstring' => get_string('needadvancedanalytics', 'statistics'));
    }
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
    $data = array();
    $urllink = get_config('wwwroot') . 'admin/users/statistics.php?type=users&subtype=useractivity';
    if ($institution) {
        $urllink .= '&institution=' . $institution;
    }
    $data['tableheadings'] = useractivity_statistics_headers($extra, $urllink);

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

    $data['table'] = useractivity_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 useractivity_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";
800
    $wheresql = " WHERE id != 0 AND u.lastlogin IS NOT NULL";
801
802
    $where = array();
    if ($institution) {
Robert Lyon's avatar
Robert Lyon committed
803
804
805
806
807
808
809
        if ($institution == 'mahara') {
            $fromsql .= " LEFT JOIN {usr_institution} ui ON (ui.usr = u.id AND ui.institution IS NULL)";
        }
        else {
            $fromsql .= " JOIN {usr_institution} ui ON (ui.usr = u.id AND ui.institution = ?)";
            $where = array($institution);
        }
810
811
812
813
814
    }
    if ($users) {
        $wheresql .= " AND u.id IN (" . join(',', array_map('db_quote', array_values((array)$users))) . ")";
    }
    if ($start) {
Robert Lyon's avatar
Robert Lyon committed
815
816
817
818
        $wheresql .= " AND EXISTS(SELECT usr FROM {event_log} el
                                  WHERE el.usr = u.id
                                  AND el.event = 'login'
                                  AND el.ctime >= DATE(?) AND el.ctime <= DATE(?)
819
                                  LIMIT 1)";
820
821
822
        $where[] = $start;
        $where[] = $end;
    }
823
824
825
826
827
828
    $count = 0;
    $usrids = get_records_sql_assoc("SELECT id, username " . $fromsql . $wheresql, $where);
    if (!empty($usrids)) {
        $usrids = array_keys($usrids);
        $count = count($usrids);
    }
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

    $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'] : '';
858
859
860
861
862
    $sortorder = "1";
    $sortdesc = !empty($extra['sortdesc']) ? 'desc' : 'asc';
    $sortdirection = '';
    $sortname = null;

863
864
    switch ($sorttype) {
        case "lastlogin":
865
866
867
868
869
            $sortdirection = array('LastActivity' => $sortdesc);
            break;
        case "lastactivity":
            $sortdirection = array('LastLogin' => $sortdesc);
            break;
870
        case "actions":
871
872
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
873
        case "logins":
874
875
876
            $sortorder = "doc.event.value == 'login' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
877
        case "groups":
878
879
880
            $sortorder = "doc.event.value == 'creategroup' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
881
        case "collections":
882
883
884
            $sortorder = "doc.event.value == 'createcollection' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
885
        case "pages":
886
887
888
            $sortorder = "doc.event.value == 'createview' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
889
        case "artefacts":
890
891
892
            $sortorder = "doc.event.value == 'saveartefact' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
893
        case "displayname":
894
895
            $sortname = 'preferredname';
            break;
896
        case "username":
897
            $sortname = 'username';
898
899
            break;
        case "lastname":
900
            $sortname = 'lastname';
901
902
903
            break;
        case "firstname":
        default:
904
            $sortname = 'firstname';
905
906
    }

907
    $result['settings']['start'] = $start;
908

909
910
911
912
913
914
915
916
    // Add in the elasticsearch data if needed
    $aggmap = array();
    if (get_config('searchplugin') == 'elasticsearch') {
        safe_require('search', 'elasticsearch');
        $options = array(
            'query' => array(
                'terms' => array(
                    'usr' => $usrids
917
                ),
918
919
            ),
            'range' => array(
920
                'range' => array(
921
922
923
                    'ctime' => array(
                        'gte' => $result['settings']['start'] . ' 00:00:00',
                        'lte' => $result['settings']['end'] . ' 23:59:59'
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
            ),
            'aggs' => array(
                'UsrId' => array(
                    'terms' => array(
                        'field' => 'usr',
                        'order' => $sortdirection,
                        'size' => $count,
                     ),
                     'aggs' => array(
                        'EventType' => array(
                            'terms' => array(
                                'field' => 'event',
                                'min_doc_count' => 0,
                            ),
                        ),
                        'EventTypeCount' => array(
                            'sum' => array(
                                'script' => array(
                                    'inline' => $sortorder,
                                ),
                            ),
                        ),
                        'LastLogin' => array(
                            'max' => array(
                                'script' => array(
Robert Lyon's avatar
Robert Lyon committed
951
                                    'inline' => "doc.ctime.value",
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
                                ),
                            ),
                        ),
                        'LastActivity' => array(
                            'max' => array(
                                'script' => array(
                                    'inline' => "doc.id.value",
                                ),
                            ),
                        ),
                    ),
                ),
            ),
        );
        if (empty($sortdirection)) { unset($options['aggs']['UsrId']['terms']['order']); }
        $aggregates = PluginSearchElasticsearch::search_events($options, 0, 0);
        if ($aggregates['totalresults'] > 0) {
            foreach ($aggregates['aggregations']['UsrId']['buckets'] as $k => $usr) {
                $user = new User();
                $user->find_by_id($usr['key']);
                $aggregates['aggregations']['UsrId']['buckets'][$k]['firstname'] = $user->get('firstname');
                $aggregates['aggregations']['UsrId']['buckets'][$k]['lastname'] = $user->get('lastname');
                $aggregates['aggregations']['UsrId']['buckets'][$k]['username'] = $user->get('username');
                $aggregates['aggregations']['UsrId']['buckets'][$k]['preferredname'] = $user->get('preferredname');
            }
            if (!empty($sortname)) {
                usort($aggregates['aggregations']['UsrId']['buckets'], function ($a, $b) use ($sortname) {
Robert Lyon's avatar
Robert Lyon committed
979
                    return strnatcasecmp($a[$sortname], $b[$sortname]);
980
981
982
983
984
985
                });
                if ($sortdesc == 'desc') {
                    $aggregates['aggregations']['UsrId']['buckets'] = array_reverse($aggregates['aggregations']['UsrId']['buckets']);
                }
            }
            ElasticsearchType_event_log::process_aggregations($aggmap, $aggregates['aggregations'], true, array('UsrId', 'EventType'));
986
987
        }
    }
988
989

    $data = array();
990
991
    $timezone = new DateTimeZone(date_default_timezone_get()); // get timezone we are in
    $offsettime = $timezone->getOffset(new DateTime("now")); // work out offset in seconds
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
    if ($aggregates['totalresults'] > 0) {
        foreach ($aggregates['aggregations']['UsrId']['buckets'] as $item) {
            $obj = new stdClass();
            $obj->id = $item['key'];
            $obj->firstname = $item['firstname'];
            $obj->lastname = $item['lastname'];
            $obj->username = $item['username'];
            $obj->displayname = $item['preferredname'];
            $obj->ctime = null;
            $obj->artefacts = !empty($aggmap[$item['key'] . '|saveartefact']) ? $aggmap[$item['key'] . '|saveartefact'] : 0;
            $obj->pages = !empty($aggmap[$item['key'] . '|createview']) ? $aggmap[$item['key'] . '|createview'] : 0;
            $obj->collections = !empty($aggmap[$item['key'] . '|createcollection']) ? $aggmap[$item['key'] . '|createcollection'] : 0;
            $obj->groups = !empty($aggmap[$item['key'] . '|creategroup']) ? $aggmap[$item['key'] . '|creategroup'] : 0;
            $obj->logins = !empty($aggmap[$item['key'] . '|login']) ? $aggmap[$item['key'] . '|login'] : 0;
1006
1007
            $lastactivity = get_field('event_log', 'event', 'id', $item['LastActivity']['value']);
            $obj->lastactivity = ($lastactivity) ? get_string($lastactivity, 'statistics') : '';
1008
1009
            $obj->profileurl = profile_url($item['key']);
            $date = $item['LastLogin']['value'] / 1000; // convert from UTC milliseconds
1010
            if ($offsettime < 0) {
1011
1012
                $date += $offsettime;
            }
1013
1014
1015
            if ($offsettime > 0) {
                $date -= $offsettime;
            }
1016
1017
1018
1019
1020
1021
1022
1023
1024
            $obj->lastlogin = $item['LastLogin']['value'] ? date('d F Y, H:i a', $date) : '';
            $obj->actions = $item['doc_count'];
            $data[] = $obj;
        }
    }
    if (empty($extra['csvdownload'])) {
        $data = array_slice($data, $offset, $limit, true);
    }

1025
1026
1027
    if (!empty($extra['csvdownload'])) {
        $csvfields = array('firstname', 'lastname', 'displayname', 'username',
                           'artefacts', 'pages', 'collections', 'groups', 'logins',
1028
                          'actions', 'lastlogin', 'lastactivity');
1029
        $USER->set_download_file(generate_csv($data, $csvfields), $institution . 'useractivitystatistics.csv', 'text/csv');
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
    }
    $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/useractivitystats.tpl');

    return $result;
}

function collaboration_statistics_headers($extra, $urllink) {
    return array(
        array('id' => 'rownum', 'name' => '#'),
        array(
1051
1052
1053
1054
              'id' => 'date', 'required' => true,
              'name' => get_string('date'),
              'class' => format_class($extra, 'date'),
              'link' => format_goto($urllink . '&sort=date', $extra, array('sort'), 'date')
1055
1056
1057
1058
1059
        ),
        array(
              'id' => 'comments', 'required' => true,
              'name' => get_string('Comments', 'artefact.comment'),
              'class' => format_class($extra, 'comments'),
1060
1061
              'link' => format_goto($urllink . '&sort=comments', $extra, array('sort'), 'comments'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'comments')
1062
1063
1064
1065
1066
        ),
        array(
              'id' => 'annotations',
              'name' => get_string('Annotations', 'artefact.annotation'),
              'class' => format_class($extra, 'annotations'),
1067
1068
              'link' => format_goto($urllink . '&sort=annotations', $extra, array('sort'), 'annotations'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'annotations')
1069
1070
1071
1072
1073
        ),
        array(
              'id' => 'usershare', 'required' => true,
              'name' => get_string('usershare', 'statistics'),
              'class' => format_class($extra, 'usershare'),
1074
1075
              'link' => format_goto($urllink . '&sort=usershare', $extra, array('sort'), 'usershare'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'users')
1076
1077
1078
1079
1080
        ),
        array(
              'id' => 'groupshare', 'required' => true,
              'name' => get_string('groupshare', 'statistics'),
              'class' => format_class($extra, 'groupshare'),
1081
1082
              'link' => format_goto($urllink . '&sort=groupshare', $extra, array('sort'), 'groupshare'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'groups')
1083
1084
1085
1086
1087
        ),
        array(
              'id' => 'institutionshare', 'required' => true,
              'name' => get_string('institutionshare', 'statistics'),
              'class' => format_class($extra, 'institutionshare'),
1088
1089
              'link' => format_goto($urllink . '&sort=institutionshare', $extra, array('sort'), 'institutionshare'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'institutions')
1090
1091
1092
1093
1094
        ),
        array(
              'id' => 'loggedinshare', 'required' => true,
              'name' => get_string('loggedinshare', 'statistics'),
              'class' => format_class($extra, 'loggedinshare'),
1095
1096
              'link' => format_goto($urllink . '&sort=loggedinshare', $extra, array('sort'), 'loggedinshare'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'registered')
1097
1098
1099
1100
1101
        ),
        array(
              'id' => 'publicshare', 'required' => true,
              'name' => get_string('publicshare', 'statistics'),
              'class' => format_class($extra, 'publicshare'),
1102
1103
              'link' => format_goto($urllink . '&sort=publicshare', $extra, array('sort'), 'publicshare'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'public')
1104
1105
1106
1107
1108
        ),
        array(
              'id' => 'secretshare', 'required' => true,
              'name' => get_string('secretshare', 'statistics'),
              'class' => format_class($extra, 'secretshare'),
1109
1110
              'link' => format_goto($urllink . '&sort=secretshare', $extra, array('sort'), 'secretshare'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'secreturls')
1111
1112
1113
1114
1115
        ),
        array(
              'id' => 'friendshare',
              'name' => get_string('friendshare', 'statistics'),
              'class' => format_class($extra, 'friendshare'),
1116
1117
              'link' => format_goto($urllink . '&sort=friendshare', $extra, array('sort'), 'friendshare'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'friends')
1118
1119
1120
1121
1122
        ),
    );
}

function collaboration_statistics($limit, $offset, $extra, $institution = null) {
1123
1124
1125
1126
    userhasaccess($institution, 'collaboration');
    if (!get_config('eventlogenhancedsearch')) {
        return array('notvalid_errorstring' => get_string('needadvancedanalytics', 'statistics'));
    }
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
    $data = array();
    $urllink = get_config('wwwroot') . 'admin/users/statistics.php?type=users&subtype=collaboration';
    if ($institution) {
        $urllink .= '&institution=' . $institution;
    }
    $data['tableheadings'] = collaboration_statistics_headers($extra, $urllink);

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

    $data['table'] = collaboration_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 collaboration_stats_table($limit, $offset, $extra, $institution, $urllink) {
    global $USER;

1148
    $start = !empty($extra['start']) ? $extra['start'] : date('Y-m-d', strtotime("-1 months"));
1149
    $end = !empty($extra['end']) ? $extra['end'] : date('Y-m-d', strtotime('now'));
1150
1151
1152
1153
1154
1155
    $from = strtotime($start);
    $to = strtotime($end);
    $daterange = array();
    while ($from < $to) {
        $daterange[date("Y_W", $from)] = date('Y-m-d', $from);
        $from = $from + (7 * 24 * 60 * 60); // Break down the range by weeks
1156
    }
1157
    $daterange[date("Y_W", $to)] = date('Y-m-d', $to);
1158
1159

    $count = count($daterange);
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186

    $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;
    if ($count < 1) {
        return $result;
    }

    $sorttype = !empty($extra['sort']) ? $extra['sort'] : '';
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
    $aggmap = array();
    if (get_config('searchplugin') == 'elasticsearch') {
        safe_require('search', 'elasticsearch');
        $options = array(
            'range' => array(
                'range' => array(
                    'ctime' => array(
                        'gte' => $start . ' 00:00:00',
                        'lt' => $end . ' 00:00:00'
                    )
                )
            ),
            'sort' => array(
                'ctime' => 'desc'
            ),
            'aggs' => array(
                'YearWeek' => array(
                    'terms' => array(
                        'field' => 'yearweek',
                    ),
                    'aggs' => array(
                        'EventType' => array(
                            'terms' => array(
                                'field' => 'event',
                            ),
                            'aggs' => array(
                                'ResourceType' => array(
                                    'terms' => array(
                                        'field' => 'resourcetype',
                                    ),
                                    'aggs' => array(
                                        'ParentResourceType' => array(
                                            'terms' => array(
                                                'field' => 'parentresourcetype',
                                            ),
                                        ),
                                    ),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
        );
Robert Lyon's avatar
Robert Lyon committed
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
        if ($institution) {
            // restrict results to users from the institution
            if ($institution == 'mahara') {
                $usrids = get_records_sql_assoc("SELECT u.id, u.username FROM {usr} u
                                                 LEFT JOIN {usr_institution} ui ON ui.usr = u.id
                                                 JOIN {event_log} el ON el.usr = u.id
                                                 WHERE ui.institution IS NULL
                                                 AND el.event = 'login'
                                                 AND el.ctime >= DATE(?) AND el.ctime <= DATE(?)
                                                 GROUP BY u.id", array($start, $end));
            }
            else {
                $usrids = get_records_sql_assoc("SELECT u.id, u.username FROM {usr} u
                                                 JOIN {usr_institution} ui ON ui.usr = u.id
                                                 JOIN {event_log} el ON el.usr = u.id
                                                 WHERE ui.institution = ?
                                                 AND el.event = 'login'
                                                 AND el.ctime >= DATE(?) AND el.ctime <= DATE(?)
                                                 GROUP BY u.id", array($institution, $start, $end));
            }
            if (!empty($usrids)) {
                $usrids = array_keys($usrids);
                $options['query'] = array(
                    'terms' => array(
                        'usr' => $usrids
                    ),
                );
            }
            else {
                return $result;
            }
        }
1263
1264
1265
1266
1267
        $aggregates = PluginSearchElasticsearch::search_events($options, 0, 0);
        if ($aggregates['totalresults'] > 0) {
            ElasticsearchType_event_log::process_aggregations($aggmap, $aggregates['aggregations'], true, array('YearWeek', 'EventType', 'ResourceType', 'ParentResourceType'));
        }
    }
1268
1269
    $result['settings']['start'] = ($start) ? $start : min($daterange);

1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
    $rawdata = array();
    // if sorting by date
    if ($sorttype == 'date' && !empty($extra['sortdesc'])) {
        $daterange = array_reverse($daterange);
    }

    foreach ($daterange as $k => $v) {
        list ($year, $week) = explode('_', $k);
        $obj = new StdClass();
        $obj->date = get_string('collaborationdate', 'statistics', format_date(strtotime($year . "W" . $week . '1'), 'strfdaymonthyearshort'));
        $obj->yearweek = $k;
1281
1282
1283
1284
1285
1286
1287
1288
1289
        $obj->comments = !empty($aggmap[$k . '|saveartefact|comment']) ? $aggmap[$k . '|saveartefact|comment'] : 0;
        $obj->annotations = !empty($aggmap[$k . '|saveartefact|annotation']) ? $aggmap[$k . '|saveartefact|annotation'] : 0;
        $obj->usershare = !empty($aggmap[$k . '|updateviewaccess|user']) ? $aggmap[$k . '|updateviewaccess|user'] : 0;
        $obj->groupshare = !empty($aggmap[$k . '|updateviewaccess|group']) ? $aggmap[$k . '|updateviewaccess|group'] : 0;
        $obj->institutionshare = !empty($aggmap[$k . '|updateviewaccess|institution']) ? $aggmap[$k . '|updateviewaccess|institution'] : 0;
        $obj->loggedinshare = !empty($aggmap[$k . '|updateviewaccess|loggedin']) ? $aggmap[$k . '|updateviewaccess|loggedin'] : 0;
        $obj->publicshare = !empty($aggmap[$k . '|updateviewaccess|public']) ? $aggmap[$k . '|updateviewaccess|public'] : 0;
        $obj->secretshare = !empty($aggmap[$k . '|updateviewaccess|token']) ? $aggmap[$k . '|updateviewaccess|token'] : 0;
        $obj->friendshare = !empty($aggmap[$k . '|updateviewaccess|friends']) ? $aggmap[$k . '|updateviewaccess|friends'] : 0;
1290

1291
        $rawdata[$k] = $obj;
1292
1293
    }

1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
    // if sorting by something other than date
    if (!empty($sorttype) && $sorttype != 'date') {
        uasort ($rawdata, function ($i, $j) use ($sorttype) {
            $a = $i->{$sorttype};
            $b = $j->{$sorttype};
            if ($a == $b) {
                return 0;
            }
            else if ($a > $b) {
                return 1;
            }
            else {
                return -1;
            }
        });
        if (!empty($extra['sortdesc'])) {
           $rawdata = array_reverse($rawdata);
        }
    }

    // Now do the limit / offset for pagination
    if (empty($extra['csvdownload'])) {
        $data = array_slice($rawdata, $offset, $limit, true);
    }
    else {
        $data = $rawdata;
        $csvfields = array('date', 'comments', 'annotations', 'usershare', 'groupshare',
                           'institutionshare', 'loggedinshare', 'publicshare', 'secretshare',
                           'friendshare');
        $USER->set_download_file(generate_csv($data, $csvfields), $institution . 'collaborationstatistics.csv', 'text/csv');
    }
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
    $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/collaborationstats.tpl');

    return $result;
}

1341
function users_statistics_headers($extra, $urllink) {
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
    return array(
        array('id' => 'rownum', 'name' => '#'),
        array(
              'id' => 'date', 'required' => true,
              'name' => get_string('date'),
              'class' => format_class($extra, 'date'),
              'link' => format_goto($urllink . '&sort=date', $extra, array('sort'), 'date')
        ),
        array(
              'id' => 'loggedin', 'required' => true,
              'name' => get_string('Loggedin', 'admin'),
              'class' => format_class($extra, 'loggedin'),
1354
1355
              'link' => format_goto($urllink . '&sort=loggedin', $extra, array('sort'), 'loggedin'),
              'helplink' => get_help_icon('core', 'reports', 'users', 'loggedin')
1356
1357
1358
1359
1360
        ),
        array(
              'id' => 'created', 'required' => true,
              'name' => get_string('Created'),
              'class' => format_class($extra, 'created'),
1361
              'helplink' => get_help_icon('core', 'reports', 'users', 'created'),
1362
1363
1364
1365
1366
1367
//              'link' => format_goto($urllink . '&sort=created', $extra, array('sort'), 'created')
        ),
        array(
              'id' => 'total', 'required' => true,
              'name' => get_string('Total'),
              'class' => format_class($extra, 'total'),
1368
1369
              'link' => format_goto($urllink . '&sort=total', $extra, array('sort'), 'total'),
              'helplink' => get_help_icon('core', 'reports', 'users', 'total')
1370
        ),
1371
    );
1372
1373
}

1374
function user_statistics($limit, $offset, $extra) {
1375
1376
    $data = array();
    $urllink = get_config('wwwroot') . 'admin/users/statistics.php?type=users&subtype=users';
1377
    $data['tableheadings'] = users_statistics_headers($extra, $urllink);
1378
1379
1380
1381
1382
1383

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

    $data['table'] = user_stats_table($limit, $offset, $extra);
    $data['table']['activeheadings'] = $activeheadings;
1384

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

    return $data;
}

1390
function user_stats_table($limit, $offset, $extra) {
1391
1392
    global $USER;

1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
    $start = !empty($extra['start']) ? $extra['start'] : date('Y-m-d', strtotime("-1 months"));
    $end = !empty($extra['end']) ? $extra['end'] : date('Y-m-d', strtotime('now'));

    if ($start) {
        $where = "type = ? AND ctime >= DATE(?) AND ctime <= DATE(?)";
        $count = count_records_select('site_data', $where, array('user-count-daily', $start, $end));
    }
    else {
        $count = count_records('site_data', 'type', 'user-count-daily');
    }
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => get_config('wwwroot') . 'admin/users/statistics.php?type=users',
        'jsonscript' => 'admin/users/statistics.json.php',
        'datatable' => 'statistics_table',
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
        'setlimit' => true,
1413
        'extradata' => $extra,
1414
1415
1416
1417
1418
1419
1420
1421
1422
    ));

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

1423
1424
    $result['settings']['start'] = ($start) ? $start : null;
    $result['settings']['end'] = $end;
1425
1426
1427
1428
1429
1430
    if ($count < 1) {
        return $result;
    }

    $day = is_postgres() ? "to_date(t.ctime::text, 'YYYY-MM-DD')" : 'DATE(t.ctime)'; // TODO: make work on other databases?

1431
    $sorttype = !empty($extra['sort']) ? $extra['sort'] : '';
1432
1433
1434
1435
1436
1437
    if (is_mysql()) {
        $cast = " (value + 0) ";
    }
    else {
        $cast = " CAST(value AS INTEGER) ";
    }
1438
1439
1440
1441
    switch ($sorttype) {
        case "total":
            $rangesql = " type = 'user-count-daily'";
            $ordersql = " ORDER BY type = 'loggedin-users-daily' DESC";
1442
            $ordersql .= ", " . $cast . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
1443
1444
1445
1446
1447
            $ordersql .= ", ctime " . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
            break;
        case "loggedin":
            $rangesql = " type = 'loggedin-users-daily'";
            $ordersql = " ORDER BY type = 'loggedin-users-daily' DESC";
1448
            $ordersql .= ", " . $cast . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
            $ordersql .= ", ctime " . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
            break;
        case "date":
        default:
            $rangesql = " type = 'user-count-daily'";
            $ordersql = " ORDER BY type = 'user-count-daily' " . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
            $ordersql .= ", ctime " . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
    }

    // Get the min/max daterange within supplied date range
    $rangewhere = array();
    if ($start) {
        $rangesql .= " AND ctime >= DATE(?) AND ctime <= DATE(?)";
        $rangewhere[] = $start;
        $rangewhere[] = $end;
    }

    $sql = "SELECT $day AS date
            FROM {site_data} t
1468
1469
1470
1471
            WHERE " . $rangesql . $ordersql;
    if (empty($extra['csvdownload'])) {
            $sql .= " LIMIT $limit OFFSET $offset";
    }
1472
1473
1474
1475
1476
1477
    $dateranges = get_records_sql_array($sql, $rangewhere);
    $daterange = array();
    foreach ($dateranges as $d) {
        $daterange[] = $d->date;
    }
    $result['settings']['start'] = ($start) ? $start : min($daterange);
1478
1479
1480
1481
1482

    $dayinterval = is_postgres() ? "'1 day'" : '1 day';

    $day = is_postgres() ? "to_date(ctime::text, 'YYYY-MM-DD')" : 'DATE(ctime)';

1483
    $usersql = "SELECT ctime, type, \"value\", $day AS date
1484
        FROM {site_data}
1485
1486
        WHERE type IN (?,?) AND $day IN (" . join(',', array_map('db_quote', $daterange)) . ")" . $ordersql;
    $userdata = get_records_sql_array($usersql, array('user-count-daily', 'loggedin-users-daily'));
1487

1488
    $userscreatedsql = "SELECT $day AS cdate, COUNT(id) AS users
1489
        FROM {usr}
1490
1491
        WHERE ctime IS NOT NULL AND $day IN (" . join(',', array_map('db_quote', $daterange)) . ")
        GROUP BY cdate";
1492

1493
1494
1495
    $userscreated = get_records_sql_array($userscreatedsql, array());

    $data = array_fill_keys($daterange, array());
1496
1497
1498
1499

    if ($userdata) {
        foreach ($userdata as &$r) {
            if ($r->type == 'user-count-daily') {
1500
1501
                $data[$r->date]['date'] = $r->date;
                $data[$r->date]['total'] = $r->value;
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
            }
            else if ($r->type == 'loggedin-users-daily' && isset($data[$r->date])) {
                $data[$r->date]['loggedin'] = $r->value;
            }
        }
        if ($userscreated) {
            foreach ($userscreated as &$r) {
                if (isset($data[$r->cdate])) {
                    $data[$r->cdate]['created'] = $r->users;
                }
            }
        }
    }
1515
1516
1517
1518
    if (!empty($extra['csvdownload'])) {
        $csvfields = array('date', 'loggedin', 'created', 'total');
        $USER->set_download_file(generate_csv($data, $csvfields), 'userstatistics.csv', 'text/csv');
    }
1519
    $result['csv'] = true;
1520
1521
1522
1523
    $columnkeys = array();
    foreach ($extra['columns'] as $column) {
        $columnkeys[$column] = 1;
    }
1524
1525
1526

    $smarty = smarty_core();
    $smarty->assign('data', $data);
1527
1528
    $smarty->assign('columns', $columnkeys);
    $smarty->assign('offset', $offset);
1529
1530
1531
1532
1533
    $result['tablerows'] = $smarty->fetch('admin/userstats.tpl');

    return $result;
}

1534
function institution_user_statistics($limit, $offset, &$institutiondata, $extra) {
1535
    userhasaccess($institutiondata['institution'], 'users');
1536
1537
    $data = array();
    $data['institution'] = $institutiondata['institution'];
1538
1539
    $urllink = get_config('wwwroot') . 'admin/users/statistics.php?institution=' . $data['institution'] . '&type=users&subtype=users';

1540
    $data['tableheadings'] = users_statistics_headers($extra, $urllink);
1541
1542
1543
1544
1545
1546

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

    $data['table'] = institution_user_stats_table($limit, $offset, $institutiondata, $extra);
    $data['table']['activeheadings'] = $activeheadings;
1547

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

    return $data;
}

1553
function institution_user_stats_table($limit, $offset, &$institutiondata, $extra) {
1554
1555
    global $USER;

1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
    $start = !empty($extra['start']) ? $extra['start'] : null;
    $end = !empty($extra['end']) ? $extra['end'] : date('Y-m-d', strtotime('now'));

    if ($start) {
        $where = "type = ? AND institution = ? AND ctime >= DATE(?) AND ctime <= DATE(?)";
        $count = count_records_select('institution_data', $where, array('user-count-daily', $institutiondata['name'], $start, $end));
    }
    else {
        $count = count_records('institution_data', 'type', 'user-count-daily', 'institution', $institutiondata['name']);
    }
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => get_config('wwwroot') . 'admin/users/statistics.php?institution=' . $institutiondata['name'] . '&type=users',
        'jsonscript' => 'admin/users/statistics.json.php',
        'datatable' => 'statistics_table',
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
        'setlimit' => true,
1576
        'extradata' => $extra,
1577
1578
1579
1580
1581
1582
1583
1584
    ));

    $result = array(
        'count'         => $count,
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );
1585
1586
    $result['settings']['start'] = ($start) ? $start : null;
    $result['settings']['end'] = $end;
1587
1588
1589
1590
1591
1592
    if ($count < 1) {
        return $result;
    }

    $day = is_postgres() ? "to_date(t.ctime::text, 'YYYY-MM-DD')" : 'DATE(t.ctime)'; // TODO: make work on other databases?

1593
    $sorttype = !empty($extra['sort']) ? $extra['sort'] : '';
1594
1595
1596
1597
1598
1599
    if (is_mysql()) {
        $cast = " (value + 0) ";
    }
    else {
        $cast = " CAST(value AS INTEGER) ";
    }
1600
1601
1602
1603
    switch ($sorttype) {
        case "total":
            $rangesql = " type = 'user-count-daily'";
            $ordersql = " ORDER BY type = 'loggedin-users-daily' DESC";
1604
            $ordersql .= ", " . $cast . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
1605
1606
1607
1608
1609
            $ordersql .= ", ctime " . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
            break;
        case "loggedin":
            $rangesql = " type = 'loggedin-users-daily'";
            $ordersql = " ORDER BY type = 'loggedin-users-daily' DESC";
1610
            $ordersql .= ", " . $cast . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
            $ordersql .= ", ctime " . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
            break;
        case "date":
        default:
            $rangesql = " type = 'user-count-daily'";
            $ordersql = " ORDER BY type = 'user-count-daily' " . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
            $ordersql .= ", ctime " . (!empty($extra['sortdesc']) ? 'ASC' : 'DESC');
    }

    // Get the min/max daterange within supplied date range
    $rangesql .= " AND institution = ?";
    $rangewhere = array($institutiondata['name']);
    if ($start) {
        $rangesql .= " AND ctime >= DATE(?) AND ctime <= DATE(?)";
        $rangewhere[] = $start;
        $rangewhere[] = $end;
    }

    $sql = "SELECT $day AS date
            FROM {institution_data} t
1631
1632
1633
1634
            WHERE " . $rangesql . $ordersql;
    if (empty($extra['csvdownload'])) {
        $sql .= " LIMIT $limit OFFSET $offset";
    }
1635
1636
1637
1638
1639
1640
    $dateranges = get_records_sql_array($sql, $rangewhere);
    $daterange = array();
    foreach ($dateranges as $d) {
        $daterange[] = $d->date;
    }
    $result['settings']['start'] = ($start) ? $start : min($daterange);
1641
1642
1643
1644
1645

    $dayinterval = is_postgres() ? "'1 day'" : '1 day';

    $day = is_postgres() ? "to_date(ctime::text, 'YYYY-MM-DD')" : 'DATE(ctime)';