registration.php 82.4 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
14
15
16
17
18
19
20
21
22
23
 * @file Register a mahara site
 */
/**
 * @defgroup Registration Registration
 * Send site information to mahara.org
 * 
 */
 
defined('INTERNAL') || die();

/**
 * @return string that is the registation form
 * @ingroup Registration 
 */
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
<tr><td>
28
29
<table>
    <tr>
Nigel McNie's avatar
Nigel McNie committed
30
31
        <th>$strfield</th>
        <th>$strvalue</th>
32
33
34
35
36
37
    </tr>
EOF;
    $data = registration_data();
    foreach($data as $key => $val) {
        $info .= '<tr><td>'. hsc($key) . '</td><td>' . hsc($val) . "</td></tr>\n";
    }
38
    $info .= '</table></td></tr>';
39

40
41
42
43
44
45
    $form = array(
        'name' => 'register',
        'autofocus' => false,
        'elements' => array(
            'whatsent' => array(
                'type' => 'fieldset',
Nigel McNie's avatar
Nigel McNie committed
46
                'legend' => get_string('datathatwillbesent', 'admin'),
47
48
49
50
51
                'collapsible' => true,
                'collapsed' => true,
                'elements' => array(
                    'info' => array(
                        'type' => 'markup',
Nigel McNie's avatar
Nigel McNie committed
52
                        'value'=> $info,
53
54
55
56
57
                    ),
                )
            ),
            'sendweeklyupdates' => array(
                'type' => 'checkbox',
Nigel McNie's avatar
Nigel McNie committed
58
59
                'title' => get_string('sendweeklyupdates', 'admin'),
                'defaultvalue' => true,
60
61
62
            ),
            'register' => array(
                'type' => 'submit',
Nigel McNie's avatar
Nigel McNie committed
63
                'value' => get_string('Register', 'admin'),
64
65
66
            ),
        )
     );
67
68
69
70
71
72
     
     return pieform($form);
}
/**
 * Runs when registration form is submitted
 */
73
74
75
function register_submit(Pieform $form, $values) {
    global $SESSION;

76
    $result = registration_send_data();
77
    $data = json_decode($result->data);
78

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

91
92
93
94
95

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

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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();
}
121

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

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    // 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) . ';';

163
164
165
166
167
168
169
170
171
172
    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);
    }
173

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

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
    // 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;
        }
    }
200

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

208
209
    $data_to_send['newstats'] = 1;

210
    return $data_to_send;
211
}
212

213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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();
}

232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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);
309
310
311
312
313
314
315
316
317
318
319
320
        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)) {
321
            $inst_data['usersloggedin'] = isset($data->sum) ? $data->sum : 0;
322
323
324
325
        }
        else {
            $inst_data['usersloggedin'] = 0;
        }
326
327
328
329
330
331

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

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

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

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

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

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

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

399
    return($data);
400
401
}

402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
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;
}

435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
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);
}

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

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

608
    $data['institutions'] = stats_graph_url('institutions');
609

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

614
615
616
617
    return $data;
}

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

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

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

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

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

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

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

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

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

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

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

    return $result;
}

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
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(
            'statsmaxfriends',
            '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(
            'statsmaxviews',
            '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(
            'statsmaxgroups',
            '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(
        'statsmaxquotaused',
        '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) {
844
845
    global $USER;

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

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

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

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

    return $result;
}

943
944
945
946
947
948
949
950
951
952
953
954

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);
955
956
        // Truncate to avoid overlapping labels
        $dataarray = array_slice($dataarray, 0, 25, true);
957
958
959

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

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

        $Graph->add(
            Image_Graph::vertical(
967
968
969
970
971
972
973
                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
974
975
976
            )
        );

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

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

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

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

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

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

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

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

Richard Mansfield's avatar
Richard Mansfield committed
1037
1038
1039
1040
    return $data;
}

function group_stats_table($limit, $offset) {
1041
1042
    global $USER;

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

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

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

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

    $groupdata = get_records_sql_array(
        "SELECT
1069
            g.id, g.name, g.urlid, mc.members, vc.views, fc.forums, pc.posts
Richard Mansfield's avatar
Richard Mansfield committed
1070
1071
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
        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
1099
            mc.members IS NULL, mc.members DESC, g.name, g.id",
Richard Mansfield's avatar
Richard Mansfield committed
1100
1101
1102
1103
1104
        array(),
        $offset,
        $limit
    );

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

1109
1110
    require_once('group.php');

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

    return $result;
}

1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
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);
1132
1133
            $strtype .= ' (' . get_string('membershiptype.abbrev.' . $t->jointype, 'group') . ')';
            $dataarray[$strtype] = $t->groups;
1134
        }
1135
        ksort($dataarray);
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
        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(
1146
1147
1148
1149
1150
1151
1152
1153
            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
1154
            )
1155
1156
        );

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

1162
1163
        $Legend->setPlotArea($Plotarea);
        $Legend->setFontSize(6);
1164
        $Plotarea->hideAxis();
1165

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

        $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');
1178
        $FillArray->addColor('black@0.6');
1179

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

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

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

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

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

Richard Mansfield's avatar
Richard Mansfield committed
1222
1223
1224
1225
    return $data;
}

function view_stats_table($limit, $offset) {
1226
1227
    global $USER;

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

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

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

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

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

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

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

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

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

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

    return $result;
}

1300
1301
1302
1303
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
1304
        FROM {view} WHERE type != ?
1305
        GROUP BY type',
1306
        array('dashboard')
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
    );

    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(
1325
1326
1327
1328
1329
1330
1331
                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
1332
1333
1334
            )
        );

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

1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
        $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);

1361
        $Graph->done(array('filename' => stats_graph_path('viewtypes')));
1362
1363
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
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
        ));
    }
    $smarty->assign('viewtypes', stats_graph_url($institutiondata['name'] . '_viewtypes'));
    $smarty->assign('viewcount', $data['table']['count']);
    $data['summary'] = $smarty->fetch('admin/viewstatssummary.tpl');

    return $data;
}

function institution_view_stats_table($limit, $offset, &$institutiondata) {
1403
1404
    global $USER;

1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
    if ($institutiondata['views'] != 0) {
        $count = count_records_select('view', 'id IN (' . join(',', array_fill(0, $institutiondata['views'], '?')) . ') AND type != ?',
                                        array_merge($institutiondata['viewids'], array('dashboard')));
    }
    else {
        $count = 0;
    }

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => get_config('wwwroot') . 'admin/users/statistics.php?institution=' . $institutiondata['name'] . '&type=views',
        'jsonscript' => 'admin/users/statistics.json.php',
        'datatable' => 'statistics_table',
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
        'extradata' => array('institution' => $institutiondata['name']),
1422
        'setlimit' => true,
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
    ));

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

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

    $viewdata = get_records_sql_assoc(
        "SELECT
            v.id, v.title, v.owner, v.group, v.institution, v.visits, v.type, v.ownerformat, v.urlid
        FROM {view} v
        WHERE v.id IN (" . join(',', array_fill(0, $institutiondata['views'], '?')) . ") AND v.type != ?
        ORDER BY v.visits DESC, v.title, v.id",
        array_merge($institutiondata['viewids'], array('dashboard')),
        $offset,
        $limit
    );

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

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

    foreach ($viewdata as &$v) {
        $v = (object) $v;
        if ($v->owner) {
            $v->ownername = display_name($v->user);
            $v->ownerurl  = profile_url($v->user);
        }
        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;
            }
        }
        $v->comments = isset($comments[$v->id]) ? (int) $comments[$v->id]->comments : 0;
    }

1472
    $csvfields = array('title', 'displaytitle', 'fullurl', 'owner', 'group', 'institution', 'ownername', 'ownerurl', 'visits', 'type', 'comments');
Hugh Davenport's avatar
Hugh Davenport committed
1473
    $USER->set_download_file(generate_csv($viewdata, $csvfields), 'viewstatistics.csv', 'text/csv');