statistics.php 207 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

    if ($latestversion = get_config('latest_version')) {
        $data['latest_version'] = $latestversion;
        if ($data['release'] == $latestversion) {
75
            $data['uptodate'] = get_string('uptodate', 'admin');
76 77 78 79 80 81
        }
        else {
            $download_page = 'https://launchpad.net/mahara/+download';
            $data['strlatestversion'] = get_string('latestversionis', 'admin', $download_page, $latestversion);
        }
    }
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
    if ($branchlatest = get_config('latest_branch_version')) {
        if ($data['release'] != $branchlatest) {
            $download_page = 'https://launchpad.net/mahara/+milestone/' . $branchlatest;
            $data['strlatestbranchversion'] = get_string('latestbranchversionis', 'admin', $download_page, $branchlatest);
        }
    }
    if ($insupport = get_config('supported_versions')) {
        $insupport = explode(',', $insupport);
        if (!in_array(get_config('series'), $insupport)) {
            if (preg_match('/dev$/', $data['release'])) {
                $data['strnotinsupport'] = get_string('versionnotinsupportdev', 'admin');
            }
            else {
                $data['strnotinsupport'] = get_string('versionnotinsupport', 'admin', get_config('series'));
            }
        }
    }
99

100 101 102 103 104
    if ($full) {
        // Add the other overall graphs here
        // Group graph
        $smarty = smarty_core();
        $smarty->assign('grouptypecounts', get_records_sql_array("
105
            SELECT grouptype, COUNT(id) AS groupcount
106 107 108
            FROM {group}
            WHERE deleted = 0
            GROUP BY grouptype
109
            ORDER BY groupcount DESC", array()
110 111
        ));
        $smarty->assign('jointypecounts', get_records_sql_array("
112
            SELECT jointype, COUNT(id) AS groupcount
113 114 115
            FROM {group}
            WHERE deleted = 0
            GROUP BY jointype
116
            ORDER BY groupcount DESC", array()
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
        ));
        $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("
172
            SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(m.group) AS groupcount
173 174 175
            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
176
            ORDER BY groupcount DESC
177 178 179 180 181 182
            LIMIT 1", array());
        $maxgroups = $maxgroups[0];
        if ($maxgroups) {
            $data['strmaxgroups'] = get_string(
                'statsmaxgroups1',
                'admin',
183
                $maxgroups->groupcount,
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
                $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;
215
        $blocktypecounts = get_records_sql_array("
216 217 218 219 220 221
            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')
222
            GROUP BY b.blocktype
223 224
            ORDER BY blocks DESC",
            array(), 0, $maxblocktypes
225
        );
226 227 228 229 230 231
        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();
            }
232 233 234
        }
        $smarty->assign('blocktypecounts', $blocktypecounts);

235 236 237 238
        $smarty->assign('viewtypes', true);
        $smarty->assign('viewcount', $data['views']);
        $data['viewsinfo'] = $smarty->fetch('admin/viewstatssummary.tpl');
    }
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
    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']);
        }
303
        $data['usersloggedin'] = get_string('loggedinsince', 'admin', $active->today, $active->thisweek, format_date(strtotime($active->weekago), 'strftimedate'), $active->ever);
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

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

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
    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("
421
                SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(m.group) AS groupcount
422 423 424
                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
425
                ORDER BY groupcount DESC
426 427 428 429 430 431
                LIMIT 1", $data['memberssqlparams']);
            $maxgroups = $maxgroups[0];
            if ($maxgroups) {
                $data['strmaxgroups'] = get_string(
                    'statsmaxgroups1',
                    'admin',
432
                    $maxgroups->groupcount,
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
                    $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');
    }

491 492 493
    return($data);
}

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
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(
544
              'id' => 'studentid',
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
              '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(
562
              'id' => 'remotename',
563 564 565 566
              'name' => get_string('remoteuser', 'admin'),
              'class' => format_class($extra, 'remotename'),
              'link' => format_goto($urllink . '&sort=remotename', $extra, array('sort'), 'remotename')
        ),
567 568 569 570 571 572
        array(
              'id' => 'quotapercent',
              'name' => get_string('quotapercent', 'admin'),
              'class' => format_class($extra, 'quotapercent'),
              'link' => format_goto($urllink . '&sort=quotapercent', $extra, array('sort'), 'quotapercent')
        ),
573
        array(
574
              'id' => 'lastlogin',
575 576 577 578
              'name' => get_string('lastlogin', 'admin'),
              'class' => format_class($extra, 'lastlogin'),
              'link' => format_goto($urllink . '&sort=lastlogin', $extra, array('sort'), 'lastlogin')
        ),
579 580 581 582 583 584 585
        array(
              'id' => 'probation',
              'name' => get_string('probationreportcolumn', 'admin'),
              'class' => format_class($extra, 'probation'),
              'link' => format_goto($urllink . '&sort=probation', $extra, array('sort'), 'probation'),
              'disabled' => empty(get_config('probationenabled'))
        ),
586 587 588 589
    );
}

function userdetails_statistics($limit, $offset, $extra, $institution = null) {
590
    userhasaccess($institution, 'userdetails');
591
    $data = array();
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    $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;
613
    $end = !empty($extra['end']) ? $extra['end'] : date('Y-m-d', strtotime('+1 day'));
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    $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;
654
    $result['settings']['users'] = !empty($users) ? count($users) : 0;
655 656 657 658 659 660 661 662 663 664 665 666

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

    $sorttype = !empty($extra['sort']) ? $extra['sort'] : '';
    switch ($sorttype) {
        case "lastlogin":
        case "displayname":
        case "username":
        case "email":
        case "remotename":
667
        case "quotapercent":
668
        case "studentid":
669
        case "probation":
670 671 672 673 674 675 676 677 678 679 680 681
            $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,
682
            (SELECT remoteusername FROM {auth_remote_user} aru WHERE aru.localusr = u.id LIMIT 1) AS remotename,
683
            ((u.quotaused * 1.0)/ u.quota) AS quotapercent, u.quota, u.quotaused, u.probation
684
            " . $fromsql . $wheresql . "
685 686 687 688
            ORDER BY " . $orderby;
    if (empty($extra['csvdownload'])) {
        $sql .= " LIMIT $limit OFFSET $offset";
    }
689 690 691 692 693 694 695
    $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)) : ' ';
696 697 698
        $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;
699 700 701
        // 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;
702
    }
703 704
    if (!empty($extra['csvdownload'])) {
        $csvfields = array('firstname', 'lastname', 'email', 'studentid',
705
                           'preferredname', 'username', 'remoteuser', 'quotapercent_format', 'lastlogin', 'probation');
706 707
        $USER->set_download_file(generate_csv($data, $csvfields), $institution . 'userdetailsstatistics.csv', 'text/csv');
    }
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    $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;
}

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
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;
838
    $end = !empty($extra['end']) ? $extra['end'] : date('Y-m-d', strtotime('+1 day'));
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
    $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;
915
    $result['settings']['users'] = !empty($users) ? count($users) : 0;
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

    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;
}

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
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'),
1036 1037
              'link' => format_goto($urllink . '&sort=artefacts', $extra, array('sort'), 'artefacts'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'artefacts')
1038 1039 1040 1041 1042
        ),
        array(
              'id' => 'pages', 'required' => true,
              'name' => get_string('Views', 'view'),
              'class' => format_class($extra, 'pages'),
1043 1044
              'link' => format_goto($urllink . '&sort=pages', $extra, array('sort'), 'pages'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'pages')
1045 1046 1047 1048 1049
        ),
        array(
              'id' => 'collections', 'required' => true,
              'name' => get_string('Collections', 'collection'),
              'class' => format_class($extra, 'collections'),
1050 1051
              'link' => format_goto($urllink . '&sort=collections', $extra, array('sort'), 'collections'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'collections')
1052 1053 1054 1055 1056
        ),
        array(
              'id' => 'groups', 'required' => true,
              'name' => get_string('groups'),
              'class' => format_class($extra, 'groups'),
1057 1058
              'link' => format_goto($urllink . '&sort=groups', $extra, array('sort'), 'groups'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'groups')
1059 1060 1061 1062 1063
        ),
        array(
              'id' => 'logins', 'required' => true,
              'name' => get_string('logins'),
              'class' => format_class($extra, 'logins'),
1064 1065
              'link' => format_goto($urllink . '&sort=logins', $extra, array('sort'), 'logins'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'logins')
1066 1067 1068 1069 1070
        ),
        array(
              'id' => 'actions',
              'name' => get_string('actions', 'statistics'),
              'class' => format_class($extra, 'actions'),
1071 1072
              'link' => format_goto($urllink . '&sort=actions', $extra, array('sort'), 'actions'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'actions')
1073 1074 1075
        ),
        array(
              'id' => 'lastlogin', 'required' => true,
Robert Lyon's avatar
Robert Lyon committed
1076
              'name' => get_string('lastactiontime', 'statistics'),
1077
              'class' => format_class($extra, 'lastlogin'),
1078 1079
              'link' => format_goto($urllink . '&sort=lastlogin', $extra, array('sort'), 'lastlogin'),
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'lastlogin')
1080 1081 1082
        ),
        array(
              'id' => 'lastactivity',
Robert Lyon's avatar
Robert Lyon committed
1083
              'name' => get_string('lastaction', 'statistics'),
1084
              'class' => format_class($extra, 'lastactivity'),
1085
              'helplink' => get_help_icon('core', 'reports', 'useractivity', 'lastactivity'),
1086
//              'link' => format_goto($urllink . '&sort=lastactivity', $extra, array('sort'), 'lastactivity')
1087 1088 1089 1090 1091
        ),
    );
}

function useractivity_statistics($limit, $offset, $extra, $institution = null) {
1092 1093 1094 1095
    userhasaccess($institution, 'useractivity');
    if (!get_config('eventlogenhancedsearch')) {
        return array('notvalid_errorstring' => get_string('needadvancedanalytics', 'statistics'));
    }
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
    $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;
1118
    $end = !empty($extra['end']) ? $extra['end'] : date('Y-m-d', strtotime('+1 day'));
1119 1120 1121
    $users = $SESSION->get('usersforstats');

    $fromsql = " FROM {usr} u";
1122
    $wheresql = " WHERE id != 0 AND u.lastlogin IS NOT NULL";
1123 1124
    $where = array();
    if ($institution) {
Robert Lyon's avatar
Robert Lyon committed
1125 1126 1127 1128 1129 1130 1131
        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);
        }
1132 1133 1134 1135 1136
    }
    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
1137 1138 1139 1140
        $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(?)
1141
                                  LIMIT 1)";
1142 1143 1144
        $where[] = $start;
        $where[] = $end;
    }
1145 1146 1147 1148 1149 1150
    $count = 0;
    $usrids = get_records_sql_assoc("SELECT id, username " . $fromsql . $wheresql, $where);
    if (!empty($usrids)) {
        $usrids = array_keys($usrids);
        $count = count($usrids);
    }
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

    $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;
1173
    $result['settings']['users'] = !empty($users) ? count($users) : 0;
1174 1175 1176 1177 1178 1179

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

    $sorttype = !empty($extra['sort']) ? $extra['sort'] : '';
1180 1181 1182 1183 1184
    $sortorder = "1";
    $sortdesc = !empty($extra['sortdesc']) ? 'desc' : 'asc';
    $sortdirection = '';
    $sortname = null;

1185 1186
    switch ($sorttype) {
        case "lastlogin":
1187 1188 1189 1190 1191
            $sortdirection = array('LastActivity' => $sortdesc);
            break;
        case "lastactivity":
            $sortdirection = array('LastLogin' => $sortdesc);
            break;
1192
        case "actions":
1193 1194
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
1195
        case "logins":
1196 1197 1198
            $sortorder = "doc.event.value == 'login' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
1199
        case "groups":
1200 1201 1202
            $sortorder = "doc.event.value == 'creategroup' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
1203
        case "collections":
1204 1205 1206
            $sortorder = "doc.event.value == 'createcollection' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
1207
        case "pages":
1208 1209 1210
            $sortorder = "doc.event.value == 'createview' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
1211
        case "artefacts":
1212 1213 1214
            $sortorder = "doc.event.value == 'saveartefact' ? 1 : 0";
            $sortdirection = array('EventTypeCount' => $sortdesc);
            break;
1215
        case "displayname":
1216 1217
            $sortname = 'preferredname';
            break;
1218
        case "username":
1219
            $sortname = 'username';
1220 1221
            break;
        case "lastname":
1222
            $sortname = 'lastname';
1223 1224 1225
            break;
        case "firstname":
        default:
1226
            $sortname = 'firstname';
1227 1228
    }

1229
    $result['settings']['start'] = $start;
1230

1231 1232 1233 1234 1235 1236 1237 1238
    // 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
1239
                ),
1240 1241
            ),
            'range' => array(
1242
                'range' => array(
1243 1244 1245
                    'ctime' => array(
                        'gte' => $result['settings']['start'] . ' 00:00:00',
                        'lte' => $result['settings']['end'] . ' 23:59:59'
1246 1247
                    )
                )
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
            ),
            '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
1273
                                    'inline' => "doc.ctime.value",
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
                                ),
                            ),
                        ),
                        '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
1301
                    return strnatcasecmp($a[$sortname], $b[$sortname]);
1302 1303 1304 1305 1306 1307
                });
                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'));
1308 1309
        }
    }
1310 1311

    $data = array();
1312 1313
    $timezone = new DateTimeZone(date_default_timezone_get()); // get timezone we are in
    $offsettime = $timezone->getOffset(new DateTime("now")); // work out offset in seconds
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    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;
1328 1329
            $lastactivity = get_field('event_log', 'event', 'id', $item['LastActivity']['value']);
            $obj->lastactivity = ($lastactivity) ? get_string($lastactivity, 'statistics') : '';
1330 1331
            $obj->profileurl = profile_url($item['key']);
            $date = $item['LastLogin']['value'] / 1000; // convert from UTC milliseconds
1332
            if ($offsettime < 0) {
1333 1334
                $date += $offsettime;
            }
1335 1336 1337
            if ($offsettime > 0) {
                $date -= $offsettime;
            }
1338 1339 1340 1341 1342 1343 1344 1345 1346
            $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);
    }

1347 1348 1349
    if (!empty($extra['csvdownload'])) {
        $csvfields = array('firstname', 'lastname', 'displayname', 'username',
                           'artefacts', 'pages', 'collections', 'groups', 'logins',
1350
                          'actions', 'lastlogin', 'lastactivity');
1351
        $USER->set_download_file(generate_csv($data, $csvfields), $institution . 'useractivitystatistics.csv', 'text/csv');
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
    }
    $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(
1373 1374 1375 1376
              'id' => 'date', 'required' => true,
              'name' => get_string('date'),
              'class' => format_class($extra, 'date'),
              'link' => format_goto($urllink . '&sort=date', $extra, array('sort'), 'date')
1377 1378 1379 1380 1381
        ),
        array(
              'id' => 'comments', 'required' => true,
              'name' => get_string('Comments', 'artefact.comment'),
              'class' => format_class($extra, 'comments'),
1382 1383
              'link' => format_goto($urllink . '&sort=comments', $extra, array('sort'), 'comments'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'comments')
1384 1385 1386 1387 1388
        ),
        array(
              'id' => 'annotations',
              'name' => get_string('Annotations', 'artefact.annotation'),
              'class' => format_class($extra, 'annotations'),
1389 1390
              'link' => format_goto($urllink . '&sort=annotations', $extra, array('sort'), 'annotations'),
              'helplink' => get_help_icon('core', 'reports', 'collaboration', 'annotations')
1391 1392 1393 1394 1395
        ),
        array(
              'id' => 'usershare', 'required' => true,
              'name' => get_string('usershare', 'statistics'),
              'class' => format_class($extra, 'usershare'),