registration.php 77 KB
Newer Older
1
2
<?php
/**
3
4
5
6
 *
 * @package    mahara
 * @subpackage core
 * @author     Catalyst IT Ltd
7
8
 * @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.
9
10
11
12
13
 * @file Register a mahara site
 */
/**
 * @defgroup Registration Registration
 * Send site information to mahara.org
Aaron Wells's avatar
Aaron Wells committed
14
 *
15
 */
Aaron Wells's avatar
Aaron Wells committed
16

17
18
19
20
defined('INTERNAL') || die();

/**
 * @return string that is the registation form
Aaron Wells's avatar
Aaron Wells committed
21
 * @ingroup Registration
22
23
 */
function register_site()  {
Nigel McNie's avatar
Nigel McNie committed
24
25
    $strfield = get_string('Field', 'admin');
    $strvalue = get_string('Value', 'admin');
26
    $info = <<<EOF
27
28
29
30
31
32
33
34
35

<table class="table table-striped table-bordered" id="register-table">
    <thead>
        <tr>
            <th>$strfield</th>
            <th>$strvalue</th>
        </tr>
    </thead>
    <tbody>
36
37
38
EOF;
    $data = registration_data();
    foreach($data as $key => $val) {
39
        $info .= '<tr><th>'. hsc($key) . '</th><td>' . hsc($val) . "</td></tr>\n";
40
    }
41
    $info .= '</tbody></table>';
42

43
44
45
46
47
48
    $form = array(
        'name' => 'register',
        'autofocus' => false,
        'elements' => array(
            'whatsent' => array(
                'type' => 'fieldset',
Nigel McNie's avatar
Nigel McNie committed
49
                'legend' => get_string('datathatwillbesent', 'admin'),
50
                'class' => "collapse",
51
52
53
                'elements' => array(
                    'info' => array(
                        'type' => 'markup',
Nigel McNie's avatar
Nigel McNie committed
54
                        'value'=> $info,
55
56
57
58
59
                    ),
                )
            ),
            'sendweeklyupdates' => array(
                'type' => 'checkbox',
Nigel McNie's avatar
Nigel McNie committed
60
61
                'title' => get_string('sendweeklyupdates', 'admin'),
                'defaultvalue' => true,
62
63
64
            ),
            'register' => array(
                'type' => 'submit',
65
                'class' => 'btn-success',
Nigel McNie's avatar
Nigel McNie committed
66
                'value' => get_string('Register', 'admin'),
67
68
69
            ),
        )
     );
Aaron Wells's avatar
Aaron Wells committed
70

71
72
73
74
75
     return pieform($form);
}
/**
 * Runs when registration form is submitted
 */
76
77
78
function register_submit(Pieform $form, $values) {
    global $SESSION;

79
    $result = registration_send_data();
80
    $data = json_decode($result->data);
81

82
    if ($data->status != 1) {
Nigel McNie's avatar
Nigel McNie committed
83
84
        log_info($result);
        $SESSION->add_error_msg(get_string('registrationfailedtrylater', 'admin', $result->info['http_code']));
85
86
    }
    else {
87
        set_config('registration_lastsent', time());
88
        set_config('registration_sendweeklyupdates', $values['sendweeklyupdates']);
89
        $SESSION->add_ok_msg(get_string('registrationsuccessfulthanksforregistering', 'admin'));
90
91
    }
    redirect('/admin/');
92
93
}

94
95
96
97
98

/**
 * Worker - performs sending of registration data to mahara.org
 */
function registration_send_data() {
99
    $registrationurl = 'https://mahara.org/api/registration.php';
100
101
102
103
104
105
    $data = registration_data();
    $request = array(
        CURLOPT_URL        => $registrationurl,
        CURLOPT_POST       => 1,
        CURLOPT_POSTFIELDS => $data,
    );
106
    return mahara_http_request($request);
107
108
}

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
function registration_store_data() {
    $data = registration_data();
    db_begin();
    $registration_id = insert_record('site_registration', (object)array(
        'time' => db_format_timestamp(time()),
    ), 'id', true);
    foreach ($data as $key => $value) {
        insert_record('site_registration_data', (object)array(
            'registration_id' => $registration_id,
            'field'           => $key,
            'value'           => ($value == null ? '' : $value)
        ));
    }
    db_commit();
}
124

125
126
127
/**
 * Builds the data that will be sent by the "register your site" feature
 */
128
function registration_data() {
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    foreach (array(
        'wwwroot',
        'installation_key',
        'sitename',
        'dbtype',
        'lang',
        'theme',
        'enablenetworking',
        'allowpublicviews',
        'allowpublicprofiles',
        'version',
        'release') as $key) {
        $data_to_send[$key] = get_config($key);
    }

144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    // System information
    $data_to_send['phpversion'] = phpversion();
    $data_to_send['dbversion'] = get_field_sql('SELECT VERSION()');
    $osversion = php_uname('s');
    if ($osversion == 'Linux') {
        $lsbversion = exec('lsb_release -d', $execout, $return_val);
        if ($return_val === 0) {
            $osversion = $lsbversion;
        }
        else {
            $osversion = php_uname();
        }
    }
    $data_to_send['osversion'] = $osversion;
    $data_to_send['phpsapi'] = php_sapi_name();
    if (!empty($_SERVER) && !empty($_SERVER['SERVER_SOFTWARE'])) {
        $data_to_send['webserver'] = $_SERVER['SERVER_SOFTWARE'];
    }
    $modules = get_loaded_extensions();
    natcasesort($modules);
    $data_to_send['phpmodules'] = '; ' . implode('; ', $modules) . ';';

166
167
168
169
170
171
172
173
174
175
    foreach (array(
        'usr_friend',
        'usr_institution',
        'group_member',
        'block_instance',
        'institution',
        'blocktype_wall_post',
        'institution') as $key) {
        $data_to_send['count_' . $key] = count_records($key);
    }
176

177
178
179
180
181
182
183
    foreach (array(
        'usr',
        'group',
        'host') as $key) {
        $data_to_send['count_' . $key] = count_records_select($key, 'deleted = 0');
        }

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    // Don't include the root user
    $data_to_send['count_usr']--;

    // Slightly more drilled down information
    if ($data = get_records_sql_array('SELECT artefacttype, COUNT(*) AS count
        FROM {artefact}
        GROUP BY artefacttype', array())) {
        foreach ($data as $artefacttypeinfo) {
            $data_to_send['artefact_type_' . $artefacttypeinfo->artefacttype] = $artefacttypeinfo->count;
        }
    }

    if ($data = get_records_sql_array('SELECT type, COUNT(*) AS count
        FROM {view}
        GROUP BY type', array())) {
        foreach ($data as $viewtypeinfo) {
            $data_to_send['view_type_' . $viewtypeinfo->type] = $viewtypeinfo->count;
        }
    }
203

204
205
206
207
208
209
210
    // Plugin versions
    foreach (plugin_types() as $type) {
        foreach (plugins_installed($type) as $plugin) {
            $data_to_send['plugin_' . $type . '_' . $plugin->name . '_version'] = $plugin->version;
        }
    }

211
212
    $data_to_send['newstats'] = 1;

213
    return $data_to_send;
214
}
215

216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
function institution_registration_store_data() {
    $data = institution_registration_data();
    db_begin();
    foreach ($data as $institution => $inst_data) {
        $registration_id = insert_record('institution_registration', (object)array(
            'time'        => db_format_timestamp(time()),
            'institution' => $institution,
        ), 'id', true);
        foreach ($inst_data as $key => $value) {
            insert_record('institution_registration_data', (object)array(
                'registration_id' => $registration_id,
                'field'           => $key,
                'value'           => $value
            ));
        }
    }
    db_commit();
}

235
236
237
238
239
function institution_registration_data() {
    $data_to_store = array();
    foreach (get_column('institution', 'name') as $institution) {
        $inst_data = array();
        if ($institution == 'mahara') {
240
241
242
243
            $membersquery = 'SELECT id FROM {usr}
                    WHERE deleted = 0 AND id > 0 AND
                    id NOT IN (SELECT usr FROM {usr_institution})';
            $membersqueryparams = array();
244
245
        }
        else {
246
            $membersquery = 'SELECT usr FROM {usr_institution} ui
247
                    JOIN {usr} u ON (u.id = ui.usr)
248
249
                    WHERE u.deleted = 0 AND ui.institution = ?';
            $membersqueryparams = array($institution);
250
        }
251
252
253
254
        $inst_data['count_members'] = count_records_sql('SELECT count(*) FROM {usr}
                WHERE id IN (' . $membersquery . ')',
                $membersqueryparams);
        if ($inst_data['count_members'] == 0) {
255
256
257
258
259
260
261
262
263
264
265
266
            $inst_data['count_views'] = 0;
            $inst_data['count_blocks'] = 0;
            $inst_data['count_artefacts'] = 0;
            $inst_data['count_interaction_forum_post'] = 0;
            $inst_data['usersloggedin'] = 0;
            $data_to_store[$institution] = $inst_data;
            continue;
        }
        $inst_data['count_views'] = 0;
        if ($data = get_records_sql_array('SELECT tmp.type, SUM(tmp.count) AS count
                FROM (SELECT v.type, COUNT(*) AS count
                    FROM {view} v
267
                    WHERE v.owner IS NOT NULL AND v.owner IN (' . $membersquery . ')
268
269
270
271
272
273
                    GROUP BY v.type
                UNION ALL
                    SELECT v.type, COUNT(*) AS count
                    FROM {view} v
                    WHERE v.institution IS NOT NULL AND v.institution = ?
                    GROUP BY v.type
274
                ) tmp GROUP BY tmp.type', array_merge($membersqueryparams, array($institution)))) {
275
276
277
278
279
280
281
282
283
284
            foreach ($data as $viewtypeinfo) {
                $inst_data['view_type_' . $viewtypeinfo->type] = $viewtypeinfo->count;
                $inst_data['count_views'] += $viewtypeinfo->count;
            }
        }
        $inst_data['count_blocks'] = 0;
        if ($data = get_records_sql_array('SELECT tmp.type, SUM(tmp.count) AS count
                FROM (SELECT bi.blocktype AS type, COUNT(*) AS count
                    FROM {block_instance} bi
                    JOIN {view} v ON v.id = bi.view
285
                    WHERE v.owner IS NOT NULL AND v.owner IN (' . $membersquery . ')
286
287
288
289
290
291
292
                    GROUP BY bi.blocktype
                UNION ALL
                    SELECT bi.blocktype AS type, COUNT(*) AS count
                    FROM {block_instance} bi
                    JOIN {view} v ON v.id = bi.view
                    WHERE v.institution IS NOT NULL AND v.institution = ?
                    GROUP BY bi.blocktype
293
                ) tmp GROUP BY tmp.type', array_merge($membersqueryparams, array($institution)))) {
294
295
296
297
298
299
300
301
            foreach ($data as $blocktypeinfo) {
                $inst_data['blocktype_' . $blocktypeinfo->type] = $blocktypeinfo->count;
                $inst_data['count_blocks'] += $blocktypeinfo->count;
            }
        }
        $inst_data['count_artefacts'] = 0;
        if ($data = get_records_sql_array('SELECT a.artefacttype AS type, COUNT(*) AS count
                FROM {artefact} a
302
303
                WHERE a.author IN (' . $membersquery . ')
                GROUP BY a.artefacttype', $membersqueryparams)) {
304
305
306
307
308
309
            foreach ($data as $artefacttypeinfo) {
                $inst_data['artefact_type_' . $artefacttypeinfo->type] = $artefacttypeinfo->count;
                $inst_data['count_artefacts'] += $artefacttypeinfo->count;
            }
        }
        $inst_data['count_interaction_forum_post'] = count_records_select('interaction_forum_post',
310
311
                'poster IN (' . $membersquery . ')',
                $membersqueryparams);
312
313
314
315
316
317
318
319
320
321
        if (is_postgres()) {
            $weekago = "CURRENT_DATE - INTERVAL '1 week'";
            $thisweeksql = "(lastaccess > $weekago)::int";
        }
        else {
            $weekago = 'CURRENT_DATE - INTERVAL 1 WEEK';
            $thisweeksql = "lastaccess > $weekago";
        }
        if ($data = get_record_sql('SELECT SUM(' . $thisweeksql . ') AS sum
                FROM {usr} u
322
323
                WHERE u.id IN (' . $membersquery . ')',
                $membersqueryparams)) {
324
            $inst_data['usersloggedin'] = isset($data->sum) ? $data->sum : 0;
325
326
327
328
        }
        else {
            $inst_data['usersloggedin'] = 0;
        }
329
330
331
332
333
334

        $data_to_store[$institution] = $inst_data;
    }
    return $data_to_store;
}

335
function site_data_current() {
336
337
338
    return array(
        'users' => count_records_select('usr', 'id > 0 AND deleted = 0'),
        'groups' => count_records('group', 'deleted', 0),
339
        'views' => count_records_select('view', 'owner != 0 OR owner IS NULL'),
340
341
342
    );
}

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

346
347
    if ($full) {
        $data = site_data_current();
348
        $data['weekly'] = true;
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

        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
        ");
371
        $data['groupmemberaverage'] = round($memberships/$data['users'], 1);
372
373
        $data['strgroupmemberaverage'] = get_string('groupmemberaverage', 'admin', $data['groupmemberaverage']);
        $data['viewsperuser'] = get_field_sql("
Francois Marier's avatar
Francois Marier committed
374
            SELECT (0.0 + COUNT(id)) / NULLIF(COUNT(DISTINCT \"owner\"), 0)
375
            FROM {view}
Francois Marier's avatar
Francois Marier committed
376
            WHERE NOT \"owner\" IS NULL AND \"owner\" > 0
377
        ");
378
        $data['viewsperuser'] = round($data['viewsperuser'], 1);
379
        $data['strviewsperuser'] = get_string('viewsperuser', 'admin', $data['viewsperuser']);
380
    }
381

382
    $data['name']        = get_config('sitename');
383
384
385
386
387
    $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');
388
    $data['cronrunning'] = !record_exists_select('cron', 'nextrun IS NULL OR nextrun < CURRENT_DATE');
389
    $data['siteclosedbyadmin'] = get_config('siteclosedbyadmin');
Richard Mansfield's avatar
Richard Mansfield committed
390

391
392
393
394
395
396
397
398
399
    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);
        }
400
    }
401

402
    return($data);
403
404
}

405
406
407
function institution_data_current($institution) {
    $data = array();
    if ($institution == 'mahara') {
408
        $membersquery = 'SELECT id FROM {usr}
409
                WHERE deleted = 0 AND id > 0 AND id NOT IN
410
411
                (SELECT usr FROM {usr_institution})';
        $membersqueryparams = array();
412
413
    }
    else {
414
        $membersquery = 'SELECT usr FROM {usr_institution} ui
415
                JOIN {usr} u ON (u.id = ui.usr)
416
417
                WHERE u.deleted = 0 AND ui.institution = ?';
        $membersqueryparams = array($institution);
418
    }
419
    $data['members'] = get_column_sql($membersquery, $membersqueryparams);
420
421
422
423
424
425
426
    $data['users'] = count($data['members']);
    if (!$data['users']) {
        $data['views'] = 0;
    }
    else {
        $data['viewids'] = get_column_sql('
                SELECT id FROM {view}
427
                    WHERE owner IS NOT NULL AND owner IN (' . $membersquery . ')
428
429
430
                UNION
                    SELECT id FROM {view}
                    WHERE institution IS NOT NULL AND institution = ?'
431
                , array_merge($membersqueryparams, array($institution)));
432
433
434
435
436
        $data['views'] = count($data['viewids']);
    }
    return $data;
}

437
438
439
440
441
function institution_statistics($institution, $full=false) {
    $data = array();

    if ($full) {
        $data = institution_data_current($institution);
442
443
        $data['weekly'] = true;
        $data['institution'] = $institution;
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513

        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 (" . join(',', array_fill(0, $data['users'], '?')) . ")";
            $active = get_record_sql($sql, $data['members']);
        }
        $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 (" . join(',', array_fill(0, $data['users'], '?')) . ")
            ", $data['members']);
            $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 (" . join(',', array_fill(0, $data['views'], '?')) . ")
            ", $data['viewids']);
            $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 (" . join(',', array_fill(0, $data['users'], '?')) . ")
            ", $data['members']);
    }

    return($data);
}

514
function user_statistics($limit, $offset, &$sitedata) {
515
516
    $data = array();
    $data['tableheadings'] = array(
517
518
519
520
        array('name' => get_string('date')),
        array('name' => get_string('Loggedin', 'admin'), 'class' => 'center'),
        array('name' => get_string('Created'), 'class' => 'center'),
        array('name' => get_string('Total'), 'class' => 'center'),
521
522
    );
    $data['table'] = user_stats_table($limit, $offset);
523
524
    $data['tabletitle'] = get_string('userstatstabletitle', 'admin');

525
    $maxfriends = get_records_sql_array("
526
        SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, SUM(f.friends) AS friends
527
528
529
530
531
532
533
534
        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
535
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
536
        ORDER BY friends DESC
537
        LIMIT 1", array());
538
539
    $maxfriends = $maxfriends[0];
    $meanfriends = 2 * count_records('usr_friend') / $sitedata['users'];
540
541
    if ($maxfriends) {
        $data['strmaxfriends'] = get_string(
542
            'statsmaxfriends1',
543
            'admin',
544
            $maxfriends->friends,
545
            round($meanfriends, 1),
546
            profile_url($maxfriends),
547
            hsc(display_name($maxfriends, null, true))
548
549
550
551
552
        );
    }
    else {
        $data['strmaxfriends'] = get_string('statsnofriends', 'admin');
    }
553
    $maxviews = get_records_sql_array("
554
        SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(v.id) AS views
555
        FROM {usr} u JOIN {view} v ON u.id = v.owner
Francois Marier's avatar
Francois Marier committed
556
        WHERE \"owner\" <> 0
557
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
558
559
560
        ORDER BY views DESC
        LIMIT 1", array());
    $maxviews = $maxviews[0];
561
562
    if ($maxviews) {
        $data['strmaxviews'] = get_string(
563
            'statsmaxviews1',
564
            'admin',
565
            $maxviews->views,
566
            $sitedata['viewsperuser'],
567
            profile_url($maxviews),
568
            hsc(display_name($maxviews, null, true))
569
570
571
572
573
        );
    }
    else {
        $data['strmaxviews'] = get_string('statsnoviews', 'admin');
    }
574
    $maxgroups = get_records_sql_array("
575
        SELECT u.id, u.firstname, u.lastname, u.preferredname, u.urlid, COUNT(m.group) AS groups
576
577
        FROM {usr} u JOIN {group_member} m ON u.id = m.member JOIN {group} g ON m.group = g.id
        WHERE g.deleted = 0
578
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
579
580
581
        ORDER BY groups DESC
        LIMIT 1", array());
    $maxgroups = $maxgroups[0];
582
583
    if ($maxgroups) {
        $data['strmaxgroups'] = get_string(
584
            'statsmaxgroups1',
585
            'admin',
586
            $maxgroups->groups,
587
            $sitedata['groupmemberaverage'],
588
            profile_url($maxgroups),
589
            hsc(display_name($maxgroups, null, true))
590
591
592
593
594
        );
    }
    else {
        $data['strmaxgroups'] = get_string('statsnogroups', 'admin');
    }
595
    $maxquotaused = get_records_sql_array("
596
        SELECT id, firstname, lastname, preferredname, urlid, quotaused
597
598
599
600
601
602
        FROM {usr}
        WHERE deleted = 0 AND id > 0
        ORDER BY quotaused DESC
        LIMIT 1", array());
    $maxquotaused = $maxquotaused[0];
    $data['strmaxquotaused'] = get_string(
603
        'statsmaxquotaused1',
604
605
        'admin',
        display_size(get_field('usr', 'AVG(quotaused)', 'deleted', 0)),
606
        profile_url($maxquotaused),
607
        hsc(display_name($maxquotaused, null, true)),
608
609
610
611
612
613
614
        display_size($maxquotaused->quotaused)
    );

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

615
616
617
618
    return $data;
}

function user_stats_table($limit, $offset) {
619
620
    global $USER;

621
622
623
624
625
    $count = count_records('site_data', 'type', 'user-count-daily');

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => get_config('wwwroot') . 'admin/statistics.php?type=users',
626
627
        'jsonscript' => 'admin/statistics.json.php',
        'datatable' => 'statistics_table',
628
629
630
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
631
        'setlimit' => true,
632
633
634
    ));

    $result = array(
635
        'count'         => $count,
636
637
638
639
640
641
642
643
644
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

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

645
    $day = is_postgres() ? "to_date(t.ctime::text, 'YYYY-MM-DD')" : 'DATE(t.ctime)'; // TODO: make work on other databases?
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663

    $daterange = get_record_sql(
        "SELECT
            MIN($day) AS mindate,
            MAX($day) AS maxdate
        FROM (
            SELECT ctime
            FROM {site_data}
            WHERE type = ?
            ORDER BY ctime DESC
            LIMIT $limit
            OFFSET $offset
        ) t",
        array('user-count-daily')
    );

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

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

    $userdata = get_records_sql_array(
Francois Marier's avatar
Francois Marier committed
667
        "SELECT ctime, type, \"value\", $day AS date
668
        FROM {site_data}
Richard Mansfield's avatar
Richard Mansfield committed
669
        WHERE type IN (?,?) AND ctime >= ? AND ctime < (date(?) + INTERVAL $dayinterval)
670
671
672
673
674
        ORDER BY type = ? DESC, ctime DESC",
        array('user-count-daily', 'loggedin-users-daily', $daterange->mindate, $daterange->maxdate, 'user-count-daily')
    );

    $userscreated = get_records_sql_array(
675
        "SELECT $day AS cdate, COUNT(id) AS users
676
        FROM {usr}
677
678
679
        WHERE NOT ctime IS NULL AND ctime >= ? AND ctime < (date(?) + INTERVAL $dayinterval)
        GROUP BY cdate",
        array($daterange->mindate, $daterange->maxdate)
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
    );

    $data = array();

    if ($userdata) {
        foreach ($userdata as &$r) {
            if ($r->type == 'user-count-daily') {
                $data[$r->date] = array(
                    'date'  => $r->date,
                    'total' => $r->value,
                );
            }
            else if ($r->type == 'loggedin-users-daily' && isset($data[$r->date])) {
                $data[$r->date]['loggedin'] = $r->value;
            }
        }
        if ($userscreated) {
            foreach ($userscreated as &$r) {
698
699
                if (isset($data[$r->cdate])) {
                    $data[$r->cdate]['created'] = $r->users;
700
701
702
703
704
                }
            }
        }
    }

705
    $csvfields = array('date', 'loggedin', 'created', 'total');
Hugh Davenport's avatar
Hugh Davenport committed
706
    $USER->set_download_file(generate_csv($data, $csvfields), 'userstatistics.csv', 'text/csv');
707
708
    $result['csv'] = true;

709
710
711
712
713
714
715
    $smarty = smarty_core();
    $smarty->assign('data', $data);
    $result['tablerows'] = $smarty->fetch('admin/userstats.tpl');

    return $result;
}

716
function institution_user_statistics($limit, $offset, &$institutiondata) {
717

718
    $data = array();
719
    $data['institution'] = $institutiondata['institution'];
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
    $data['tableheadings'] = array(
        array('name' => get_string('date')),
        array('name' => get_string('Loggedin', 'admin'), 'class' => 'center'),
        array('name' => get_string('Joined', 'group'), 'class' => 'center'),
        array('name' => get_string('Total'), 'class' => 'center'),
    );
    $data['table'] = institution_user_stats_table($limit, $offset, $institutiondata);
    $data['tabletitle'] = get_string('userstatstabletitle', 'admin');

    if (!$institutiondata['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);
737
        $data['summary'] = $smarty->fetch('admin/institutionuserstatssummary.tpl');
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

        return $data;
    }

    $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 (" . join(',', array_fill(0, $institutiondata['users'], '?')) . ")
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
        ORDER BY friends DESC
        LIMIT 1", $institutiondata['members']);
    $maxfriends = $maxfriends[0];
    $meanfriends = count_records_sql('SELECT COUNT(*) FROM
                (SELECT * FROM {usr_friend}
                    WHERE usr1 IN (' . join(',', array_fill(0, $institutiondata['users'], '?')) . ')
                UNION ALL SELECT * FROM {usr_friend}
                    WHERE usr2 IN (' . join(',', array_fill(0, $institutiondata['users'], '?')) . ')
                ) tmp', array_merge($institutiondata['members'], $institutiondata['members'])) / $institutiondata['users'];
    if ($maxfriends) {
        $data['strmaxfriends'] = get_string(
765
            'statsmaxfriends1',
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
            'admin',
            round($meanfriends, 1),
            profile_url($maxfriends),
            hsc(display_name($maxfriends, null, true)),
            $maxfriends->friends
        );
    }
    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 (" . join(',', array_fill(0, $institutiondata['users'], '?')) . ")
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
        ORDER BY views DESC
        LIMIT 1", $institutiondata['members']);
    $maxviews = $maxviews[0];
    if ($maxviews) {
        $data['strmaxviews'] = get_string(
786
            'statsmaxviews1',
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
            'admin',
            $institutiondata['viewsperuser'],
            profile_url($maxviews),
            hsc(display_name($maxviews, null, true)),
            $maxviews->views
        );
    }
    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 (" . join(',', array_fill(0, $institutiondata['users'], '?')) . ")
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname, u.urlid
        ORDER BY groups DESC
        LIMIT 1", $institutiondata['members']);
    $maxgroups = $maxgroups[0];
    if ($maxgroups) {
        $data['strmaxgroups'] = get_string(
807
            'statsmaxgroups1',
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
            'admin',
            $institutiondata['groupmemberaverage'],
            profile_url($maxgroups),
            hsc(display_name($maxgroups, null, true)),
            $maxgroups->groups
        );
    }
    else {
        $data['strmaxgroups'] = get_string('statsnogroups', 'admin');
    }
    $maxquotaused = get_records_sql_array("
        SELECT id, firstname, lastname, preferredname, urlid, quotaused
        FROM {usr}
        WHERE id IN (" . join(',', array_fill(0, $institutiondata['users'], '?')) . ")
        ORDER BY quotaused DESC
        LIMIT 1", $institutiondata['members']);
    $maxquotaused = $maxquotaused[0];
    $avgquota = get_field_sql("
        SELECT AVG(quotaused)
        FROM {usr}
        WHERE id IN (" . join(',', array_fill(0, $institutiondata['users'], '?')) . ")
        ", $institutiondata['members']);
    $data['strmaxquotaused'] = get_string(
831
        'statsmaxquotaused1',
832
833
834
835
836
837
838
839
840
        'admin',
        display_size($avgquota),
        profile_url($maxquotaused),
        hsc(display_name($maxquotaused, null, true)),
        display_size($maxquotaused->quotaused)
    );

    $smarty = smarty_core();
    $smarty->assign('data', $data);
841
    $data['summary'] = $smarty->fetch('admin/institutionuserstatssummary.tpl');
842
843
844
845
846

    return $data;
}

function institution_user_stats_table($limit, $offset, &$institutiondata) {
847
848
    global $USER;

849
850
851
852
853
854
855
856
857
858
859
    $count = count_records('institution_data', 'type', 'user-count-daily', 'institution', $institutiondata['name']);

    $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,
        'extradata' => array('institution' => $institutiondata['name']),
860
        'setlimit' => true,
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
    ));

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

    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?

    $daterange = get_record_sql(
        "SELECT
            MIN($day) AS mindate,
            MAX($day) AS maxdate
        FROM (
            SELECT ctime
            FROM {institution_data}
            WHERE type = ? AND institution = ?
            ORDER BY ctime DESC
            LIMIT $limit
            OFFSET $offset
        ) t",
        array('user-count-daily', $institutiondata['name'])
    );

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

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

    $userdata = get_records_sql_array(
        "SELECT ctime, type, \"value\", $day AS date
        FROM {institution_data}
        WHERE type IN (?,?) AND institution = ? AND ctime >= ? AND ctime < (date(?) + INTERVAL $dayinterval)
        ORDER BY type = ? DESC, ctime DESC",
        array('user-count-daily', 'loggedin-users-daily', $institutiondata['name'], $daterange->mindate, $daterange->maxdate, 'user-count-daily')
    );

    $userscreated = get_records_sql_array(
        "SELECT $day as cdate, COUNT(usr) AS users
        FROM {usr_institution}
        WHERE institution = ?
        AND NOT ctime IS NULL AND ctime >= ? AND ctime < (date(?) + INTERVAL $dayinterval)
        GROUP BY cdate",
        array($institutiondata['name'], $daterange->mindate, $daterange->maxdate)
    );

    $data = array();

    if ($userdata) {
        foreach ($userdata as &$r) {
            if ($r->type == 'user-count-daily') {
                $data[$r->date] = array(
                    'date'  => $r->date,
                    'total' => $r->value,
                );
            }
            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;
                }
            }
        }
    }

935
    $csvfields = array('date', 'loggedin', 'created', 'total');
Hugh Davenport's avatar
Hugh Davenport committed
936
    $USER->set_download_file(generate_csv($data, $csvfields), 'userstatistics.csv', 'text/csv');
937
938
    $result['csv'] = true;

939
940
941
942
943
944
945
    $smarty = smarty_core();
    $smarty->assign('data', $data);
    $result['tablerows'] = $smarty->fetch('admin/userstats.tpl');

    return $result;
}

946

947
function user_institution_graph($type = null) {
948
949
950
951
952
953
954
    // Draw a bar graph showing the number of users in each institution
    require_once(get_config('libroot') . 'institution.php');

    $institutions = Institution::count_members(false, true);
    if (count($institutions) > 1) {
        $dataarray = array();
        foreach ($institutions as &$i) {
955
            $dataarray[$i->displayname][get_string('institution')] = $i->members;
956
957
        }
        arsort($dataarray);
958
        // Truncate to avoid trying to fit too many results onto graph
959
        $dataarray = array_slice($dataarray, 0, 12, true);
960

961
962
963
964
965
966
        $data['graph'] = ($type) ? $type : 'bar';
        $data['graph_function_name'] = 'user_institution_graph';
        $data['title'] = get_string('institutionmembers','admin');
        $data['labels'] = array_keys($dataarray[$i->displayname]);
        $data['data'] = $dataarray;
        return $data;
967
968
969
    }
}

Richard Mansfield's avatar
Richard Mansfield committed
970
971
972
function group_statistics($limit, $offset) {
    $data = array();
    $data['tableheadings'] = array(
973
974
975
        array('name' => '#'),
        array('name' => get_string('Group', 'group')),
        array('name' => get_string('Members', 'group'), 'class' => 'center'),
Sean Brennan's avatar
Sean Brennan committed
976
        array('name' => get_string('Views', 'view'), 'class' => 'center'),
977
978
        array('name' => get_string('nameplural', 'interaction.forum'), 'class' => 'center'),
        array('name' => get_string('Posts', 'interaction.forum'), 'class' => 'center'),
Richard Mansfield's avatar
Richard Mansfield committed
979
980
    );
    $data['table'] = group_stats_table($limit, $offset);
981
    $data['tabletitle'] = get_string('groupstatstabletitle', 'admin');
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997

    $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()
    ));
998
    $smarty->assign('groupgraph', true);
999

1000
1001
    $data['summary'] = $smarty->fetch('admin/groupstatssummary.tpl');

Richard Mansfield's avatar
Richard Mansfield committed
1002
1003
1004
1005
    return $data;
}

function group_stats_table($limit, $offset) {
1006
1007
    global $USER;

Richard Mansfield's avatar
Richard Mansfield committed
1008
1009
1010
1011
1012
    $count = count_records('group', 'deleted', 0);

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => get_config('wwwroot') . 'admin/statistics.php?type=groups',
1013
1014
        'jsonscript' => 'admin/statistics.json.php',
        'datatable' => 'statistics_table',
Richard Mansfield's avatar
Richard Mansfield committed
1015
1016
1017
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
1018
        'setlimit' => true,
Richard Mansfield's avatar
Richard Mansfield committed
1019
1020
1021
    ));

    $result = array(
1022
        'count'         => $count,
Richard Mansfield's avatar
Richard Mansfield committed
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

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

    $groupdata = get_records_sql_array(
        "SELECT
1034
            g.id, g.name, g.urlid, mc.members, vc.views, fc.forums, pc.posts
Richard Mansfield's avatar
Richard Mansfield committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
        FROM {group} g
            LEFT JOIN (
                SELECT gm.group, COUNT(gm.member) AS members
                FROM {group_member} gm
                GROUP BY gm.group
            ) mc ON g.id = mc.group
            LEFT JOIN (
                SELECT v.group, COUNT(v.id) AS views
                FROM {view} v
                WHERE NOT v.group IS NULL
                GROUP BY v.group
            ) vc ON g.id = vc.group
            LEFT JOIN (
                SELECT ii.group, COUNT(ii.id) AS forums
                FROM {interaction_instance} ii
                WHERE ii.plugin = 'forum' AND ii.deleted = 0
                GROUP BY ii.group
            ) fc ON g.id = fc.group
            LEFT JOIN (
                SELECT ii.group, COUNT(ifp.id) AS posts
                FROM {interaction_instance} ii
                    INNER JOIN {interaction_forum_topic} ift ON ii.id = ift.forum
                    INNER JOIN {interaction_forum_post} ifp ON ift.id = ifp.topic
                WHERE ii.deleted = 0 AND ift.deleted = 0 AND ifp.deleted = 0
                GROUP BY ii.group
            ) pc ON g.id = pc.group
        WHERE
            g.deleted = 0
        ORDER BY
1064
            mc.members IS NULL, mc.members DESC, g.name, g.id",
Richard Mansfield's avatar
Richard Mansfield committed
1065
1066
1067
1068
1069
        array(),
        $offset,
        $limit
    );

1070
    $csvfields = array('id', 'name', 'members', 'views', 'forums', 'posts');
Hugh Davenport's avatar
Hugh Davenport committed
1071
    $USER->set_download_file(generate_csv($groupdata, $csvfields), 'groupstatistics.csv', 'text/csv');
1072
1073
    $result['csv'] = true;

1074
1075
    require_once('group.php');

Richard Mansfield's avatar
Richard Mansfield committed
1076
1077
1078
1079
1080
1081
1082
1083
    $smarty = smarty_core();
    $smarty->assign('data', $groupdata);
    $smarty->assign('offset', $offset);
    $result['tablerows'] = $smarty->fetch('admin/groupstats.tpl');

    return $result;
}

1084
function group_type_graph($type = false) {
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
    $grouptypes = get_records_sql_array("
        SELECT grouptype, jointype, COUNT(id) AS groups
        FROM {group}
        WHERE deleted = 0
        GROUP BY grouptype, jointype
        ORDER BY groups DESC", array()
    );

    if (count($grouptypes) > 1) {
        $dataarray = array();
        foreach ($grouptypes as &$t) {
            $strtype = get_string('name', 'grouptype.' . $t->grouptype);
1097
1098
            $strtype .= ' (' . get_string('membershiptype.abbrev.' . $t->jointype, 'group') . ')';
            $dataarray[$strtype] = $t->groups;
1099
        }
1100
        ksort($dataarray);
1101
        arsort($dataarray);
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
        $data['graph'] = ($type) ? $type : 'pie';
        $data['graph_function_name'] = 'group_type_graph';
        $data['title'] = get_string('grouptypes','statistics');
        $data['labels'] = array_keys($dataarray);
        $data['data'] = $dataarray;
        require_once(get_config('libroot') . 'graph.php');
        $graphdata = get_circular_graph_json($data);

        $dbdata['type'] = 'group-type-graph';
        $dbwhere['type'] = 'group-type-graph';
        $dbdata['value'] = json_encode($graphdata);
        $dbdata['ctime'] = db_format_timestamp(time());
        ensure_record_exists('site_data', (object)$dbwhere, (object)$dbdata);
1115
1116
1117
    }
}

1118
1119
1120
1121
1122
1123
function group_type_graph_render($type = null) {
    $data['graph'] = ($type) ? $type : 'pie';
    $data['jsondata'] = get_field('site_data','value','type','group-type-graph');
    return $data;
}

Richard Mansfield's avatar
Richard Mansfield committed
1124
1125
1126
function view_statistics($limit, $offset) {
    $data = array();
    $data['tableheadings'] = array(
1127
1128
1129
1130
1131
        array('name' => '#'),
        array('name' => get_string('view')),
        array('name' => get_string('Owner', 'view')),
        array('name' => get_string('Visits'), 'class' => 'center'),
        array('name' => get_string('Comments', 'artefact.comment'), 'class' => 'center'),
Richard Mansfield's avatar
Richard Mansfield committed
1132
1133
    );
    $data['table'] = view_stats_table($limit, $offset);
1134
    $data['tabletitle'] = get_string('viewstatstabletitle', 'admin');
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150

    $smarty = smarty_core();
    $maxblocktypes = 5;
    $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')
        GROUP BY b.blocktype, langsection
        ORDER BY blocks DESC",
        array(), 0, $maxblocktypes
    ));
1151
    $smarty->assign('viewtypes', true);
1152
    $smarty->assign('viewcount', $data['table']['count']);
1153
1154
    $data['summary'] = $smarty->fetch('admin/viewstatssummary.tpl');

Richard Mansfield's avatar
Richard Mansfield committed
1155
1156
1157
1158
    return $data;
}

function view_stats_table($limit, $offset) {
1159
1160
    global $USER;

1161
    $count = count_records_select('view', '(owner != 0 OR owner IS NULL) AND type != ?', array('dashboard'));
Richard Mansfield's avatar
Richard Mansfield committed
1162
1163
1164
1165
1166
1167
1168
1169
1170

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => get_config('wwwroot') . 'admin/statistics.php?type=views',
        'jsonscript' => 'admin/statistics.json.php',
        'datatable' => 'statistics_table',
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
1171
        'setlimit' => true,
Richard Mansfield's avatar
Richard Mansfield committed
1172
1173
1174
    ));

    $result = array(
1175
        'count'         => $count,
Richard Mansfield's avatar
Richard Mansfield committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

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

1185
    $viewdata = get_records_sql_assoc(
Richard Mansfield's avatar
Richard Mansfield committed
1186
        "SELECT
1187
            v.id, v.title, v.owner, v.group, v.institution, v.visits, v.type, v.ownerformat, v.urlid
Richard Mansfield's avatar
Richard Mansfield committed
1188
        FROM {view} v
1189
        WHERE (v.owner != 0 OR \"owner\" IS NULL) AND v.type != ?
1190
        ORDER BY v.visits DESC, v.title, v.id",
1191
        array('dashboard'),
Richard Mansfield's avatar
Richard Mansfield committed
1192
1193
1194
1195
        $offset,
        $limit
    );

1196
1197
1198
1199
    require_once('view.php');
    require_once('group.php');
    View::get_extra_view_info($viewdata, false, false);

1200
1201
1202
    safe_require('artefact', 'comment');
    $comments = ArtefactTypeComment::count_comments(array_keys($viewdata));

Richard Mansfield's avatar
Richard Mansfield committed
1203
    foreach ($viewdata as &$v) {
1204
        $v = (object) $v;
1205
        if ($v->owner) {
1206
1207
            $v->ownername = display_name($v->user);
            $v->ownerurl  = profile_url($v->user);
1208
        }
1209
1210
1211
1212
1213
1214
1215
1216
        else {
            $v->ownername = $v->sharedby;
            if ($v->group) {
                $v->ownerurl = group_homepage_url($v->groupdata);
            }
            else if ($v->institution && $v->institution != 'mahara') {
                $v->ownerurl = get_config('wwwroot') . 'institution/index.php?institution=' . $v->institution;
            }
1217
        }
1218
        $v->comments = isset($comments[$v->id]) ? (int) $comments[$v->id]->comments : 0;
Richard Mansfield's avatar
Richard Mansfield committed
1219
1220
    }

1221
    $csvfields = array('title', 'displaytitle', 'fullurl', 'owner', 'group', 'institution', 'ownername', 'ownerurl', 'visits', 'type', 'comments');
Hugh Davenport's avatar
Hugh Davenport committed
1222
    $USER->set_download_file(generate_csv($viewdata, $csvfields), 'viewstatistics.csv', 'text/csv');
1223
1224
    $result['csv'] = true;

Richard Mansfield's avatar
Richard Mansfield committed
1225
1226
1227
1228
1229
1230
1231
1232
    $smarty = smarty_core();
    $smarty->assign('data', $viewdata);
    $smarty->assign('offset', $offset);
    $result['tablerows'] = $smarty->fetch('admin/viewstats.tpl');

    return $result;
}

1233
function view_type_graph($type = null) {
1234
1235
1236
    // Draw a pie graph of views broken down by view type.
    $viewtypes = get_records_sql_array('
        SELECT type, COUNT(id) AS views
1237
        FROM {view} WHERE type != ?
1238
        GROUP BY type',
1239
        array('dashboard')
1240
1241
1242
1243
1244
1245
1246
1247
1248
    );

    if (count($viewtypes) > 1) {
        $dataarray = array();
        foreach ($viewtypes as &$t) {
            $dataarray[get_string($t->type, 'view')] = $t->views;
        }
        arsort($dataarray);

1249
1250
1251
1252
1253
1254
1255
        $data['graph'] = ($type) ? $type : 'pie';
        $data['graph_function_name'] = 'view_type_graph';
        $data['title'] = get_string('viewsbytype', 'admin');
        $data['labels'] = array_keys($dataarray);
        $data['data'] = $dataarray;
        require_once(get_config('libroot') . 'graph.php');
        $graphdata = get_circular_graph_json($data);
1256

1257
1258
1259
1260
1261
        $dbdata['type'] = 'view-type-graph';
        $dbwhere['type'] = 'view-type-graph';
        $dbdata['value'] = json_encode($graphdata);
        $dbdata['ctime'] = db_format_timestamp(time());
        ensure_record_exists('site_data', (object)$dbwhere, (object)$dbdata);
1262
1263
1264
    }
}

1265
1266
1267
1268
1269
1270
function view_type_graph_render($type = null) {
    $data['graph'] = ($type) ? $type : 'pie';
    $data['jsondata'] = get_field('site_data','value','type','view-type-graph');
    return $data;
}

1271
1272
1273
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
function institution_view_statistics($limit, $offset, &$institutiondata) {
    $data = array();
    $data['tableheadings'] = array(
        array('name' => '#'),
        array('name' => get_string('view')),
        array('name' => get_string('Owner', 'view')),
        array('name' => get_string('Visits'), 'class' => 'center'),
        array('name' => get_string('Comments', 'artefact.comment'), 'class' => 'center'),
    );
    $data['table'] = institution_view_stats_table($limit, $offset, $institutiondata);
    $data['tabletitle'] = get_string('viewstatstabletitle', 'admin');

    $smarty = smarty_core();
    $maxblocktypes = 5;
    if ($institutiondata['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 (" . join(',', array_fill(0, $institutiondata['views'], '?')) . ")
            GROUP BY b.blocktype, langsection
            ORDER BY blocks DESC",
            $institutiondata['viewids'], 0, $maxblocktypes
        ));
    }