registration.php 32.3 KB
Newer Older
1
2
<?php
/**
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    mahara
 * @subpackage core
 * @author     Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 * @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
40
41
    $strfield = get_string('Field', 'admin');
    $strvalue = get_string('Value', 'admin');
42
    $info = <<<EOF
43
<tr><td>
44
45
<table>
    <tr>
Nigel McNie's avatar
Nigel McNie committed
46
47
        <th>$strfield</th>
        <th>$strvalue</th>
48
49
50
51
52
53
    </tr>
EOF;
    $data = registration_data();
    foreach($data as $key => $val) {
        $info .= '<tr><td>'. hsc($key) . '</td><td>' . hsc($val) . "</td></tr>\n";
    }
54
    $info .= '</table></td></tr>';
55

56
57
58
59
60
61
    $form = array(
        'name' => 'register',
        'autofocus' => false,
        'elements' => array(
            'whatsent' => array(
                'type' => 'fieldset',
Nigel McNie's avatar
Nigel McNie committed
62
                'legend' => get_string('datathatwillbesent', 'admin'),
63
64
65
66
67
                'collapsible' => true,
                'collapsed' => true,
                'elements' => array(
                    'info' => array(
                        'type' => 'markup',
Nigel McNie's avatar
Nigel McNie committed
68
                        'value'=> $info,
69
70
71
72
73
                    ),
                )
            ),
            'sendweeklyupdates' => array(
                'type' => 'checkbox',
Nigel McNie's avatar
Nigel McNie committed
74
75
                'title' => get_string('sendweeklyupdates', 'admin'),
                'defaultvalue' => true,
76
77
78
            ),
            'register' => array(
                'type' => 'submit',
Nigel McNie's avatar
Nigel McNie committed
79
                'value' => get_string('Register', 'admin'),
80
81
82
            ),
        )
     );
83
84
85
86
87
88
     
     return pieform($form);
}
/**
 * Runs when registration form is submitted
 */
89
90
91
function register_submit(Pieform $form, $values) {
    global $SESSION;

92
    $result = registration_send_data();
93
    $data = json_decode($result->data);
94

95
    if ($data->status != 1) {
Nigel McNie's avatar
Nigel McNie committed
96
97
        log_info($result);
        $SESSION->add_error_msg(get_string('registrationfailedtrylater', 'admin', $result->info['http_code']));
98
99
    }
    else {
100
        set_config('registration_lastsent', time());
101
        set_config('registration_sendweeklyupdates', $values['sendweeklyupdates']);
102
        $SESSION->add_ok_msg(get_string('registrationsuccessfulthanksforregistering', 'admin'));
103
104
    }
    redirect('/admin/');
105
106
}

107
108
109
110
111

/**
 * Worker - performs sending of registration data to mahara.org
 */
function registration_send_data() {
112
    $registrationurl = 'http://mahara.org/api/registration.php';
113
114
115
116
117
118
    $data = registration_data();
    $request = array(
        CURLOPT_URL        => $registrationurl,
        CURLOPT_POST       => 1,
        CURLOPT_POSTFIELDS => $data,
    );
119
    return mahara_http_request($request);
120
121
}

122

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

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

153
154
155
156
157
158
159
    foreach (array(
        'usr',
        'group',
        'host') as $key) {
        $data_to_send['count_' . $key] = count_records_select($key, 'deleted = 0');
        }

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    // 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;
        }
    }
179

180
181
    $data_to_send['newstats'] = 1;

182
    return $data_to_send;
183
}
184

185
function site_data_current() {
186
187
188
    return array(
        'users' => count_records_select('usr', 'id > 0 AND deleted = 0'),
        'groups' => count_records('group', 'deleted', 0),
189
        'views' => count_records_select('view', 'owner != 0 OR owner IS NULL'),
190
191
192
    );
}

193
function site_statistics($full=false) {
194
195
    $data = array();

196
197
    if ($full) {
        $data = site_data_current();
198
        $data['weekly'] = stats_graph_url('weekly');
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220

        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
        ");
221
        $data['groupmemberaverage'] = round($memberships/$data['users'], 1);
222
223
        $data['strgroupmemberaverage'] = get_string('groupmemberaverage', 'admin', $data['groupmemberaverage']);
        $data['viewsperuser'] = get_field_sql("
Francois Marier's avatar
Francois Marier committed
224
            SELECT (0.0 + COUNT(id)) / NULLIF(COUNT(DISTINCT \"owner\"), 0)
225
            FROM {view}
Francois Marier's avatar
Francois Marier committed
226
            WHERE NOT \"owner\" IS NULL AND \"owner\" > 0
227
        ");
228
        $data['viewsperuser'] = round($data['viewsperuser'], 1);
229
        $data['strviewsperuser'] = get_string('viewsperuser', 'admin', $data['viewsperuser']);
230
    }
231

232
    $data['name']        = get_config('sitename');
233
234
235
236
237
    $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');
238
    $data['cronrunning'] = !record_exists_select('cron', 'nextrun IS NULL OR nextrun < CURRENT_DATE');
Richard Mansfield's avatar
Richard Mansfield committed
239

240
241
242
243
244
245
246
247
248
    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);
        }
249
    }
250

251
    return($data);
252
253
}

254
function user_statistics($limit, $offset, &$sitedata) {
255
256
    $data = array();
    $data['tableheadings'] = array(
257
258
259
260
        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'),
261
262
    );
    $data['table'] = user_stats_table($limit, $offset);
263
264
    $data['tabletitle'] = get_string('userstatstabletitle', 'admin');

265
    $maxfriends = get_records_sql_array("
266
        SELECT u.id, u.firstname, u.lastname, u.preferredname, SUM(f.friends) AS friends
267
268
269
270
271
272
273
274
        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
275
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname
276
        ORDER BY friends DESC
277
        LIMIT 1", array());
278
279
    $maxfriends = $maxfriends[0];
    $meanfriends = 2 * count_records('usr_friend') / $sitedata['users'];
280
281
282
283
    if ($maxfriends) {
        $data['strmaxfriends'] = get_string(
            'statsmaxfriends',
            'admin',
284
            round($meanfriends, 1),
285
            get_config('wwwroot') . 'user/view.php?id=' . $maxfriends->id,
286
            hsc(display_name($maxfriends, null, true)),
287
288
289
290
291
292
            $maxfriends->friends
        );
    }
    else {
        $data['strmaxfriends'] = get_string('statsnofriends', 'admin');
    }
293
    $maxviews = get_records_sql_array("
Richard Mansfield's avatar
Richard Mansfield committed
294
        SELECT u.id, u.firstname, u.lastname, u.preferredname, COUNT(v.id) AS views
295
        FROM {usr} u JOIN {view} v ON u.id = v.owner
Francois Marier's avatar
Francois Marier committed
296
        WHERE \"owner\" <> 0
297
298
299
300
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname
        ORDER BY views DESC
        LIMIT 1", array());
    $maxviews = $maxviews[0];
301
302
303
304
305
306
    if ($maxviews) {
        $data['strmaxviews'] = get_string(
            'statsmaxviews',
            'admin',
            $sitedata['viewsperuser'],
            get_config('wwwroot') . 'user/view.php?id=' . $maxviews->id,
307
            hsc(display_name($maxviews, null, true)),
308
309
310
311
312
313
            $maxviews->views
        );
    }
    else {
        $data['strmaxviews'] = get_string('statsnoviews', 'admin');
    }
314
315
316
317
318
319
320
321
    $maxgroups = get_records_sql_array("
        SELECT u.id, u.firstname, u.lastname, u.preferredname, COUNT(m.group) AS groups
        FROM {usr} u JOIN {group_member} m ON u.id = m.member JOIN {group} g ON m.group = g.id
        WHERE g.deleted = 0
        GROUP BY u.id, u.firstname, u.lastname, u.preferredname
        ORDER BY groups DESC
        LIMIT 1", array());
    $maxgroups = $maxgroups[0];
322
323
324
325
326
327
    if ($maxgroups) {
        $data['strmaxgroups'] = get_string(
            'statsmaxgroups',
            'admin',
            $sitedata['groupmemberaverage'],
            get_config('wwwroot') . 'user/view.php?id=' . $maxgroups->id,
328
            hsc(display_name($maxgroups, null, true)),
329
330
331
332
333
334
            $maxgroups->groups
        );
    }
    else {
        $data['strmaxgroups'] = get_string('statsnogroups', 'admin');
    }
335
336
337
338
339
340
341
342
343
344
345
346
    $maxquotaused = get_records_sql_array("
        SELECT id, firstname, lastname, preferredname, quotaused
        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)),
        get_config('wwwroot') . 'user/view.php?id=' . $maxquotaused->id,
347
        hsc(display_name($maxquotaused, null, true)),
348
349
350
        display_size($maxquotaused->quotaused)
    );

351
    $data['institutions'] = stats_graph_url('institutions');
352

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

357
358
359
360
361
362
363
364
365
    return $data;
}

function user_stats_table($limit, $offset) {
    $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',
366
367
        'jsonscript' => 'admin/statistics.json.php',
        'datatable' => 'statistics_table',
368
369
370
371
372
373
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
    ));

    $result = array(
374
        'count'         => $count,
375
376
377
378
379
380
381
382
383
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

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

384
    $day = is_postgres() ? "to_date(t.ctime::text, 'YYYY-MM-DD')" : 'DATE(t.ctime)'; // TODO: make work on other databases?
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402

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

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

    $userdata = get_records_sql_array(
Francois Marier's avatar
Francois Marier committed
406
        "SELECT ctime, type, \"value\", $day AS date
407
        FROM {site_data}
Richard Mansfield's avatar
Richard Mansfield committed
408
        WHERE type IN (?,?) AND ctime >= ? AND ctime < (date(?) + INTERVAL $dayinterval)
409
410
411
412
413
        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(
414
        "SELECT $day AS cdate, COUNT(id) AS users
415
        FROM {usr}
416
417
418
        WHERE NOT ctime IS NULL AND ctime >= ? AND ctime < (date(?) + INTERVAL $dayinterval)
        GROUP BY cdate",
        array($daterange->mindate, $daterange->maxdate)
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
    );

    $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) {
437
438
                if (isset($data[$r->cdate])) {
                    $data[$r->cdate]['created'] = $r->users;
439
440
441
442
443
444
445
446
447
448
449
450
                }
            }
        }
    }

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

    return $result;
}

451
452
453
454
455
456
457
458
459
460
461
462

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);
463
464
        // Truncate to avoid overlapping labels
        $dataarray = array_slice($dataarray, 0, 25, true);
465
466
467

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

468
        $Graph =& Image_Graph::factory('graph', array(300, 300));
469
470
471
472
473
474
        $Font =& $Graph->addNew('font', 'Vera');
        $Font->setSize(9);
        $Graph->setFont($Font);

        $Graph->add(
            Image_Graph::vertical(
475
476
477
478
479
480
481
                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
482
483
484
            )
        );

485
486
487
488
489
        $Date->setAlignment(IMAGE_GRAPH_ALIGN_RIGHT);
        $DateFont =& $Graph->addNew('font', 'Vera');
        $DateFont->setColor('gray@0.8');
        $Date->setFont($DateFont);

490
491
492
        $Dataset =& Image_Graph::factory('dataset', array($dataarray));
        $Plot =& $Plotarea->addNew('bar', array(&$Dataset));
        $Plot->setLineColor('gray');
493
        $Plot->setSpacing(2);
494
495
496
497
498
499
500
501
502

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

503
504
505
506
507
508
        $AxisX =& $Plotarea->getAxis(IMAGE_GRAPH_AXIS_X);
        if (count($dataarray) > 4) {
            $AxisX->setFontAngle('vertical');
        }
        $AxisX->setFontSize(8);

509
        $Graph->done(array('filename' => stats_graph_path('institutions')));
510
511
512
    }
}

Richard Mansfield's avatar
Richard Mansfield committed
513
514
515
function group_statistics($limit, $offset) {
    $data = array();
    $data['tableheadings'] = array(
516
517
518
        array('name' => '#'),
        array('name' => get_string('Group', 'group')),
        array('name' => get_string('Members', 'group'), 'class' => 'center'),
Sean Brennan's avatar
Sean Brennan committed
519
        array('name' => get_string('Views', 'view'), 'class' => 'center'),
520
521
        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
522
523
    );
    $data['table'] = group_stats_table($limit, $offset);
524
    $data['tabletitle'] = get_string('groupstatstabletitle', 'admin');
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540

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

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

Richard Mansfield's avatar
Richard Mansfield committed
545
546
547
548
549
550
551
552
553
    return $data;
}

function group_stats_table($limit, $offset) {
    $count = count_records('group', 'deleted', 0);

    $pagination = build_pagination(array(
        'id' => 'stats_pagination',
        'url' => get_config('wwwroot') . 'admin/statistics.php?type=groups',
554
555
        'jsonscript' => 'admin/statistics.json.php',
        'datatable' => 'statistics_table',
Richard Mansfield's avatar
Richard Mansfield committed
556
557
558
559
560
561
        'count' => $count,
        'limit' => $limit,
        'offset' => $offset,
    ));

    $result = array(
562
        'count'         => $count,
Richard Mansfield's avatar
Richard Mansfield committed
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

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

    $groupdata = get_records_sql_array(
        "SELECT
            g.id, g.name, mc.members, vc.views, fc.forums, pc.posts
        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
604
            mc.members DESC, g.name, g.id",
Richard Mansfield's avatar
Richard Mansfield committed
605
606
607
608
609
610
611
612
613
614
615
616
617
        array(),
        $offset,
        $limit
    );

    $smarty = smarty_core();
    $smarty->assign('data', $groupdata);
    $smarty->assign('offset', $offset);
    $result['tablerows'] = $smarty->fetch('admin/groupstats.tpl');

    return $result;
}

618
619
620
621
622
623
624
625
626
627
628
629
630
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);
631
632
            $strjoin = get_string('membershiptype.abbrev.' . $t->jointype, 'group');
            $dataarray[$strtype . '/' . $strjoin] = $t->groups;
633
        }
634
        ksort($dataarray);
635
636
637
638
639
640
641
642
643
644
        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(
645
646
647
648
649
650
651
652
            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
653
            )
654
655
        );

656
657
658
659
660
        $Date->setAlignment(IMAGE_GRAPH_ALIGN_RIGHT);
        $DateFont =& $Graph->addNew('font', 'Vera');
        $DateFont->setColor('gray@0.8');
        $Date->setFont($DateFont);

661
662
        $Legend->setPlotArea($Plotarea);
        $Legend->setFontSize(6);
663
        $Plotarea->hideAxis();
664

665
        $Dataset =& Image_Graph::factory('dataset', array($dataarray));
666
        $Plot =& $Plotarea->addNew('pie', $Dataset);
667
668
669
670
671
672
673
674
675
676

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

679
        $Marker =& $Plot->addNew('Image_Graph_Marker_Value', IMAGE_GRAPH_VALUE_Y);
680
        $Marker->setBorderColor('white');
681
        $Marker->setFontSize(7);
682
683
684
685

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

686
        $Graph->done(array('filename' => stats_graph_path('grouptypes')));
687
688
689
    }
}

Richard Mansfield's avatar
Richard Mansfield committed
690
691
692
function view_statistics($limit, $offset) {
    $data = array();
    $data['tableheadings'] = array(
693
694
695
696
697
        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
698
699
    );
    $data['table'] = view_stats_table($limit, $offset);
700
    $data['tabletitle'] = get_string('viewstatstabletitle', 'admin');
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716

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

Richard Mansfield's avatar
Richard Mansfield committed
721
722
723
724
    return $data;
}

function view_stats_table($limit, $offset) {
725
    $count = count_records_select('view', '(owner != 0 OR owner IS NULL) AND type != ?', array('dashboard'));
Richard Mansfield's avatar
Richard Mansfield committed
726
727
728
729
730
731
732
733
734
735
736
737

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

    $result = array(
738
        'count'         => $count,
Richard Mansfield's avatar
Richard Mansfield committed
739
740
741
742
743
744
745
746
747
        'tablerows'     => '',
        'pagination'    => $pagination['html'],
        'pagination_js' => $pagination['javascript'],
    );

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

748
    $viewdata = get_records_sql_assoc(
Richard Mansfield's avatar
Richard Mansfield committed
749
        "SELECT
750
            v.id, v.title, v.owner, v.group, v.institution, v.visits,
751
752
753
            u.id AS userid, u.firstname, u.lastname,
            g.id AS groupid, g.name AS groupname,
            i.displayname AS institutionname
Richard Mansfield's avatar
Richard Mansfield committed
754
755
756
757
        FROM {view} v
            LEFT JOIN {usr} u ON v.owner = u.id
            LEFT JOIN {group} g ON v.group = g.id
            LEFT JOIN {institution} i ON v.institution = i.name
758
        WHERE (v.owner != 0 OR \"owner\" IS NULL) AND v.type != ?
759
        ORDER BY v.visits DESC, v.title, v.id",
760
        array('dashboard'),
Richard Mansfield's avatar
Richard Mansfield committed
761
762
763
764
        $offset,
        $limit
    );

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

Richard Mansfield's avatar
Richard Mansfield committed
768
    foreach ($viewdata as &$v) {
769
770
771
772
773
774
775
776
777
778
779
780
781
782
        if ($v->owner) {
            $v->ownername = display_name($v->owner);
            $v->ownerurl  = 'user/view.php?id=' . $v->userid;
        }
        else if ($v->group) {
            $v->ownername = $v->groupname;
            $v->ownerurl  = 'group/view.php?id=' . $v->groupid;
        }
        else if ($v->institution == 'mahara') {
            $v->ownername = get_config('sitename');
        }
        else if ($v->institution) {
            $v->ownername = $v->institutionname;
        }
783
        $v->comments = isset($comments[$v->id]) ? (int) $comments[$v->id]->comments : 0;
Richard Mansfield's avatar
Richard Mansfield committed
784
785
786
787
788
789
790
791
792
793
    }

    $smarty = smarty_core();
    $smarty->assign('data', $viewdata);
    $smarty->assign('offset', $offset);
    $result['tablerows'] = $smarty->fetch('admin/viewstats.tpl');

    return $result;
}

794
795
796
797
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
798
        FROM {view} WHERE type != ?
799
        GROUP BY type',
800
        array('dashboard')
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
    );

    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(
819
820
821
822
823
824
825
                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
826
827
828
            )
        );

829
830
831
832
833
        $Date->setAlignment(IMAGE_GRAPH_ALIGN_RIGHT);
        $DateFont =& $Graph->addNew('font', 'Vera');
        $DateFont->setColor('gray@0.8');
        $Date->setFont($DateFont);

834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
        $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);

855
        $Graph->done(array('filename' => stats_graph_path('viewtypes')));
856
857
858
859
    }
}


860
861
862
863
864
function graph_site_data_weekly() {

    $lastyear = db_format_timestamp(time() - 60*60*12*365);
    $values = array($lastyear, 'view-count', 'user-count', 'group-count');
    $weekly = get_records_sql_array('
Francois Marier's avatar
Francois Marier committed
865
        SELECT ctime, type, "value", ' . db_format_tsfield('ctime', 'ts') . '
866
867
868
869
        FROM {site_data}
        WHERE ctime >= ? AND type IN (?,?,?)
        ORDER BY ctime, type', $values);

Richard Mansfield's avatar
Richard Mansfield committed
870
    if (!count($weekly) > 1) {
871
872
873
        return;
    }

Richard Mansfield's avatar
Richard Mansfield committed
874
    $dataarray = array();
875
    foreach ($weekly as &$r) {
876
        $dataarray[$r->type][strftime("%d %b", $r->ts)] = $r->value;
877
    }
878
879
880
881
882
883
    foreach ($dataarray as &$t) {
        // The graph will look nasty until we have 2 points to plot.
        if (count($t) < 2) {
            return;
        }
    }
884
885
886

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

887
    $Graph =& Image_Graph::factory('graph', array(350, 200));
888
    $Font =& $Graph->addNew('font', 'Vera');
889
    $Font->setSize(9);
890
891
    $Graph->setFont($Font);

Richard Mansfield's avatar
Richard Mansfield committed
892
893
    $Graph->add(
        Image_Graph::vertical(
894
895
896
897
898
899
900
            Image_Graph::vertical(
                $Plotarea = Image_Graph::factory('plotarea'),
                $Legend = Image_Graph::factory('legend'),
                88
            ),
            $Date = Image_Graph::factory('title', array(format_date(time(), 'strftimew3cdate'), 7)),
            96
Richard Mansfield's avatar
Richard Mansfield committed
901
902
903
        )
    );

904
905
906
907
908
    $Date->setAlignment(IMAGE_GRAPH_ALIGN_RIGHT);
    $DateFont =& $Graph->addNew('font', 'Vera');
    $DateFont->setColor('gray@0.8');
    $Date->setFont($DateFont);

Richard Mansfield's avatar
Richard Mansfield committed
909
910
911
    $Legend->setPlotarea($Plotarea);

    $datasetinfo = array(
912
        'user-count'  => array('color' => 'blue@0.6', 'name' => get_string('users')),
Sean Brennan's avatar
Sean Brennan committed
913
        'view-count'  => array('color' => 'green@0.6', 'name' => get_string('Views', 'view')),
914
        'group-count' => array('color' => 'red@0.6', 'name' => get_string('groups')),
915
916
    );

917
    $yaxis = array('min' => array(), 'max' => array());
918
    $points = 1;
Richard Mansfield's avatar
Richard Mansfield committed
919
920
921
    foreach (array_keys($datasetinfo) as $k) {
        $dataset =& Image_Graph::factory('dataset', array($dataarray[$k]));
        $dataset->setName($datasetinfo[$k]['name']);
922
        $plot =& $Plotarea->addNew('line', array(&$dataset));
Richard Mansfield's avatar
Richard Mansfield committed
923
        $linestyle =& Image_Graph::factory('Image_Graph_Line_Solid', array($datasetinfo[$k]['color']));
924
925
        $linestyle->setThickness(3);
        $plot->setLineStyle($linestyle);
926
927
        $yaxis['max'][$k] = max($dataarray[$k]);
        $yaxis['min'][$k] = min($dataarray[$k]);
928
        $points = max($points, count($dataarray[$k]));
929
930
    }

931
932
933
934
935
936
    $AxisX =& $Plotarea->getAxis(IMAGE_GRAPH_AXIS_X);
    $AxisX->setFontAngle('vertical');
    $AxisX->setFontSize(8);
    $AxisX->setLabelInterval(ceil($points/30)); // Avoid label crowding

    $AxisY =& $Plotarea->getAxis(IMAGE_GRAPH_AXIS_Y);
937
    $maxy = max($yaxis['max']);
938
    $AxisY->forceMaximum($maxy * 1.025);
939
940
    // $miny = min($yaxis['min']);
    // $padding = ($maxy - $miny) * 0.025;
941
942
    // $AxisY->forceMaximum($maxy + $padding);
    // $AxisY->forceMinimum($miny - $padding);
943

944
    $Graph->done(array('filename' => stats_graph_path('weekly')));
945
946
}

947
function graph_site_data_daily() {
948
949
950
    user_institution_graph();
    group_type_graph();
    view_type_graph();
951
952
}

953
954
955
956
957
958
959
960
961
962
963
function stats_graph_path($name) {
    return get_config('dataroot') . 'images/' . $name . '.png';
}

function stats_graph_url($name) {
    if (file_exists(stats_graph_path($name))) {
        return get_config('wwwroot') . 'admin/thumb.php?type=' . $name;
    }
    return '';
}

964
?>