activity.php 61.6 KB
Newer Older
1 2 3 4 5
<?php
/**
 *
 * @package    mahara
 * @subpackage core
6
 * @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
 *
 */

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

/**
 * This is the function to call whenever anything happens
 * that is going to end up on a user's activity page.
Aaron Wells's avatar
Aaron Wells committed
17
 *
18
 * @param string $activitytype type of activity
19 20 21 22
 * @param array $data must contain the fields specified by get_required_parameters of the activity type subclass.
 * @param string $plugintype
 * @param string $pluginname
 * @param bool $delay
23
 */
24
function activity_occurred($activitytype, $data, $plugintype=null, $pluginname=null, $delay=null) {
25 26 27 28 29 30
    try {
        $at = activity_locate_typerecord($activitytype, $plugintype, $pluginname);
    }
    catch (Exception $e) {
        return;
    }
31 32 33 34
    if (is_null($delay)) {
        $delay = !empty($at->delay);
    }
    if ($delay) {
35
        $delayed = new StdClass;
36
        $delayed->type = $at->id;
37 38 39 40 41
        $delayed->data = serialize($data);
        $delayed->ctime = db_format_timestamp(time());
        insert_record('activity_queue', $delayed);
    }
    else {
42
        handle_activity($at, $data);
43
    }
44 45
}

Aaron Wells's avatar
Aaron Wells committed
46 47 48
/**
 * This function dispatches all the activity stuff to whatever notification
 * plugin it needs to, and figures out all the implications of activity and who
49
 * needs to know about it.
Aaron Wells's avatar
Aaron Wells committed
50
 *
51
 * @param object $activitytype record from database table activity_type
52
 * @param mixed $data must contain message to save.
Aaron Wells's avatar
Aaron Wells committed
53
 * each activity type has different requirements of $data -
54
 *  - <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.
55 56 57 58
 * @param $cron = true if called by a cron job
 * @param object $queuedactivity  record of the activity in the queue (from the table activity_queue)
 * @return int The ID of the last processed user
 *      = 0 if all users get processed
59
 */
60
function handle_activity($activitytype, $data, $cron=false, $queuedactivity=null) {
61
    $data = (object)$data;
62

63 64 65 66 67
    if ($cron && isset($queuedactivity)) {
        $data->last_processed_userid = $queuedactivity->last_processed_userid;
        $data->activity_queue_id = $queuedactivity->id;
    }

68
    $classname = get_activity_type_classname($activitytype);
69
    $activity = new $classname($data, $cron);
70
    if (!$activity->any_users()) {
71
        return 0;
72
    }
73

74
    return $activity->notify_users();
75 76
}

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
/**
 * Given an activity type id or record, calculate the class name.
 *
 * @param mixed $activitytype either numeric activity type id or an activity type record (containing name, plugintype, pluginname)
 * @return string
 */
function get_activity_type_classname($activitytype) {
    $activitytype = activity_locate_typerecord($activitytype);

    $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);
    }
    return $classname;
}

97
/**
Aaron Wells's avatar
Aaron Wells committed
98
 * this function returns an array of users who subsribe to a particular activitytype
99
 * including the notification method they are using to subscribe to it.
100
 *
101
 * @param int $activitytype the id of the activity type
102 103 104
 * @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
105
 * @param array $admininstitutions list of institution names to get admins for
106 107
 * @return array of users
 */
108 109
function activity_get_users($activitytype, $userids=null, $userobjs=null, $adminonly=false,
                            $admininstitutions = array()) {
110
    $values = array($activitytype);
111 112
    $sql = '
        SELECT
Aaron Wells's avatar
Aaron Wells committed
113
            u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff,
114 115
            p.method, ap.value AS lang, apm.value AS maildisabled, aic.value AS mnethostwwwroot,
            h.appname AS mnethostapp
116 117
        FROM {usr} u
        LEFT JOIN {usr_activity_preference} p
118
            ON (p.usr = u.id AND p.activity = ?)' . (empty($admininstitutions) ? '' : '
119 120 121
        LEFT OUTER JOIN {usr_institution} ui
            ON (u.id = ui.usr
                AND ui.institution IN ('.join(',',array_map('db_quote',$admininstitutions)).'))') . '
122 123
        LEFT OUTER JOIN {usr_account_preference} ap
            ON (ap.usr = u.id AND ap.field = \'lang\')
124
        LEFT OUTER JOIN {usr_account_preference} apm
125
            ON (apm.usr = u.id AND apm.field = \'maildisabled\')
126 127 128 129 130 131
        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
132
        WHERE u.deleted = 0';
133 134 135
    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));
Aaron Wells's avatar
Aaron Wells committed
136
    }
137 138 139 140
    else if (!empty($userids) && is_array($userids)) {
        $sql .= ' AND u.id IN (' . implode(',',db_array_to_ph($userids)) . ')';
        $values = array_merge($values, $userids);
    }
141 142 143
    if (!empty($admininstitutions)) {
        $sql .= '
        GROUP BY
144
            u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff,
145
            p.method, ap.value, apm.value, aic.value, h.appname
146 147 148 149
        HAVING (u.admin = 1 OR SUM(ui.admin) > 0)';
    } else if ($adminonly) {
        $sql .= ' AND u.admin = 1';
    }
Aaron Wells's avatar
Aaron Wells committed
150
    return get_records_sql_assoc($sql, $values);
151 152
}

153

154 155 156 157
/**
 * this function inserts a default set of activity preferences for a given user
 * id
 */
158 159
function activity_set_defaults($eventdata) {
    $user_id = $eventdata['id'];
160
    $activitytypes = get_records_array('activity_type', 'admin', 0);
161

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

171 172
function activity_add_admin_defaults($userids) {
    $activitytypes = get_records_array('activity_type', 'admin', 1);
173

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


188 189
function activity_process_queue() {

190
    if ($toprocess = get_records_array('activity_queue')) {
191 192 193
        // Hack to avoid duplicate watchlist notifications on the same view
        $watchlist = activity_locate_typerecord('watchlist');
        $viewsnotified = array();
194
        foreach ($toprocess as $activity) {
195 196 197 198 199 200 201
            $data = unserialize($activity->data);
            if ($activity->type == $watchlist->id && !empty($data->view)) {
                if (isset($viewsnotified[$data->view])) {
                    continue;
                }
                $viewsnotified[$data->view] = true;
            }
202

203
            try {
204
                $last_processed_userid = handle_activity($activity->type, $data, true, $activity);
205 206
            }
            catch (MaharaException $e) {
Aaron Wells's avatar
Aaron Wells committed
207
                // Exceptions can happen while processing the queue, we just
208 209 210
                // log them and continue
                log_debug($e->getMessage());
            }
211 212 213 214 215 216 217 218 219 220 221 222 223
            // Update the activity queue
            // or Remove this activity from the queue if all the users get processed
            // to make sure we
            // never send duplicate emails even if part of the
            // activity handler fails for whatever reason
            if (!empty($last_processed_userid)) {
                update_record('activity_queue', array('last_processed_userid' => $last_processed_userid), array('id' => $activity->id));
            }
            else {
                if (!delete_records('activity_queue', 'id', $activity->id)) {
                    log_warn("Unable to remove activity $activity->id from the queue. Skipping it.");
                }
            }
224 225 226
        }
    }
}
227

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
/**
 * event-listener is called when an artefact is changed or a block instance
 * is commited. Saves the view, the block instance, user and time into the
 * database
 *
 * @global User $USER
 * @param string $event
 * @param object $eventdata
 */
function watchlist_record_changes($event){
    global $USER;

    // don't catch root's changes, especially not when installing...
    if ($USER->get('id') <= 0) {
        return;
    }
    if ($event instanceof BlockInstance) {
245 246 247 248 249
        $viewid = $event->get('view');
        if ($viewid) {
            set_field('view', 'mtime', db_format_timestamp(time()), 'id', $viewid);
        }
        if (record_exists('usr_watchlist_view', 'view', $viewid)) {
250 251
            $whereobj = new stdClass();
            $whereobj->block = $event->get('id');
252
            $whereobj->view = $viewid;
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
            $whereobj->usr = $USER->get('id');
            $dataobj = clone $whereobj;
            $dataobj->changed_on = date('Y-m-d H:i:s');
            ensure_record_exists('watchlist_queue', $whereobj, $dataobj);
        }
    }
    else if ($event instanceof ArtefactType) {
        $blockid = $event->get('id');
        $getcolumnquery = '
            SELECT DISTINCT
             "view", "block"
            FROM
             {view_artefact}
            WHERE
             artefact =' . $blockid;
        $relations = get_records_sql_array($getcolumnquery, array());

        // fix unnecessary type-inconsistency of get_records_sql_array
        if (false === $relations) {
            $relations = array();
        }

        foreach ($relations as $rel) {
276 277 278 279 280
            $viewid = $rel->view;
            if ($viewid) {
                set_field('view', 'mtime', db_format_timestamp(time()), 'id', $viewid);
            }
            if (!record_exists('usr_watchlist_view', 'view', $viewid)) {
281 282 283 284
                continue;
            }
            $whereobj = new stdClass();
            $whereobj->block = $rel->block;
285
            $whereobj->view = $viewid;
286 287 288 289 290 291 292 293
            $whereobj->usr = $USER->get('id');
            $dataobj = clone $whereobj;
            $dataobj->changed_on = date('Y-m-d H:i:s');
            ensure_record_exists('watchlist_queue', $whereobj, $dataobj);
        }
    }
    else if (!is_object($event) && !empty($event['id'])) {
        $viewid = $event['id'];
294 295 296
        if ($viewid) {
            set_field('view', 'mtime', db_format_timestamp(time()), 'id', $viewid);
        }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
        if (record_exists('usr_watchlist_view', 'view', $viewid)) {
            $whereobj = new stdClass();
            $whereobj->view = $viewid;
            $whereobj->usr = $USER->get('id');
            $whereobj->block = null;
            $dataobj = clone $whereobj;
            $dataobj->changed_on = date('Y-m-d H:i:s');
            ensure_record_exists('watchlist_queue', $whereobj, $dataobj);
        }
    }
    else {
        return;
    }
}

/**
 * is triggered when a blockinstance is deleted. Deletes all watchlist_queue
 * entries that refer to this blockinstance
 *
 * @param BlockInstance $blockinstance
 */
function watchlist_block_deleted(BlockInstance $block) {
    global $USER;

    // don't catch root's changes, especially not when installing...
    if ($USER->get('id') <= 0) {
        return;
    }

    delete_records('watchlist_queue', 'block', $block->get('id'));

    if (record_exists('usr_watchlist_view', 'view', $block->get('view'))) {
        $whereobj = new stdClass();
        $whereobj->view = $block->get('view');
        $whereobj->block = null;
        $whereobj->usr = $USER->get('id');
        $dataobj = clone $whereobj;
        $dataobj->changed_on = date('Y-m-d H:i:s');
        ensure_record_exists('watchlist_queue', $whereobj, $dataobj);
    }
}

/**
 * is called by the cron-job to process the notifications stored into
 * watchlist_queue.
 */
function watchlist_process_notifications() {
    $delayMin = get_config('watchlistnotification_delay');
    $comparetime = time() - $delayMin * 60;

    $sql = "SELECT usr, view, MAX(changed_on) AS time
            FROM {watchlist_queue}
            GROUP BY usr, view";
    $results = get_records_sql_array($sql, array());

    if (false === $results) {
        return;
    }

    foreach ($results as $viewuserdaterow) {
        if ($viewuserdaterow->time > date('Y-m-d H:i:s', $comparetime)) {
            continue;
        }

        // don't send a notification if only blockinstances are referenced
        // that were deleted (block exists but corresponding
        // block_instance doesn't)
        $sendnotification = false;

        $blockinstance_ids = get_column('watchlist_queue', 'block', 'usr', $viewuserdaterow->usr, 'view', $viewuserdaterow->view);
        if (is_array($blockinstance_ids)) {
            $blockinstance_ids = array_unique($blockinstance_ids);
        }

        $viewuserdaterow->blocktitles = array();

        // need to check if view has an owner, group or institution
        $view = get_record('view', 'id', $viewuserdaterow->view);
        if (empty($view->owner) && empty($view->group) && empty($view->institution)) {
            continue;
        }
        // ignore root pages, owner = 0, this account is not meant to produce content
        if (isset($view->owner) && empty($view->owner)) {
            continue;
        }
382 383 384 385 386 387 388
        // Ignore system templates, institution = 'mahara' and template = 2
        require_once(get_config('libroot') . 'view.php');
        if (isset($view->institution)
            && $view->institution == 'mahara'
            && $view->template == View::SITE_TEMPLATE) {
            continue;
        }
389 390 391 392 393 394 395 396 397 398 399 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 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

        foreach ($blockinstance_ids as $blockinstance_id) {
            if (empty($blockinstance_id)) {
                // if no blockinstance is given, assume that the form itself
                // was changed, e.g. the theme, or a block was removed
                $sendnotification = true;
                continue;
            }
            require_once(get_config('docroot') . 'blocktype/lib.php');

            try {
                $block = new BlockInstance($blockinstance_id);
            }
            catch (BlockInstanceNotFoundException $exc) {
                // maybe the block was deleted
                continue;
            }

            $blocktype = $block->get('blocktype');
            $title = '';

            // try to get title rendered by plugin-class
            safe_require('blocktype', $blocktype);
            if (class_exists(generate_class_name('blocktype', $blocktype))) {
                $title = $block->get_title();
            }
            else {
                log_warn('class for blocktype could not be loaded: ' . $blocktype);
                $title = $block->get('title');
            }

            // if no title was given to the blockinstance, try to get one
            // from the artefact
            if (empty($title)) {
                $configdata = $block->get('configdata');

                if (array_key_exists('artefactid', $configdata)) {
                    try {
                        $artefact = $block->get_artefact_instance($configdata['artefactid']);
                        $title = $artefact->get('title');
                    }
                    catch(Exception $exc) {
                        log_warn('couldn\'t identify title of blockinstance ' .
                                 $block->get('id') . $exc->getMessage());
                    }
                }
            }

            // still no title, maybe the default-name for the blocktype
            if (empty($title)) {
                $title = get_string('title', 'blocktype.' . $blocktype);
            }

            // no title could be retrieved, so let's tell the user at least
            // what type of block was changed
            if (empty($title)) {
                $title = '[' . $blocktype . '] (' .
                    get_string('nonamegiven', 'activity') . ')';
            }

            $viewuserdaterow->blocktitles[] = $title;
            $sendnotification = true;
        }

        // only send notification if there is something to talk about (don't
        // send notification for example when new blockelement was aborted)
        if ($sendnotification) {
            try{
                $watchlistnotification = new ActivityTypeWatchlistnotification($viewuserdaterow, false);
                $watchlistnotification->notify_users();
            }
            catch (ViewNotFoundException $exc) {
                // Seems like the view has been deleted, don't do anything
            }
            catch (SystemException $exc) {
                // if the view that was changed doesn't have an owner
            }
        }

        delete_records('watchlist_queue', 'usr', $viewuserdaterow->usr, 'view', $viewuserdaterow->view);
    }
}

472
function activity_get_viewaccess_users($view) {
473
    require_once(get_config('docroot') . 'lib/group.php');
474
    $sql = "SELECT userlist.userid, usr.*, actpref.method, accpref.value AS lang
475
                FROM (
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
                    SELECT friend.usr1 AS userid
                      FROM {view} view
                      JOIN {view_access} access ON (access.view = view.id AND access.accesstype = 'friends')
                      JOIN {usr_friend} friend ON (view.owner = friend.usr2 AND view.id = ?)
                    UNION
                    SELECT friend.usr2 AS userid
                      FROM {view} view
                      JOIN {view_access} access ON (access.view = view.id AND access.accesstype = 'friends')
                      JOIN {usr_friend} friend ON (view.owner = friend.usr1 AND view.id = ?)
                    UNION
                    SELECT access.usr AS userid
                      FROM {view_access} access
                     WHERE access.view = ?
                    UNION
                    SELECT members.member AS userid
                      FROM {view_access} access
492 493 494 495 496 497 498
                      JOIN {group} grp ON (access.group = grp.id AND grp.deleted = 0 AND access.view = ?)
                      JOIN {group_member} members ON (grp.id = members.group AND members.member <> CASE WHEN access.usr IS NULL THEN -1 ELSE access.usr END)
                     WHERE (access.role IS NULL OR access.role = members.role) AND
                      (grp.viewnotify = " . GROUP_ROLES_ALL . "
                       OR (grp.viewnotify = " . GROUP_ROLES_NONMEMBER . " AND (members.role = 'admin' OR members.role = 'tutor'))
                       OR (grp.viewnotify = " . GROUP_ROLES_ADMIN . " AND members.role = 'admin')
                      )
499
                ) AS userlist
500 501 502 503 504
                JOIN {usr} usr ON usr.id = userlist.userid
                LEFT JOIN {usr_activity_preference} actpref ON actpref.usr = usr.id
                LEFT JOIN {activity_type} acttype ON actpref.activity = acttype.id AND acttype.name = 'viewaccess'
                LEFT JOIN {usr_account_preference} accpref ON accpref.usr = usr.id AND accpref.field = 'lang'";
    $values = array($view, $view, $view, $view);
505
    if (!$u = get_records_sql_assoc($sql, $values)) {
506 507 508
        $u = array();
    }
    return $u;
509 510
}

511 512 513 514 515 516 517 518 519
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)) {
Aaron Wells's avatar
Aaron Wells committed
520 521
            $at = get_record_select('activity_type',
                'name = ? AND plugintype IS NULL AND pluginname IS NULL',
522
                array($activitytype));
Aaron Wells's avatar
Aaron Wells committed
523
        }
524 525 526 527 528
        else {
            $at = get_record('activity_type', 'name', $activitytype, 'plugintype', $plugintype, 'pluginname', $pluginname);
        }
    }
    if (empty($at)) {
529
        throw new SystemException("Invalid activity type $activitytype");
530 531 532
    }
    return $at;
}
533

534 535 536 537 538 539 540 541 542 543 544
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;
}

545 546 547 548 549 550 551 552 553
/**
 * To implement a new activity type, you must subclass this class. Your subclass
 * MUST at minimum include the following:
 *
 * 1. Override the __construct method with one which first calls parent::__construct
 *    and then populates $this->users with the list of recipients for this activity.
 *
 * 2. Implement the get_required_parameters method.
 */
554
abstract class ActivityType {
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

    /**
     * NOTE: Child classes MUST call the parent constructor, AND populate
     * $this->users with a list of user records which should receive the message!
     *
     * @param array $data The data needed to send the notification
     * @param boolean $cron Indicates whether this is being called by the cron job
     */
    public function __construct($data, $cron=false) {
        $this->cron = $cron;
        $this->set_parameters($data);
        $this->ensure_parameters();
        $this->activityname = strtolower(substr(get_class($this), strlen('ActivityType')));
    }

    /**
     * This method should return an array which names the fields that must be present in the
     * $data that was passed to the class's constructor. It should include all necessary data
     * to determine the recipient(s) of the notification and to determine its content.
     *
     * @return array
     */
    abstract function get_required_parameters();

579 580 581 582 583
    /**
     * The number of users in a split chunk to notify
     */
    const USERCHUNK_SIZE = 1000;

584 585 586 587 588 589
    /**
     * Who any notifications about this activity should appear to come from
     */
    protected $fromuser;

    /**
Aaron Wells's avatar
Aaron Wells committed
590 591
     * 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
592 593 594 595
     * the 'noreply' address)
     */
    protected $hideemail = true;

596 597
    protected $subject;
    protected $message;
598
    protected $strings;
599 600
    protected $users = array();
    protected $url;
601
    protected $urltext;
602
    protected $id;
603 604
    protected $type;
    protected $activityname;
605
    protected $cron;
606 607
    protected $last_processed_userid;
    protected $activity_queue_id;
608
    protected $overridemessagecontents;
Evan Goldenberg's avatar
Evan Goldenberg committed
609
    protected $parent;
610
    protected $defaultmethod;
611

612 613 614 615 616 617 618
    public function get_id() {
        if (!isset($this->id)) {
            $tmp = activity_locate_typerecord($this->get_type());
            $this->id = $tmp->id;
        }
        return $this->id;
    }
619 620 621 622 623 624 625 626 627

    public function get_default_method() {
        if (!isset($this->defaultmethod)) {
            $tmp = activity_locate_typerecord($this->get_id());
            $this->defaultmethod = $tmp->defaultmethod;
        }
        return $this->defaultmethod;
    }

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    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;
    }

    private function set_parameters($data) {
        foreach ($data as $key => $value) {
            if (property_exists($this, $key)) {
                $this->{$key} = $value;
            }
646
        }
647 648 649 650 651
    }

    private function ensure_parameters() {
        foreach ($this->get_required_parameters() as $param) {
            if (!isset($this->{$param})) {
652 653 654 655
                // Allow some string parameters to be specified in $this->strings
                if (!in_array($param, array('subject', 'message', 'urltext')) || empty($this->strings->{$param}->key)) {
                    throw new ParamOutOfRangeException(get_string('missingparam', 'activity', $param, $this->get_type()));
                }
656 657 658 659 660
            }
        }
    }

    public function to_stdclass() {
Aaron Wells's avatar
Aaron Wells committed
661
       return (object)get_object_vars($this);
662
    }
663

664
    public function get_string_for_user($user, $string) {
665
        if (empty($string) || empty($this->strings->{$string}->key)) {
666 667
            return;
        }
668 669 670 671
        $args = array_merge(
            array(
                $user->lang,
                $this->strings->{$string}->key,
672
                empty($this->strings->{$string}->section) ? 'mahara' : $this->strings->{$string}->section,
673
            ),
674
            empty($this->strings->{$string}->args) ? array() : $this->strings->{$string}->args
675 676 677 678
        );
        return call_user_func_array('get_string_from_language', $args);
    }

679 680
    // Optional string to use for the link text.
    public function add_urltext(array $stringdef) {
681
        $def = $stringdef;
682 683 684
        if (!is_object($this->strings)) {
            $this->strings = new stdClass();
        }
685
        $this->strings->urltext = (object) $def;
686 687
    }

688 689 690 691 692 693 694
    public function get_urltext($user) {
        if (empty($this->urltext)) {
            return $this->get_string_for_user($user, 'urltext');
        }
        return $this->urltext;
    }

695
    public function get_message($user) {
696 697 698
        if (empty($this->message)) {
            return $this->get_string_for_user($user, 'message');
        }
699 700
        return $this->message;
    }
Aaron Wells's avatar
Aaron Wells committed
701

702
    public function get_subject($user) {
703 704 705
        if (empty($this->subject)) {
            return $this->get_string_for_user($user, 'subject');
        }
706 707
        return $this->subject;
    }
708

709 710 711 712 713 714 715 716 717
    /**
     * Rewrite $this->url with the ID of the internal notification record for this activity.
     * (Generally so that you can make a URL that sends the user to the Mahara inbox page
     * for this message.)
     *
     * @param int $internalid
     * @return boolean True if $this->url was updated, False if not.
     */
    protected function update_url($internalid) {
718 719 720
        return false;
    }

721
    public function notify_user($user) {
722
        $changes = new stdClass;
723

724 725 726 727 728 729 730 731 732
        $userdata = $this->to_stdclass();
        // some stuff gets overridden by user specific stuff
        if (!empty($user->url)) {
            $userdata->url = $user->url;
        }
        if (empty($user->lang) || $user->lang == 'default') {
            $user->lang = get_config('lang');
        }
        if (empty($user->method)) {
733
            // If method is not set then either the user has selected 'none' or their setting has not been set (so use default).
734 735 736 737 738 739
            if ($record = get_record('usr_activity_preference', 'usr', $user->id, 'activity', $this->get_id())) {
                $user->method = $record->method;
                if (empty($user->method)) {
                    // The user specified 'none' as their notification type.
                    return;
                }
740
            }
741 742 743 744 745 746
            else {
                $user->method = $this->get_default_method();
                if (empty($user->method)) {
                    // The default notification type is 'none' for this activity type.
                    return;
                }
747
            }
748
        }
749 750

        // always do internal
751 752 753 754 755 756
        foreach (PluginNotificationInternal::$userdata as &$p) {
            $function = 'get_' . $p;
            $userdata->$p = $this->$function($user);
        }

        $userdata->internalid = PluginNotificationInternal::notify_user($user, $userdata);
757
        if ($this->update_url($userdata->internalid)) {
758
            $changes->url = $userdata->url = $this->url;
759 760
        }

761 762 763 764 765 766
        if ($user->method != 'internal' || isset($changes->url)) {
            $changes->read = (int) ($user->method != 'internal');
            $changes->id = $userdata->internalid;
            update_record('notification_internal_activity', $changes);
        }

767 768
        if ($user->method != 'internal') {
            $method = $user->method;
769
            safe_require('notification', $method);
770 771 772 773 774 775 776 777 778 779
            $notificationclass = generate_class_name('notification', $method);
            $classvars = get_class_vars($notificationclass);
            if (!empty($classvars['userdata'])) {
                foreach ($classvars['userdata'] as &$p) {
                    $function = 'get_' . $p;
                    if (!isset($userdata->$p) && method_exists($this, $function)) {
                        $userdata->$p = $this->$function($user);
                    }
                }
            }
780
            try {
781
                call_static_method($notificationclass, 'notify_user', $user, $userdata);
782
            }
783
            catch (MaharaException $e) {
784
                static $badnotification = false;
785
                static $adminnotified = array();
786
                // We don't mind other notification methods failing, as it'll
787
                // go into the activity log as 'unread'
788 789
                $changes->read = 0;
                update_record('notification_internal_activity', $changes);
790
                if (!$badnotification && !($e instanceof EmailDisabledException || $e instanceof InvalidEmailException)) {
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
                    // Admins should probably know about the error, but to avoid sending too many similar notifications,
                    // save an initial prefix of the message being sent and throw away subsequent exceptions with the
                    // same prefix.  To cut down on spam, it's worth missing out on a few similar messages.
                    $k = substr($e, 0, 60);
                    if (!isset($adminnotified[$k])) {
                        $message = (object) array(
                            'users' => get_column('usr', 'id', 'admin', 1),
                            'subject' => get_string('adminnotificationerror', 'activity'),
                            'message' => $e,
                        );
                        $adminnotified[$k] = 1;
                        $badnotification = true;
                        activity_occurred('maharamessage', $message);
                        $badnotification = false;
                    }
806
                }
807 808
            }
        }
809

810 811
        // The user's unread message count does not need to be updated from $changes->read
        // because of the db trigger on notification_internal_activity.
812 813
    }

814 815 816 817 818 819
    /**
     * Sound out notifications to $this->users.
     * Note that, although this has batching properties built into it with USERCHUNK_SIZE,
     * it's also recommended to update a bulk ActivityType's constructor to limit the total
     * number of records pulled from the database.
     */
820
    public function notify_users() {
821
        safe_require('notification', 'internal');
822 823
        $this->type = $this->get_id();

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
        if ($this->cron) {
            // Sort the list of users to notify by userid
            uasort($this->users, function($a, $b) {return $a->id > $b->id;});
            // Notify a chunk of users
            $num_processed_users = 0;
            $last_processed_userid = 0;
            foreach ($this->users as $user) {
                if ($this->last_processed_userid && ($user->id <= $this->last_processed_userid)) {
                    continue;
                }
                if ($num_processed_users < ActivityType::USERCHUNK_SIZE) {
                    // Immediately update the last_processed_userid in the activity_queue
                    // to prevent duplicated notifications
                    $last_processed_userid = $user->id;
                    update_record('activity_queue', array('last_processed_userid' => $last_processed_userid), array('id' => $this->activity_queue_id));
                    $this->notify_user($user);
                    $num_processed_users++;
                }
                else {
843
                    break;
844 845
                }
            }
846
            return $last_processed_userid;
847 848 849 850 851 852
        }
        else {
            while (!empty($this->users)) {
                $user = array_shift($this->users);
                $this->notify_user($user);
            }
853
        }
854
        return 0;
855
    }
856
}
857

Aaron Wells's avatar
Aaron Wells committed
858
abstract class ActivityTypeAdmin extends ActivityType {
859

860 861
    public function __construct($data, $cron=false) {
        parent::__construct($data, $cron);
862
        $this->users = activity_get_users($this->get_id(), null, null, true);
863 864 865 866
    }
}

class ActivityTypeContactus extends ActivityTypeAdmin {
Aaron Wells's avatar
Aaron Wells committed
867

868 869
    protected $fromname;
    protected $fromemail;
870 871 872 873 874 875 876 877 878 879
    protected $hideemail = false;

    /**
     * @param array $data Parameters:
     *                    - message (string)
     *                    - subject (string) (optional)
     *                    - fromname (string)
     *                    - fromaddress (email address)
     *                    - fromuser (int) (if a logged in user)
     */
Aaron Wells's avatar
Aaron Wells committed
880
    function __construct($data, $cron=false) {
881
        parent::__construct($data, $cron);
882
        if (!empty($this->fromuser)) {
883
            $this->url = profile_url($this->fromuser, false);
884
        }
885 886 887 888 889
        else {
            $this->customheaders = array(
                'Reply-to: ' . $this->fromname . ' <' . $this->fromemail . '>',
            );
        }
890
    }
891 892 893 894 895 896

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

    function get_message($user) {
Aaron Wells's avatar
Aaron Wells committed
897
        return get_string_from_language($user->lang, 'newcontactusfrom', 'activity') . ' ' . $this->fromname
898
            . ' <' . $this->fromemail .'>' . (isset($this->subject) ? ': ' . $this->subject : '')
899 900 901
            . "\n\n" . $this->message;
    }

902 903 904 905 906 907 908 909 910
    public function get_required_parameters() {
        return array('message', 'fromname', 'fromemail');
    }
}

class ActivityTypeObjectionable extends ActivityTypeAdmin {

    protected $view;
    protected $artefact;
911
    protected $reporter;
912
    protected $ctime;
913

914 915 916 917 918 919
    /**
     * @param array $data Parameters:
     *                    - message (string)
     *                    - view (int)
     *                    - artefact (int) (optional)
     *                    - reporter (int)
920
     *                    - ctime (int) (optional)
921
     */
Aaron Wells's avatar
Aaron Wells committed
922
    function __construct($data, $cron=false) {
923
        parent::__construct($data, $cron);
924

925 926 927 928 929 930 931 932 933
        require_once('view.php');
        $this->view = new View($this->view);

        if (!empty($this->artefact)) {
            require_once(get_config('docroot') . 'artefact/lib.php');
            $this->artefact = artefact_instance_from_id($this->artefact);
        }

        if ($owner = $this->view->get('owner')) {
934
            // Notify institutional admins of the view owner
935
            if ($institutions = get_column('usr_institution', 'institution', 'usr', $owner)) {
936 937 938 939
                $this->users = activity_get_users($this->get_id(), null, null, null, $institutions);
            }
        }

940
        if (empty($this->artefact)) {
941
            $this->url = $this->view->get_url(false, true) . '&objection=1';
942 943
        }
        else {
944
            $this->url = 'artefact/artefact.php?artefact=' . $this->artefact->get('id') . '&view=' . $this->view->get('id') . '&objection=1';
945
        }
946

947
        if (empty($this->strings->subject)) {
948
            $this->overridemessagecontents = true;
949
            $viewtitle = $this->view->get('title');
950
            $this->strings = new stdClass();
951 952 953 954 955 956 957 958
            if (empty($this->artefact)) {
                $this->strings->subject = (object) array(
                    'key'     => 'objectionablecontentview',
                    'section' => 'activity',
                    'args'    => array($viewtitle, display_default_name($this->reporter)),
                );
            }
            else {
959
                $title = $this->artefact->get('title');
960 961 962 963 964
                $this->strings->subject = (object) array(
                    'key'     => 'objectionablecontentviewartefact',
                    'section' => 'activity',
                    'args'    => array($viewtitle, $title, display_default_name($this->reporter)),
                );
965 966 967 968
            }
        }
    }

969
    public function get_emailmessage($user) {
970
        $reporterurl = profile_url($this->reporter);
971 972 973 974 975
        $ctime = strftime(get_string_from_language($user->lang, 'strftimedaydatetime'), $this->ctime);
        if (empty($this->artefact)) {
            return get_string_from_language(
                $user->lang, 'objectionablecontentviewtext', 'activity',
                $this->view->get('title'), display_default_name($this->reporter), $ctime,
976
                $this->message, $this->view->get_url(true, true) . "&objection=1", $reporterurl
977 978 979 980 981 982
            );
        }
        else {
            return get_string_from_language(
                $user->lang, 'objectionablecontentviewartefacttext', 'activity',
                $this->view->get('title'), $this->artefact->get('title'), display_default_name($this->reporter), $ctime,
983
                $this->message, get_config('wwwroot') . "artefact/artefact.php?artefact=" . $this->artefact->get('id') . "&view=" . $this->view->get('id') . "&objection=1", $reporterurl
984 985 986 987 988 989 990
            );
        }
    }

    public function get_htmlmessage($user) {
        $viewtitle = hsc($this->view->get('title'));
        $reportername = hsc(display_default_name($this->reporter));
991
        $reporterurl = profile_url($this->reporter);
992 993 994 995 996 997
        $ctime = strftime(get_string_from_language($user->lang, 'strftimedaydatetime'), $this->ctime);
        $message = hsc($this->message);
        if (empty($this->artefact)) {
            return get_string_from_language(
                $user->lang, 'objectionablecontentviewhtml', 'activity',
                $viewtitle, $reportername, $ctime,
998
                $message, $this->view->get_url(true, true) . "&objection=1", $viewtitle,
999 1000 1001 1002 1003 1004 1005
                $reporterurl, $reportername
            );
        }
        else {
            return get_string_from_language(
                $user->lang, 'objectionablecontentviewartefacthtml', 'activity',
                $viewtitle, hsc($this->artefact->get('title')), $reportername, $ctime,
1006
                $message, get_config('wwwroot') . "artefact/artefact.php?artefact=" . $this->artefact->get('id') . "&view=" . $this->view->get('id') . "&objection=1", hsc($this->artefact->get('title')),
1007 1008 1009 1010 1011
                $reporterurl, $reportername
            );
        }
    }

1012
    public function get_required_parameters() {
1013
        return array('message', 'view', 'reporter');
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    }

}

class ActivityTypeVirusRepeat extends ActivityTypeAdmin {

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

Aaron Wells's avatar
Aaron Wells committed
1024
    public function __construct($data, $cron=false) {
1025
        parent::__construct($data, $cron);
1026 1027 1028
    }

    public function get_subject($user) {
1029
        $userstring = $this->username . ' (' . $this->fullname . ') (userid:' . $this->userid . ')' ;
1030 1031 1032 1033 1034
        return get_string_from_language($user->lang, 'virusrepeatsubject', 'mahara', $userstring);
    }

    public function get_message($user) {
        return get_string_from_language($user->lang, 'virusrepeatmessage');
1035 1036 1037 1038 1039 1040 1041 1042 1043
    }

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

class ActivityTypeVirusRelease extends ActivityTypeAdmin {

Aaron Wells's avatar
Aaron Wells committed
1044
    public function __construct($data, $cron=false) {
1045
        parent::__construct($data, $cron);
1046 1047 1048 1049 1050 1051 1052 1053 1054
    }

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

class ActivityTypeMaharamessage extends ActivityType {

1055 1056 1057 1058 1059 1060
    /**
     * @param array $data Parameters:
     *                    - subject (string)
     *                    - message (string)
     *                    - users (list of user ids)
     */
Aaron Wells's avatar
Aaron Wells committed
1061
    public function __construct($data, $cron=false) {
1062
        parent::__construct($data, $cron);
1063
        $this->users = activity_get_users($this->get_id(), $this->users);
1064 1065 1066 1067 1068 1069 1070
    }

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

1071 1072 1073 1074 1075 1076 1077
class ActivityTypeInstitutionmessage extends ActivityType {

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

1078 1079
    public function __construct($data, $cron=false) {
        parent::__construct($data, $cron);
1080
        if ($this->messagetype == 'request') {
1081
            $this->url = 'admin/users/institutionusers.php';
1082 1083
            $this->users = activity_get_users($this->get_id(), null, null, null,
                                              array($this->institution->name));
1084
            $this->add_urltext(array('key' => 'institutionmembers', 'section' => 'admin'));
1085
        } else if ($this->messagetype == 'invite') {
1086
            $this->url = 'account/institutions.php';
1087
            $this->users = activity_get_users($this->get_id(), $this->users);
1088
            $this->add_urltext(array('key' => 'institutionmembership', 'section' => 'mahara'));
1089 1090 1091
        }
    }

1092 1093 1094
    public function get_subject($user) {
        if ($this->messagetype == 'request') {
            $userstring = $this->fullname . ' (' . $this->username . ')';
Aaron Wells's avatar
Aaron Wells committed
1095
            return get_string_from_language($user->lang, 'institutionrequestsubject', 'activity', $userstring,
1096 1097
                                            $this->institution->displayname);
        } else if ($this->messagetype == 'invite') {
Aaron Wells's avatar
Aaron Wells committed
1098
            return get_string_from_language($user->lang, 'institutioninvitesubject', 'activity',
1099 1100 1101 1102 1103 1104
                                            $this->institution->displayname);
        }
    }

    public function get_message($user) {
        if ($this->messagetype == 'request') {
1105
            return $this->get_subject($user) .' '. get_string_from_language($user->lang, 'institutionrequestmessage', 'activity', $this->url);
1106
        } else if ($this->messagetype == 'invite') {
1107
            return $this->get_subject($user) .' '. get_string_from_language($user->lang, 'institutioninvitemessage', 'activity', $this->url);
1108 1109 1110
        }
    }

1111 1112 1113 1114 1115
    public function get_required_parameters() {
        return array('messagetype', 'institution');
    }
}

Aaron Wells's avatar
Aaron Wells committed
1116
class ActivityTypeUsermessage extends ActivityType {
1117 1118 1119 1120

    protected $userto;
    protected $userfrom;

1121 1122 1123 1124 1125 1126
    /**
     * @param array $data Parameters:
     *                    - userto (int)
     *                    - userfrom (int)
     *                    - subject (string)
     *                    - message (string)
Evan Goldenberg's avatar
Evan Goldenberg committed
1127
     *                    - parent (int)
1128
     */
Aaron Wells's avatar
Aaron Wells committed
1129
    public function __construct($data, $cron=false) {
1130
        parent::__construct($data, $cron);