activity.php 33.5 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
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
 *
Francois Marier's avatar
Francois Marier committed
7
8
9
10
 * 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.
11
 *
Francois Marier's avatar
Francois Marier committed
12
13
14
15
 * 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.
16
 *
Francois Marier's avatar
Francois Marier committed
17
18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21
 *
 * @package    mahara
 * @subpackage core
22
 * @author     Catalyst IT Ltd
23
 * @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
 *
 */

defined('INTERNAL') || die();

/**
 * This is the function to call whenever anything happens
 * that is going to end up on a user's activity page.
 * 
 * @param string $activitytype type of activity
 * @param mixed $data data 
 */
37
function activity_occurred($activitytype, $data, $plugintype=null, $pluginname=null, $overridedelay=false) {
38
    $at = activity_locate_typerecord($activitytype, $plugintype, $pluginname);
39
    if (!empty($at->delay) && !$overridedelay) {
40
        $delayed = new StdClass;
41
        $delayed->type = $at->id;
42
43
44
45
46
        $delayed->data = serialize($data);
        $delayed->ctime = db_format_timestamp(time());
        insert_record('activity_queue', $delayed);
    }
    else {
47
        handle_activity($at, $data);
48
    }
49
50
51
}

/** 
52
53
54
 * This function dispatches all the activity stuff to whatever notification 
 * plugin it needs to, and figures out all the implications of activity and who 
 * needs to know about it.
55
 * 
56
 * @param object $activitytype record from database table activity_type
57
58
 * @param mixed $data must contain message to save.
 * each activity type has different requirements of $data - 
59
 *  - <b>viewaccess</b> must contain $owner userid of view owner AND $view (id of view) and $oldusers array of userids before access change was committed.
60
 */
61
function handle_activity($activitytype, $data, $cron=false) {
62
    $data = (object)$data;
63
    $activitytype = activity_locate_typerecord($activitytype);
64

65
66
67
68
69
70
71
    $classname = 'ActivityType' . ucfirst($activitytype->name);
    if (!empty($activitytype->plugintype)) {
        safe_require($activitytype->plugintype, $activitytype->pluginname);
        $classname = 'ActivityType' . 
            ucfirst($activitytype->plugintype) . 
            ucfirst($activitytype->pluginname) . 
            ucfirst($activitytype->name);
72
    }
73

74
    $activity = new $classname($data, $cron);
75
    if (!$activity->any_users()) {
76
77
        return;
    }
78

79
    $activity->notify_users();
80
81
82
}

/**
83
84
 * this function returns an array of users who subsribe to a particular activitytype 
 * including the notification method they are using to subscribe to it.
85
 *
86
 * @param int $activitytype the id of the activity type
87
88
89
 * @param array $userids an array of userids to filter by
 * @param array $userobjs an array of user objects to filterby
 * @param bool $adminonly whether to filter by admin flag
90
 * @param array $admininstitutions list of institution names to get admins for
91
92
 * @return array of users
 */
93
94
function activity_get_users($activitytype, $userids=null, $userobjs=null, $adminonly=false,
                            $admininstitutions = array()) {
95
    $values = array($activitytype);
96
97
    $sql = '
        SELECT
98
            u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff, 
99
            p.method, ap.value AS lang, aic.value AS mnethostwwwroot, h.appname AS mnethostapp
100
101
        FROM {usr} u
        LEFT JOIN {usr_activity_preference} p
102
            ON (p.usr = u.id AND p.activity = ?)' . (empty($admininstitutions) ? '' : '
103
104
105
        LEFT OUTER JOIN {usr_institution} ui
            ON (u.id = ui.usr
                AND ui.institution IN ('.join(',',array_map('db_quote',$admininstitutions)).'))') . '
106
107
        LEFT OUTER JOIN {usr_account_preference} ap
            ON (ap.usr = u.id AND ap.field = \'lang\')
108
109
110
111
112
113
        LEFT OUTER JOIN {auth_instance} ai
            ON (ai.id = u.authinstance AND ai.authname = \'xmlrpc\')
        LEFT OUTER JOIN {auth_instance_config} aic
            ON (aic.instance = ai.id AND aic.field = \'wwwroot\')
        LEFT OUTER JOIN {host} h
            ON aic.value = h.wwwroot
114
        WHERE TRUE';
115
116
117
118
119
120
121
122
    if (!empty($userobjs) && is_array($userobjs)) {
        $sql .= ' AND u.id IN (' . implode(',',db_array_to_ph($userobjs)) . ')';
        $values = array_merge($values, array_to_fields($userobjs));
    } 
    else if (!empty($userids) && is_array($userids)) {
        $sql .= ' AND u.id IN (' . implode(',',db_array_to_ph($userids)) . ')';
        $values = array_merge($values, $userids);
    }
123
124
125
    if (!empty($admininstitutions)) {
        $sql .= '
        GROUP BY
126
            u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff,
127
            p.method, ap.value, aic.value, h.appname
128
129
130
131
        HAVING (u.admin = 1 OR SUM(ui.admin) > 0)';
    } else if ($adminonly) {
        $sql .= ' AND u.admin = 1';
    }
132
    return get_records_sql_array($sql, $values);
133
134
}

135
136
137
138
139
140
141
142
143
144
145
146
147
148

function activity_default_notification_method() {
    static $method = null;
    if (is_null($method)) {
        if (in_array('email', array_map(create_function('$a', 'return $a->name;'), plugins_installed('notification')))) {
            $method = 'email';
        }
        else {
            $method = 'internal';
        }
    }
    return $method;
}

149
150
151
152
/**
 * this function inserts a default set of activity preferences for a given user
 * id
 */
153
154
function activity_set_defaults($eventdata) {
    $user_id = $eventdata['id'];
155
    $activitytypes = get_records_array('activity_type', 'admin', 0);
156
157
    $method = activity_default_notification_method();

158
    foreach ($activitytypes as $type) {
159
160
        insert_record('usr_activity_preference', (object)array(
            'usr' => $user_id,
Richard Mansfield's avatar
Richard Mansfield committed
161
            'activity' => $type->id,
162
            'method' => $method,
163
        ));
164
165
166
167
    }
    
}

168
169
function activity_add_admin_defaults($userids) {
    $activitytypes = get_records_array('activity_type', 'admin', 1);
170
171
    $method = activity_default_notification_method();

172
173
    foreach ($activitytypes as $type) {
        foreach ($userids as $id) {
174
            if (!record_exists('usr_activity_preference', 'usr', $id, 'activity', $type->id)) {
175
176
                insert_record('usr_activity_preference', (object)array(
                    'usr' => $id,
177
                    'activity' => $type->id,
178
                    'method' => $method,
179
180
181
182
183
184
185
                ));
            }
        }
    }
}


186
187
function activity_process_queue() {

188
    db_begin();
189
    if ($toprocess = get_records_array('activity_queue')) {
190
191
192
        // Hack to avoid duplicate watchlist notifications on the same view
        $watchlist = activity_locate_typerecord('watchlist');
        $viewsnotified = array();
193
        foreach ($toprocess as $activity) {
194
195
196
197
198
199
200
            $data = unserialize($activity->data);
            if ($activity->type == $watchlist->id && !empty($data->view)) {
                if (isset($viewsnotified[$data->view])) {
                    continue;
                }
                $viewsnotified[$data->view] = true;
            }
201
202
203
204
205
206
207
208
            try {
                handle_activity($activity->type, $data, true);
            }
            catch (MaharaException $e) {
                // Exceptions can happen while processing the queue, we just 
                // log them and continue
                log_debug($e->getMessage());
            }
209
210
211
212
213
        }
        delete_records('activity_queue');
    }
    db_commit();
}
214

215
function activity_get_viewaccess_users($view, $owner, $type) {
216
    $type = activity_locate_typerecord($type);
217
    $sql = "SELECT userid, u.*, p.method, ap.value AS lang
218
219
                FROM (
                SELECT (CASE WHEN usr1 = ? THEN usr2 ELSE usr1 END) AS userid 
220
221
222
                    FROM {usr_friend} f
                    JOIN {view} v ON (v.owner = f.usr1 OR v.owner = f.usr2)
                    JOIN {view_access} vu ON vu.view = v.id
223
                        WHERE (usr1 = ? OR usr2 = ?) AND vu.accesstype = ? AND v.id = ? 
224
                UNION SELECT usr AS userid 
225
                    FROM {view_access_usr} u 
226
                        WHERE u.view = ?
227
                UNION SELECT m.member 
228
                    FROM {group_member} m
229
230
                    JOIN {view_access_group} vg ON vg.group = m.group
                    JOIN {group} g ON (g.id = vg.group AND g.deleted = 0)
231
                        WHERE vg.view = ? AND (vg.role IS NULL OR vg.role = m.role)
232
                ) AS userlist
233
                JOIN {usr} u ON u.id = userlist.userid
234
235
                LEFT JOIN {usr_activity_preference} p ON p.usr = u.id AND p.activity = ?
                LEFT JOIN {usr_account_preference} ap ON ap.usr = u.id AND ap.field = 'lang'";
236
    $values = array($owner, $owner, $owner, 'friends', $view, $view, $view, $type->id);
237
    if (!$u = get_records_sql_assoc($sql, $values)) {
238
239
240
        $u = array();
    }
    return $u;
241
242
}

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
function activity_locate_typerecord($activitytype, $plugintype=null, $pluginname=null) {
    if (is_object($activitytype)) {
        return $activitytype;
    }
    if (is_numeric($activitytype)) {
        $at = get_record('activity_type', 'id', $activitytype);
    }
    else {
        if (empty($plugintype) && empty($pluginname)) {
            $at = get_record_select('activity_type', 
                'name = ? AND plugintype IS NULL AND pluginname IS NULL', 
                array($activitytype));
        } 
        else {
            $at = get_record('activity_type', 'name', $activitytype, 'plugintype', $plugintype, 'pluginname', $pluginname);
        }
    }
    if (empty($at)) {
        throw new Exception("Invalid activity type $activitytype");
    }
    return $at;
}
265

266
267
268
269
270
271
272
273
274
275
276
function generate_activity_class_name($name, $plugintype, $pluginname) {
    if (!empty($plugintype)) {
        safe_require($plugintype, $pluginname);
        return 'ActivityType' .
            ucfirst($plugintype) .
            ucfirst($pluginname) .
            ucfirst($name);
    }
    return 'ActivityType' . $name;
}

277
278
279
/** activity type classes **/
abstract class ActivityType {
    
280
281
282
283
284
285
286
287
288
289
290
291
    /**
     * Who any notifications about this activity should appear to come from
     */
    protected $fromuser;

    /**
     * When sending notifications, should the email of the person sending it be 
     * hidden? (Almost always yes, will cause the email to appear to come from 
     * the 'noreply' address)
     */
    protected $hideemail = true;

292
293
    protected $subject;
    protected $message;
294
    protected $strings;
295
296
    protected $users = array();
    protected $url;
297
    protected $id;
298
299
    protected $type;
    protected $activityname;
300
    protected $cron;
301
    protected $overridemessagecontents;
Evan Goldenberg's avatar
Evan Goldenberg committed
302
    protected $parent;
303
304
305
306
307
308
309
310
   
    public function get_id() {
        if (!isset($this->id)) {
            $tmp = activity_locate_typerecord($this->get_type());
            $this->id = $tmp->id;
        }
        return $this->id;
    }
311
312
313
314
315
316
317
318
319
320
321
322
323
324
    
    public function get_type() {
        $prefix = 'ActivityType';
        return strtolower(substr(get_class($this), strlen($prefix)));
    }

    public function any_users() {
        return (is_array($this->users) && count($this->users) > 0);
    }

    public function get_users() {
        return $this->users;
    }

325
326
    public function __construct($data, $cron=false) {
        $this->cron = $cron;
327
328
        $this->set_parameters($data);
        $this->ensure_parameters();
329
        $this->activityname = strtolower(substr(get_class($this), strlen('ActivityType')));
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
    }

    private function set_parameters($data) {
        foreach ($data as $key => $value) {
            if (property_exists($this, $key)) {
                $this->{$key} = $value;
            }
        }   
    }

    private function ensure_parameters() {
        foreach ($this->get_required_parameters() as $param) {
            if (!isset($this->{$param})) {
                throw new ParamOutOfRangeException(get_string('missingparam', 'activity', $param, $this->get_type()));
            }
        }
    }

    public function to_stdclass() {
       return (object)get_object_vars($this); 
    }
351

352
    public function get_string_for_user($user, $string) {
353
354
355
        if (empty($string)) {
            return;
        }
356
357
358
359
360
361
        $args = array_merge(
            array(
                $user->lang,
                $this->strings->{$string}->key,
                $this->strings->{$string}->section,
            ),
362
            empty($this->strings->{$string}->args) ? array() : $this->strings->{$string}->args
363
364
365
366
        );
        return call_user_func_array('get_string_from_language', $args);
    }

367
368
369
370
371
    // Optional string to use for the link text.
    public function add_urltext(array $stringdef) {
        $this->strings->urltext = (object) $stringdef;
    }

372
    public function get_message($user) {
373
374
375
        if (empty($this->message)) {
            return $this->get_string_for_user($user, 'message');
        }
376
377
        return $this->message;
    }
378
        
379
    public function get_subject($user) {
380
381
382
        if (empty($this->subject)) {
            return $this->get_string_for_user($user, 'subject');
        }
383
384
        return $this->subject;
    }
385

386
387
388
389
390
    // rewrite the url with the internal notification id?
    protected function update_url() {
        return false;
    }

391
    abstract function get_required_parameters();
392
393

    public function notify_user($user) {
394
        $changes = new stdClass;
395

396
397
398
399
400
        $userdata = $this->to_stdclass();
        // some stuff gets overridden by user specific stuff
        if (!empty($user->url)) {
            $userdata->url = $user->url;
        }
401
        $userdata->urltext = $this->get_string_for_user($user, 'urltext');
402
403
404
405
406
407
        if (empty($user->lang) || $user->lang == 'default') {
            $user->lang = get_config('lang');
        }
        $userdata->message = $this->get_message($user);
        $userdata->subject = $this->get_subject($user);
        if (empty($user->method)) {
408
            $user->method = call_static_method(get_class($this), 'default_notification_method');
409
        }
410
411

        // always do internal
412
413
        $userdata->internalid = call_static_method('PluginNotificationInternal', 'notify_user', $user, $userdata);
        if ($this->update_url($userdata->internalid)) {
414
            $changes->url = $userdata->url = $this->url;
415
416
        }

417
418
419
420
421
422
        if ($user->method != 'internal' || isset($changes->url)) {
            $changes->read = (int) ($user->method != 'internal');
            $changes->id = $userdata->internalid;
            update_record('notification_internal_activity', $changes);
        }

423
424
        if ($user->method != 'internal') {
            $method = $user->method;
425
            safe_require('notification', $method);
426
427
428
            try {
                call_static_method(generate_class_name('notification', $method), 'notify_user', $user, $userdata);
            }
429
430
431
            catch (MaharaException $e) {
                // We don't mind other notification methods failing, as it'll 
                // go into the activity log as 'unread'
432
433
                $changes->read = 0;
                update_record('notification_internal_activity', $changes);
434
435
            }
        }
436

437
438
439
    }

    public function notify_users() {
440
        safe_require('notification', 'internal');
441
442
443
444
445
446
        $this->type = $this->get_id();

        foreach ($this->get_users() as $user) {
            $this->notify_user($user);
        }
    }
447
448
449
450

    public static function default_notification_method() {
        return activity_default_notification_method();
    }
451
452
453
454
455
}


abstract class ActivityTypeAdmin extends ActivityType { 

456
457
    public function __construct($data, $cron=false) {
        parent::__construct($data, $cron);
458
        $this->users = activity_get_users($this->get_id(), null, null, true);
459
460
461
462
463
464
465
    }
}

class ActivityTypeContactus extends ActivityTypeAdmin {
    
    protected $fromname;
    protected $fromemail;
466
467
468
469
470
471
472
473
474
475
    protected $hideemail = false;

    /**
     * @param array $data Parameters:
     *                    - message (string)
     *                    - subject (string) (optional)
     *                    - fromname (string)
     *                    - fromaddress (email address)
     *                    - fromuser (int) (if a logged in user)
     */
476
477
    function __construct($data, $cron=false) { 
        parent::__construct($data, $cron);
478
479
        if (!empty($this->fromuser)) {
            $this->url = get_config('wwwroot') . 'user/view.php?id=' . $this->fromuser;
480
        }
481
482
483
484
485
        else {
            $this->customheaders = array(
                'Reply-to: ' . $this->fromname . ' <' . $this->fromemail . '>',
            );
        }
486
    }
487
488
489
490
491
492
493

    function get_subject($user) {
        return get_string_from_language($user->lang, 'newcontactus', 'activity');
    }

    function get_message($user) {
        return get_string_from_language($user->lang, 'newcontactusfrom', 'activity') . ' ' . $this->fromname 
494
            . ' <' . $this->fromemail .'>' . (isset($this->subject) ? ': ' . $this->subject : '')
495
496
497
            . "\n\n" . $this->message;
    }

498
499
500
501
502
503
504
505
506
    public function get_required_parameters() {
        return array('message', 'fromname', 'fromemail');
    }
}

class ActivityTypeObjectionable extends ActivityTypeAdmin {

    protected $view;
    protected $artefact;
507
    protected $reporter;
508

509
510
511
512
513
514
515
    /**
     * @param array $data Parameters:
     *                    - message (string)
     *                    - view (int)
     *                    - artefact (int) (optional)
     *                    - reporter (int)
     */
516
517
    function __construct($data, $cron=false) { 
        parent::__construct($data, $cron);
518
519
520
521
522
523
524
525
526
        if (empty($this->artefact)) {
            $this->url = get_config('wwwroot') . 'view/view.php?id=' . $this->view;
        }
        else {
            $this->url = get_config('wwwroot') . 'view/artefact.php?artefact=' . $this->artefact . '&view=' . $this->view;
        }
    }

    function get_subject($user) {
527
528
529
530
        if (!$viewtitle = get_field('view', 'title', 'id', $this->view)) {
            throw new ViewNotFoundException(get_string('viewnotfound', 'error', $this->view));
        }
        if (empty($this->artefact)) {
531
532
            return get_string_from_language($user->lang, 'objectionablecontentview', 'activity',
                                            $viewtitle, display_name($this->reporter, $user));
533
534
535
536
537
        }
        else {
            if (!$artefacttitle = get_field('artefact', 'title', 'id', $this->artefact)) {
                throw new ArtefactNotFoundException(get_string('artefactnotfound', 'error', $this->artefact));
            }
538
539
            return get_string_from_language($user->lang, 'objectionablecontentartefact', 'activity',
                                            $artefacttitle, display_name($this->reporter, $user));
540
541
542
543
        }
    }

    public function get_required_parameters() {
544
        return array('message', 'view', 'reporter');
545
546
547
548
549
550
551
552
553
554
    }

}

class ActivityTypeVirusRepeat extends ActivityTypeAdmin {

    protected $username;
    protected $fullname;
    protected $userid;

555
556
    public function __construct($data, $cron=false) { 
        parent::__construct($data, $cron);
557
558
559
    }

    public function get_subject($user) {
560
        $userstring = $this->username . ' (' . $this->fullname . ') (userid:' . $this->userid . ')' ;
561
562
563
564
565
        return get_string_from_language($user->lang, 'virusrepeatsubject', 'mahara', $userstring);
    }

    public function get_message($user) {
        return get_string_from_language($user->lang, 'virusrepeatmessage');
566
567
568
569
570
571
572
573
574
    }

    public function get_required_parameters() {
        return array('username', 'fullname', 'userid');
    }
}

class ActivityTypeVirusRelease extends ActivityTypeAdmin {

575
576
    public function __construct($data, $cron=false) { 
        parent::__construct($data, $cron);
577
578
579
580
581
582
583
584
585
    }

    public function get_required_parameters() {
        return array();
    }
}

class ActivityTypeMaharamessage extends ActivityType {

586
587
588
589
590
591
    /**
     * @param array $data Parameters:
     *                    - subject (string)
     *                    - message (string)
     *                    - users (list of user ids)
     */
592
593
    public function __construct($data, $cron=false) { 
        parent::__construct($data, $cron);
594
        $this->users = activity_get_users($this->get_id(), $this->users);
595
596
597
598
599
600
601
    }

    public function get_required_parameters() {
        return array('message', 'subject', 'users');
    }
}

602
603
604
605
606
607
608
class ActivityTypeInstitutionmessage extends ActivityType {

    protected $messagetype;
    protected $institution;
    protected $username;
    protected $fullname;

609
610
    public function __construct($data, $cron=false) {
        parent::__construct($data, $cron);
611
612
613
614
615
        if ($this->messagetype == 'request') {
            $this->url = get_config('wwwroot') . 'admin/users/institutionusers.php';
            $this->users = activity_get_users($this->get_id(), null, null, null,
                                              array($this->institution->name));
        } else if ($this->messagetype == 'invite') {
616
            $this->url = get_config('wwwroot') . 'account/institutions.php';
617
618
619
620
            $this->users = activity_get_users($this->get_id(), $this->users);
        }
    }

621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
    public function get_subject($user) {
        if ($this->messagetype == 'request') {
            $userstring = $this->fullname . ' (' . $this->username . ')';
            return get_string_from_language($user->lang, 'institutionrequestsubject', 'activity', $userstring, 
                                            $this->institution->displayname);
        } else if ($this->messagetype == 'invite') {
            return get_string_from_language($user->lang, 'institutioninvitesubject', 'activity', 
                                            $this->institution->displayname);
        }
    }

    public function get_message($user) {
        if ($this->messagetype == 'request') {
            return get_string_from_language($user->lang, 'institutionrequestmessage', 'activity');
        } else if ($this->messagetype == 'invite') {
            return get_string_from_language($user->lang, 'institutioninvitemessage', 'activity');
        }
    }

640
641
642
643
644
    public function get_required_parameters() {
        return array('messagetype', 'institution');
    }
}

645
646
647
648
649
class ActivityTypeUsermessage extends ActivityType { 

    protected $userto;
    protected $userfrom;

650
651
652
653
654
655
    /**
     * @param array $data Parameters:
     *                    - userto (int)
     *                    - userfrom (int)
     *                    - subject (string)
     *                    - message (string)
Evan Goldenberg's avatar
Evan Goldenberg committed
656
     *                    - parent (int)
657
     */
658
659
    public function __construct($data, $cron=false) { 
        parent::__construct($data, $cron);
660
661
662
        if ($this->userfrom) {
            $this->fromuser = $this->userfrom;
        }
663
        $this->users = activity_get_users($this->get_id(), array($this->userto));
664
665
666
667
        $this->add_urltext(array(
            'key'     => 'Reply',
            'section' => 'group',
        ));
668
669
    } 

670
671
    public function get_subject($user) {
        if (empty($this->subject)) {
Clare Lenihan's avatar
Clare Lenihan committed
672
            return get_string_from_language($user->lang, 'newusermessage', 'group',
673
674
675
676
677
                                            display_name($this->userfrom));
        }
        return $this->subject;
    }

678
    protected function update_url($internalid) {
Evan Goldenberg's avatar
Evan Goldenberg committed
679
        $this->url = get_config('wwwroot') . 'user/sendmessage.php?id=' . $this->userfrom . '&replyto=' . $internalid . '&returnto=inbox';
680
681
682
        return true;
    }

683
684
685
686
687
688
689
690
691
692
    public function get_required_parameters() {
        return array('message', 'userto', 'userfrom');
    }
    
}

class ActivityTypeWatchlist extends ActivityType { 

    protected $view;

693
694
    private $viewinfo;

695
696
697
698
    /**
     * @param array $data Parameters:
     *                    - view (int)
     */
699
700
    public function __construct($data, $cron) { 
        parent::__construct($data, $cron); 
701
702
        //$oldsubject = $this->subject;
        if (!$this->viewinfo = get_record_sql('SELECT u.*, v.title FROM {usr} u
703
704
                                         JOIN {view} v ON v.owner = u.id
                                         WHERE v.id = ?', array($this->view))) {
705
            if (!empty($this->cron)) { // probably deleted already
706
707
708
709
                return;
            }
            throw new ViewNotFoundException(get_string('viewnotfound', 'error', $this->view));
        }
710
711
712
713
714
        // mysql compatibility (sigh...)
        $casturl = 'CAST(? AS TEXT)';
        if (get_config('dbtype') == 'mysql') {
            $casturl = 'CAST(? AS CHAR)'; // note, NOT varchar
        }
715
        $sql = 'SELECT u.*, p.method, ap.value AS lang, ' . $casturl . ' AS url
716
717
718
719
720
                    FROM {usr_watchlist_view} wv
                    JOIN {usr} u
                        ON wv.usr = u.id
                    LEFT JOIN {usr_activity_preference} p
                        ON p.usr = u.id
721
722
                    LEFT OUTER JOIN {usr_account_preference} ap
                        ON (ap.usr = u.id AND ap.field = \'lang\')
723
724
725
726
727
                    WHERE (p.activity = ? OR p.activity IS NULL)
                    AND wv.view = ?
               ';
        $this->users = get_records_sql_array($sql, 
                                       array(get_config('wwwroot') . 'view/view.php?id=' 
728
                                             . $this->view, $this->get_id(), $this->view));
729
        $this->add_urltext(array('key' => 'View', 'section' => 'view'));
730
731
732
733
734
735
736
    }

    public function get_subject($user) {
        return get_string_from_language($user->lang, 'newwatchlistmessage', 'activity');
    }

    public function get_message($user) {
737
738
        return get_string_from_language($user->lang, 'newwatchlistmessageview', 'activity', 
                                        display_name($this->viewinfo, $user), $this->viewinfo->title);
739
740
741
    }

    public function get_required_parameters() {
742
        return array('view');
743
744
745
746
747
748
749
750
    }
}

class ActivityTypeNewview extends ActivityType { 

    protected $owner;
    protected $view;

751
752
    private $viewinfo;

753
754
    public function __construct($data, $cron=false) { 
        parent::__construct($data, $cron);
755
        if (!$this->viewinfo = get_record_sql('SELECT u.*, v.title FROM {usr} u
756
757
                                         JOIN {view} v ON v.owner = u.id
                                         WHERE v.id = ?', array($this->view))) {
758
            if (!empty($this->cron)) { //probably deleted already
759
760
761
762
763
764
765
766
                return;
            }
            throw new ViewNotFoundException(get_string('viewnotfound', 'error', $this->view));
        }

        $this->url = get_config('wwwroot') . 'view/view.php?id=' . $this->view;

        // add users on friendslist or userlist...
767
        $this->users = activity_get_viewaccess_users($this->view, $this->owner, $this->get_id()); 
768
769
770
771
772
773
774
    }

    public function get_subject($user) {
        return get_string_from_language($user->lang, 'newviewsubject', 'activity');
    }
    
    public function get_message($user) {
775
776
        return get_string_from_language($user->lang, 'newviewmessage', 'activity', 
                                        display_name($this->viewinfo, $user), $this->viewinfo->title);
777
778
779
780
781
782
783
784
785
786
787
788
789
    }
    
    public function get_required_parameters() {
        return array('owner', 'view');
    }
}

class ActivityTypeViewaccess extends ActivityType { 

    protected $view;
    protected $owner;
    protected $oldusers; // this can be empty though

790
791
    private $viewinfo;

792
793
794
795
796
797
    /**
     * @param array $data Parameters:
     *                    - owner (int)
     *                    - view (int)
     *                    - oldusers (array of user IDs)
     */
798
799
    public function __construct($data, $cron=false) { 
        parent::__construct($data, $cron);
800
        if (!$this->viewinfo = get_record_sql('SELECT u.*, v.title FROM {usr} u
801
802
                                         JOIN {view} v ON v.owner = u.id
                                         WHERE v.id = ?', array($this->view))) {
803
            if (!empty($this->cron)) { // probably deleted already
804
805
806
807
808
809
                return;
            }
            throw new ViewNotFoundException(get_string('viewnotfound', 'error', $this->view));
        }
        $this->url = get_config('wwwroot') . 'view/view.php?id=' . $this->view;
        $this->users = array_diff_key(
810
            activity_get_viewaccess_users($this->view, $this->owner, $this->get_id()),
811
812
            $this->oldusers
        );
813
        $this->add_urltext(array('key' => 'View', 'section' => 'view'));
814
    }
815

816
817
818
819
820
    public function get_subject($user) {
        return get_string('newviewaccesssubject', 'activity');
    }
    
    public function get_message($user) {
821
822
        return get_string_from_language($user->lang, 'newviewaccessmessage', 'activity',
                                        $this->viewinfo->title, display_name($this->viewinfo, $user));
823
824
    }
    
825
826
827
828
829
    public function get_required_parameters() {
        return array('view', 'owner', 'oldusers');
    }
}

830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
class ActivityTypeGroupMessage extends ActivityType {

    protected $group;
    protected $roles;
    protected $submittedview;
    private $viewinfo;
    private $groupinfo;

    /**
     * @param array $data Parameters:
     *                    - subject (string)
     *                    - message (string)
     *                    - group (integer)
     *                    - roles (list of roles)
     */
    public function __construct($data, $cron=false) {
        require_once('group.php');

        parent::__construct($data, $cron);

        $this->groupinfo = get_record('group', 'id', $this->group);

        $members = group_get_member_ids($this->group, isset($this->roles) ? $this->roles : null);
        $this->users = activity_get_users($this->get_id(), $members);

        if ($this->submittedview) {
            $this->viewinfo = get_record('view', 'id', $this->submittedview);
            $this->viewinfo->ownername = display_name($this->viewinfo->owner);
            $this->url = get_config('wwwroot') . 'view/view.php?id=' . $this->submittedview;
        }
    }

    public function get_subject($user) {
        if ($this->submittedview) {
            return get_string_from_language($user->lang, 'viewsubmittedsubject', 'activity', $this->groupinfo->name);
        }
        return $this->subject;
    }

    public function get_message($user) {
        if ($this->submittedview) {
            return get_string_from_language($user->lang, 'viewsubmittedmessage', 'activity', $this->viewinfo->ownername, $this->viewinfo->title, $this->groupinfo->name);
        }
        return $this->subject;
    }

    public function get_required_parameters() {
        return array('message', 'subject', 'group');
    }
}

881
882
883
884
885
886
abstract class ActivityTypePlugin extends ActivityType {

    abstract public function get_plugintype();

    abstract public function get_pluginname();

887
888
889
890
891
    public function get_type() {
        $prefix = 'ActivityType' . $this->get_plugintype() . $this->get_pluginname();
        return strtolower(substr(get_class($this), strlen($prefix)));
    }

892
893
894
895
896
897
898
899
900
    public function get_id() {
        if (!isset($this->id)) {
            $tmp = activity_locate_typerecord($this->get_type(), $this->get_plugintype(), $this->get_pluginname());
            $this->id = $tmp->id;
        }
        return $this->id;
    }
}

901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
/**
 * Get one page of notifications and return html
 */
function activitylist_html($type='all', $limit=10, $offset=0) {
    global $USER;

    $userid = $USER->get('id');

    $typesql = '';
    if ($type != 'all') {
        // Treat as comma-separated list of activity type names
        $types = split(',', preg_replace('/[^a-z,]+/', '', $type));
        if ($types) {
            $typesql = ' at.name IN (' . join(',', array_map('db_quote', $types)) . ')';
            if (in_array('adminmessages', $types)) {
                $typesql = '(' . $typesql . ' OR at.admin = 1)';
            }
            $typesql = ' AND ' . $typesql;
        }
    }

    $from = "
        FROM {notification_internal_activity} a
        JOIN {activity_type} at ON a.type = at.id
        WHERE a.usr = ? $typesql";
    $values = array($userid);

    $count = count_records_sql('SELECT COUNT(*)' . $from, $values);

    $pagination = build_pagination(array(
        'id'         => 'activitylist_pagination',
        'url'        => get_config('wwwroot') . 'account/activity/index.php?type=' . hsc($type),
        'jsonscript' => 'account/activity/index.json.php',
        'datatable'  => 'activitylist',
        'count'      => $count,
        'limit'      => $limit,
        'offset'     => $offset,
    ));

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

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

    $records = get_records_sql_array('
        SELECT
            a.*, at.name AS type, at.plugintype, at.pluginname' . $from . '
        ORDER BY a.ctime DESC',
        $values,
        $offset,
        $limit
    );
    if ($records) {
        foreach ($records as &$r) {
            $r->date = format_date(strtotime($r->ctime), 'strfdaymonthyearshort');
            $section = empty($r->plugintype) ? 'activity' : "{$r->plugintype}.{$r->pluginname}";
            $r->strtype = get_string('type' . $r->type, $section);
967
            $r->message = format_whitespace($r->message);
968
969
970
971
972
973
974
975
976
        }
    }

    $smarty = smarty_core();
    $smarty->assign('data', $records);
    $result['tablerows'] = $smarty->fetch('account/activity/activitylist.tpl');

    return $result;
}