registration.php 82.9 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 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
function institution_registration_data() {
    $data_to_store = array();
    foreach (get_column('institution', 'name') as $institution) {
        $inst_data = array();
        if ($institution == 'mahara') {
            $members = get_column_sql('SELECT id
                    FROM {usr}
                    WHERE deleted = 0 AND id > 0 AND id NOT IN
                        (SELECT usr FROM {usr_institution})
                    ', array());
        }
        else {
            $members = get_column_sql('SELECT usr
                    FROM {usr_institution} ui
                    JOIN {usr} u ON (u.id = ui.usr)
                    WHERE u.deleted = 0 AND ui.institution = ?
                    ', array($institution));
        }
        $inst_data['count_members'] =  count($members);
        if (!$members) {
            $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
                    WHERE v.owner IS NOT NULL AND v.owner IN (' . join(',', array_fill(0, count($members), '?')) . ')
                    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
                ) tmp GROUP BY tmp.type', array_merge($members, array($institution)))) {
            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
                    WHERE v.owner IS NOT NULL AND v.owner IN (' . join(',', array_fill(0, count($members), '?')) . ')
                    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
                ) tmp GROUP BY tmp.type', array_merge($members, array($institution)))) {
            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
                WHERE a.author IN (' . join(',', array_fill(0, count($members), '?')) . ')
                GROUP BY a.artefacttype', $members)) {
            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',
                'poster IN (' . join(',', array_fill(0, count($members), '?')) . ')',
                $members);
312
313
314
315
316
317
318
319
320
321
322
323
        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
                WHERE u.id IN (' . join(',', array_fill(0, count($members), '?')) . ')',
                $members)) {
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'] = stats_graph_url('weekly');
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');
Richard Mansfield's avatar
Richard Mansfield committed
389

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

401
    return($data);
402
403
}

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

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

    if ($full) {
        $data = institution_data_current($institution);
        $data['weekly'] = stats_graph_url($institution . '_weekly');

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

513
function user_statistics($limit, $offset, &$sitedata) {
514
515
    $data = array();
    $data['tableheadings'] = array(
516
517
518
519
        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'),
520
521
    );
    $data['table'] = user_stats_table($limit, $offset);
522
523
    $data['tabletitle'] = get_string('userstatstabletitle', 'admin');

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

610
    $data['institutions'] = stats_graph_url('institutions');
611

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

616
617
618
619
    return $data;
}

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

622
623
624
625
626
    $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',
627
628
        'jsonscript' => 'admin/statistics.json.php',
        'datatable' => 'statistics_table',
629
630
631
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
632
        'setlimit' => true,
633
634
635
    ));

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

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

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

    $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';

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

    $userdata = get_records_sql_array(
Francois Marier's avatar
Francois Marier committed
668
        "SELECT ctime, type, \"value\", $day AS date
669
        FROM {site_data}
Richard Mansfield's avatar
Richard Mansfield committed
670
        WHERE type IN (?,?) AND ctime >= ? AND ctime < (date(?) + INTERVAL $dayinterval)
671
672
673
674
675
        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(
676
        "SELECT $day AS cdate, COUNT(id) AS users
677
        FROM {usr}
678
679
680
        WHERE NOT ctime IS NULL AND ctime >= ? AND ctime < (date(?) + INTERVAL $dayinterval)
        GROUP BY cdate",
        array($daterange->mindate, $daterange->maxdate)
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
    );

    $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) {
699
700
                if (isset($data[$r->cdate])) {
                    $data[$r->cdate]['created'] = $r->users;
701
702
703
704
705
                }
            }
        }
    }

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

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

    return $result;
}

717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
function institution_user_statistics($limit, $offset, &$institutiondata) {
    $data = array();
    $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);
        $data['summary'] = $smarty->fetch('admin/userstatssummary.tpl');

        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(
764
            'statsmaxfriends1',
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
            '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(
785
            'statsmaxviews1',
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
            '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(
806
            'statsmaxgroups1',
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
            '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(
830
        'statsmaxquotaused1',
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
        '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['summary'] = $smarty->fetch('admin/userstatssummary.tpl');

    return $data;
}

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

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

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

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

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

    return $result;
}

945
946
947
948
949
950
951
952
953
954
955
956

function user_institution_graph() {
    // 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) {
            $dataarray[$i->displayname] = $i->members;
        }
        arsort($dataarray);
957
958
        // Truncate to avoid overlapping labels
        $dataarray = array_slice($dataarray, 0, 25, true);
959
960
961

        require_once(get_config('libroot') . "pear/Image/Graph.php");

962
        $Graph =& Image_Graph::factory('graph', array(300, 300));
963
964
965
966
967
968
        $Font =& $Graph->addNew('font', 'Vera');
        $Font->setSize(9);
        $Graph->setFont($Font);

        $Graph->add(
            Image_Graph::vertical(
969
970
971
972
973
974
975
                Image_Graph::vertical(
                    Image_Graph::factory('title', array(get_string('institutionmembers', 'admin'), 9)),
                    $Plotarea = Image_Graph::factory('plotarea'),
                    5
                ),
                $Date = Image_Graph::factory('title', array(format_date(time(), 'strftimew3cdate'), 7)),
                96
976
977
978
            )
        );

979
980
981
982
983
        $Date->setAlignment(IMAGE_GRAPH_ALIGN_RIGHT);
        $DateFont =& $Graph->addNew('font', 'Vera');
        $DateFont->setColor('gray@0.8');
        $Date->setFont($DateFont);

984
985
986
        $Dataset =& Image_Graph::factory('dataset', array($dataarray));
        $Plot =& $Plotarea->addNew('bar', array(&$Dataset));
        $Plot->setLineColor('gray');
987
        $Plot->setSpacing(2);
988
989
990
991
992
993
994
995
996

        $FillArray =& Image_Graph::factory('Image_Graph_Fill_Array');
        $Plot->setFillStyle($FillArray);
        $FillArray->addColor('blue@0.6');
        $FillArray->addColor('green@0.6');
        $FillArray->addColor('red@0.6');
        $FillArray->addColor('yellow@0.6');
        $FillArray->addColor('orange@0.6');

997
998
999
1000
1001
1002
        $AxisX =& $Plotarea->getAxis(IMAGE_GRAPH_AXIS_X);
        if (count($dataarray) > 4) {
            $AxisX->setFontAngle('vertical');
        }
        $AxisX->setFontSize(8);

1003
        $Graph->done(array('filename' => stats_graph_path('institutions')));
1004
1005
1006
    }
}

Richard Mansfield's avatar
Richard Mansfield committed
1007
1008
1009
function group_statistics($limit, $offset) {
    $data = array();
    $data['tableheadings'] = array(
1010
1011
1012
        array('name' => '#'),
        array('name' => get_string('Group', 'group')),
        array('name' => get_string('Members', 'group'), 'class' => 'center'),
Sean Brennan's avatar
Sean Brennan committed
1013
        array('name' => get_string('Views', 'view'), 'class' => 'center'),
1014
1015
        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
1016
1017
    );
    $data['table'] = group_stats_table($limit, $offset);
1018
    $data['tabletitle'] = get_string('groupstatstabletitle', 'admin');
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034

    $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()
    ));
1035
    $smarty->assign('groupgraph', stats_graph_url('grouptypes'));
1036

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

Richard Mansfield's avatar
Richard Mansfield committed
1039
1040
1041
1042
    return $data;
}

function group_stats_table($limit, $offset) {
1043
1044
    global $USER;

Richard Mansfield's avatar
Richard Mansfield committed
1045
1046
1047
1048
1049
    $count = count_records('group', 'deleted', 0);

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => get_config('wwwroot') . 'admin/statistics.php?type=groups',
1050
1051
        'jsonscript' => 'admin/statistics.json.php',
        'datatable' => 'statistics_table',
Richard Mansfield's avatar
Richard Mansfield committed
1052
1053
1054
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
1055
        'setlimit' => true,
Richard Mansfield's avatar
Richard Mansfield committed
1056
1057
1058
    ));

    $result = array(
1059
        'count'         => $count,
Richard Mansfield's avatar
Richard Mansfield committed
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

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

    $groupdata = get_records_sql_array(
        "SELECT
1071
            g.id, g.name, g.urlid, mc.members, vc.views, fc.forums, pc.posts
Richard Mansfield's avatar
Richard Mansfield committed
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
        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
1101
            mc.members IS NULL, mc.members DESC, g.name, g.id",
Richard Mansfield's avatar
Richard Mansfield committed
1102
1103
1104
1105
1106
        array(),
        $offset,
        $limit
    );

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

1111
1112
    require_once('group.php');

Richard Mansfield's avatar
Richard Mansfield committed
1113
1114
1115
1116
1117
1118
1119
1120
    $smarty = smarty_core();
    $smarty->assign('data', $groupdata);
    $smarty->assign('offset', $offset);
    $result['tablerows'] = $smarty->fetch('admin/groupstats.tpl');

    return $result;
}

1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
function group_type_graph() {
    $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);
1134
1135
            $strtype .= ' (' . get_string('membershiptype.abbrev.' . $t->jointype, 'group') . ')';
            $dataarray[$strtype] = $t->groups;
1136
        }
1137
        ksort($dataarray);
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
        arsort($dataarray);

        require_once(get_config('libroot') . "pear/Image/Graph.php");

        $Graph =& Image_Graph::factory('graph', array(300, 200));
        $Font =& $Graph->addNew('font', 'Vera');
        $Font->setSize(9);
        $Graph->setFont($Font);

        $Graph->add(
1148
1149
1150
1151
1152
1153
1154
1155
            Image_Graph::vertical(
                Image_Graph::horizontal(
                    $Plotarea = Image_Graph::factory('plotarea'),
                    $Legend = Image_Graph::factory('legend'),
                    60
                ),
                $Date = Image_Graph::factory('title', array(format_date(time(), 'strftimew3cdate'), 7)),
                96
1156
            )
1157
1158
        );

1159
1160
1161
1162
1163
        $Date->setAlignment(IMAGE_GRAPH_ALIGN_RIGHT);
        $DateFont =& $Graph->addNew('font', 'Vera');
        $DateFont->setColor('gray@0.8');
        $Date->setFont($DateFont);

1164
1165
        $Legend->setPlotArea($Plotarea);
        $Legend->setFontSize(6);
1166
        $Plotarea->hideAxis();
1167

1168
        $Dataset =& Image_Graph::factory('dataset', array($dataarray));
1169
        $Plot =& $Plotarea->addNew('pie', $Dataset);
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179

        $Plot->setLineColor('black');

        $FillArray =& Image_Graph::factory('Image_Graph_Fill_Array');
        $Plot->setFillStyle($FillArray);
        $FillArray->addColor('blue@0.6');
        $FillArray->addColor('green@0.6');
        $FillArray->addColor('red@0.6');
        $FillArray->addColor('yellow@0.6');
        $FillArray->addColor('orange@0.6');
1180
        $FillArray->addColor('black@0.6');
1181

1182
        $Marker =& $Plot->addNew('Image_Graph_Marker_Value', IMAGE_GRAPH_VALUE_Y);
1183
        $Marker->setBorderColor('white');
1184
        $Marker->setFontSize(7);
1185
1186
1187
1188

        $PointingMarker =& $Plot->addNew('Image_Graph_Marker_Pointing_Angular', array(20, &$Marker));
        $Plot->setMarker($PointingMarker);

1189
        $Graph->done(array('filename' => stats_graph_path('grouptypes')));
1190
1191
1192
    }
}

Richard Mansfield's avatar
Richard Mansfield committed
1193
1194
1195
function view_statistics($limit, $offset) {
    $data = array();
    $data['tableheadings'] = array(
1196
1197
1198
1199
1200
        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
1201
1202
    );
    $data['table'] = view_stats_table($limit, $offset);
1203
    $data['tabletitle'] = get_string('viewstatstabletitle', 'admin');
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219

    $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
    ));
1220
    $smarty->assign('viewtypes', stats_graph_url('viewtypes'));
1221
    $smarty->assign('viewcount', $data['table']['count']);
1222
1223
    $data['summary'] = $smarty->fetch('admin/viewstatssummary.tpl');

Richard Mansfield's avatar
Richard Mansfield committed
1224
1225
1226
1227
    return $data;
}

function view_stats_table($limit, $offset) {
1228
1229
    global $USER;

1230
    $count = count_records_select('view', '(owner != 0 OR owner IS NULL) AND type != ?', array('dashboard'));
Richard Mansfield's avatar
Richard Mansfield committed
1231
1232
1233
1234
1235
1236
1237
1238
1239

    $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,
1240
        'setlimit' => true,
Richard Mansfield's avatar
Richard Mansfield committed
1241
1242
1243
    ));

    $result = array(
1244
        'count'         => $count,
Richard Mansfield's avatar
Richard Mansfield committed
1245
1246
1247
1248
1249
1250
1251
1252
1253
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

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

1254
    $viewdata = get_records_sql_assoc(
Richard Mansfield's avatar
Richard Mansfield committed
1255
        "SELECT
1256
            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
1257
        FROM {view} v
1258
        WHERE (v.owner != 0 OR \"owner\" IS NULL) AND v.type != ?
1259
        ORDER BY v.visits DESC, v.title, v.id",
1260
        array('dashboard'),
Richard Mansfield's avatar
Richard Mansfield committed
1261
1262
1263
1264
        $offset,
        $limit
    );

1265
1266
1267
1268
    require_once('view.php');
    require_once('group.php');
    View::get_extra_view_info($viewdata, false, false);

1269
1270
1271
    safe_require('artefact', 'comment');
    $comments = ArtefactTypeComment::count_comments(array_keys($viewdata));

Richard Mansfield's avatar
Richard Mansfield committed
1272
    foreach ($viewdata as &$v) {
1273
        $v = (object) $v;
1274
        if ($v->owner) {
1275
1276
            $v->ownername = display_name($v->user);
            $v->ownerurl  = profile_url($v->user);
1277
        }
1278
1279
1280
1281
1282
1283
1284
1285
        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;
            }
1286
        }
1287
        $v->comments = isset($comments[$v->id]) ? (int) $comments[$v->id]->comments : 0;
Richard Mansfield's avatar
Richard Mansfield committed
1288
1289
    }

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

Richard Mansfield's avatar
Richard Mansfield committed
1294
1295
1296
1297
1298
1299
1300
1301
    $smarty = smarty_core();
    $smarty->assign('data', $viewdata);
    $smarty->assign('offset', $offset);
    $result['tablerows'] = $smarty->fetch('admin/viewstats.tpl');

    return $result;
}

1302
1303
1304
1305
function view_type_graph() {
    // Draw a pie graph of views broken down by view type.
    $viewtypes = get_records_sql_array('
        SELECT type, COUNT(id) AS views
1306
        FROM {view} WHERE type != ?
1307
        GROUP BY type',
1308
        array('dashboard')
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
    );

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

        require_once(get_config('libroot') . "pear/Image/Graph.php");

        $Graph =& Image_Graph::factory('graph', array(300, 200));
        $Font =& $Graph->addNew('font', 'Vera');
        $Font->setSize(9);
        $Graph->setFont($Font);

        $Graph->add(
            Image_Graph::vertical(
1327
1328
1329
1330
1331
1332
1333
                Image_Graph::vertical(
                    Image_Graph::factory('title', array(get_string('viewsbytype', 'admin'), 9)),
                    $Plotarea = Image_Graph::factory('plotarea'),
                    5
                ),
                $Date = Image_Graph::factory('title', array(format_date(time(), 'strftimew3cdate'), 7)),
                96
1334
1335
1336
            )
        );

1337
1338
1339
1340
1341
        $Date->setAlignment(IMAGE_GRAPH_ALIGN_RIGHT);
        $DateFont =& $Graph->addNew('font', 'Vera');
        $DateFont->setColor('gray@0.8');
        $Date->setFont($DateFont);

1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
        $Plotarea->hideAxis();
        $Dataset =& Image_Graph::factory('dataset', array($dataarray));
        $Plot =& $Plotarea->addNew('pie', array(&$Dataset));

        $Plot->setLineColor('black');

        $FillArray =& Image_Graph::factory('Image_Graph_Fill_Array');
        $Plot->setFillStyle($FillArray);
        $FillArray->addColor('blue@0.6');
        $FillArray->addColor('green@0.6');
        $FillArray->addColor('red@0.6');
        $FillArray->addColor('yellow@0.6');
        $FillArray->addColor('orange@0.6');

        $Marker =& $Plot->addNew('Image_Graph_Marker_Value', IMAGE_GRAPH_VALUE_X);
        $Marker->setBorderColor('white');
        $Marker->setFontSize(8);

        $PointingMarker =& $Plot->addNew('Image_Graph_Marker_Pointing_Angular', array(20, &$Marker));
        $Plot->setMarker($PointingMarker);

1363
        $Graph->done(array('filename' => stats_graph_path('viewtypes')));
1364
1365
1366
    }
}

1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
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_tabl