group.php 109 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
 *
 */

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

14
// Constants for the different group roles
15
define ('GROUP_ROLES_NONE', 0);
16
17
18
19
define('GROUP_ROLES_ALL', 1);
define('GROUP_ROLES_NONMEMBER', 2);
define('GROUP_ROLES_ADMIN', 3);

20
21
22
23
24
// Constants for the different group roles
define('GROUP_HIDE_NONE', 0);
define('GROUP_HIDE_MEMBERS', 1);
define('GROUP_HIDE_TUTORS', 2);

25
// Role related functions
26

27
28
29
30
31
32
/**
 * Establishes what role a user has in a given group.
 *
 * If the user is not in the group, this returns false.
 *
 * @param mixed $groupid  ID of the group to check
Aaron Wells's avatar
Aaron Wells committed
33
 * @param mixed $userid   ID of the user to check. Defaults to the logged in
34
 *                        user.
Aaron Wells's avatar
Aaron Wells committed
35
 * @return mixed          The role the user has in the group, or false if they
36
37
 *                        have no role in the group
 */
38
function group_user_access($groupid, $userid=null, $refresh=null) {
39
    static $result;
40

41
    if (empty($userid) && !is_logged_in()) {
42
43
44
        return false;
    }

45
46
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);
47

48
    if (isset($result[$groupid][$userid]) && !isset($refresh)) {
49
50
51
52
        return $result[$groupid][$userid];
    }

    return $result[$groupid][$userid] = get_field('group_member', 'role', 'group', $groupid, 'member', $userid);
53
54
}

55
56
57
/**
 * Returns whether the given user is the only administrator in the given group.
 *
Aaron Wells's avatar
Aaron Wells committed
58
 * If the user isn't in the group, or they're not an admin, or there is another admin, false
59
60
 * is returned.
 *
61
62
 * @param int $groupid The ID of the group to check
 * @param int $userid  The ID of the user to check
63
64
 * @returns boolean
 */
65
function group_is_only_admin($groupid, $userid=null) {
66
    static $result;
67

68
69
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);
70

71
72
73
74
75
76
    if (isset($result[$groupid][$userid])) {
        return $result[$groupid][$userid];
    }

    return $result[$groupid][$userid] = (group_user_access($groupid, $userid) == 'admin'
        && count_records('group_member', 'group', $groupid, 'role', 'admin') == 1);
77
78
79
}

/**
Aaron Wells's avatar
Aaron Wells committed
80
 * Returns whether the given user is allowed to change their role to the
81
82
 * requested role in the given group.
 *
Aaron Wells's avatar
Aaron Wells committed
83
 * This function is checking whether _role changes_ are allowed, not if a user
84
85
 * is allowed to be added to a group.
 *
86
87
 * @param int $groupid The ID of the group to check
 * @param int $userid  The ID of the user to check
88
89
90
 * @param string $role The role the user wishes to switch to
 * @returns boolean
 */
91
function group_can_change_role($groupid, $userid, $role) {
92
93
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);
94
95

    if (!group_user_access($groupid, $userid)) {
96
97
98
99
        return false;
    }

    // Sole remaining admins can never change their role
100
    if (group_is_only_admin($groupid, $userid)) {
101
102
103
104
105
106
107
108
109
        return false;
    }

    return true;
}

/**
 * Changes a user role in a group, if this is allowed.
 *
110
111
 * @param int $groupid The ID of the group
 * @param int $userid  The ID of the user whose role needs changing
112
 * @param string $role The role the user wishes to switch to
Aaron Wells's avatar
Aaron Wells committed
113
114
 * @throws AccessDeniedException If the specified role change is not allowed.
 *                               Check with group_can_change_role first if you
115
116
 *                               need to.
 */
117
118
119
function group_change_role($groupid, $userid, $role) {
    // group_can_change_role checks whether the group and user parameters are valid
    if (!group_can_change_role($groupid, $userid, $role)) {
120
        throw new AccessDeniedException(get_string('usercannotchangetothisrole', 'group'));
121
122
    }

123
    set_field('group_member', 'role', $role, 'group', $groupid, 'member', $userid);
124

125
    $data = new stdClass();
126
127
128
129
130
131
132
133
134
135
    $data->user = $userid;
    $data->group = $groupid;
    $data->role = $role;
    handle_event('userchangegrouprole', array(
        'id' => $groupid,
        'eventfor' => 'group',
        'parentid' => $userid,
        'parenttype' => 'user',
        'rules' => $data)
    );
136
137
}

138
139
140
/**
 * Returns whether a user is allowed to edit views in a given group
 *
141
 * @param mixed $group The ID of the group
142
143
144
 * @param int $userid The ID of the user
 * @returns boolean
 */
145
function group_user_can_edit_views($group, $userid=null) {
146
147
148
149
150
151
    // root user can always do whatever it wants
    $sysuser = get_record('usr', 'username', 'root');
    if ($sysuser->id == $userid) {
        return true;
    }

152
    if (empty($userid) && !is_logged_in()) {
153
154
155
        return false;
    }

156
    $groupid = is_numeric($group) ? group_param_groupid($group) : intval($group->id);
157
    $userid  = group_param_userid($userid);
158

159
160
161
162
163
164
165
166
    if ($role = group_user_access($groupid, $userid)) {
        return group_role_can_edit_views($group, $role);
    }
    return false;
}

function group_role_can_edit_views($group, $role) {

167
168
169
170
    if (empty($role)) {
        return false;
    }

171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
    if ($role == 'admin') {
        return true;
    }

    if (is_numeric($group)) {
        $editroles = get_field('group', 'editroles', 'id', $group);
    }
    else if (!isset($group->editroles)) {
        $editroles = get_field('group', 'editroles', 'id', $group->id);
    }
    else {
        $editroles = $group->editroles;
    }

    if ($role == 'member') {
186
        return ($editroles == 'all' && group_within_edit_window($group));
187
188
189
    }

    return $editroles != 'admin';
190
191
}

192
193
194
195
196
197
198

/**
 * Determine if the current date/time is within the editable window of the
 * group if one is set. By default, a group admin is considered to be within
 * the window.
 * @param object $group the group to check
 * @param bool $admin_always whether the admin should be OK regardless of time
199
 * @param bool $tutor_always whether the tutor should be OK regardless of time
200
 */
201
function group_within_edit_window($group, $admin_always=true, $tutor_always=true) {
202
    if (is_numeric($group)) {
203
        $group = get_group_by_id($group, true);
204
205
206
    }

    if ($admin_always && group_user_access($group->id) == 'admin') {
207
208
209
210
211
        return true;
    }

    if ($tutor_always && group_user_access($group->id) == 'tutor') {
        return true;
212
213
214
215
216
217
218
219
220
221
222
223
    }

    $start = !empty($group->editwindowstart) ? strtotime($group->editwindowstart) : null;
    $end = !empty($group->editwindowend) ? strtotime($group->editwindowend) : null;
    $now = time();

    return (empty($start) && empty($end)) ||
        (!empty($start) && $now > $start && empty($end)) ||
        (empty($start) && $now < $end && !empty($end)) ||
        ($start < $now && $now < $end);
}

224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
function group_role_can_moderate_views($group, $role) {
    static $moderatingroles = array();

    if (empty($role)) {
        return false;
    }

    if ($role == 'admin') {
        return true;
    }

    if (!isset($moderatingroles[$group])) {
        $grouptype = get_field('group', 'grouptype', 'id', $group);
        safe_require('grouptype', $grouptype);
        $moderatingroles[$group] = call_static_method('GroupType' . ucfirst($grouptype), 'get_view_moderating_roles');
    }

    return in_array($role, $moderatingroles[$group]);
}

244
245
246
247
248
249
250
251
252
253
/**
 * Returns whether a user is allowed to see the report
 *
 * @param obj $group The group object
 * @param str $role The role of the user
 * @returns boolean
 */
function group_role_can_access_report($group, $role) {
    global $USER;

254
255
256
257
    if (!$group->groupparticipationreports) {
        return false;
    }

258
259
260
261
262
263
264
    if (group_user_access($group->id) && ($role == 'admin' || $USER->get('admin') || $USER->is_institutional_admin() || $USER->is_institutional_staff())) {
        return true;
    }

    return false;
}

265
/**
Aaron Wells's avatar
Aaron Wells committed
266
 * Returns whether a user is allowed to assess views that have been submitted
267
268
269
270
271
272
273
 * to the given group.
 *
 * @param int $groupid ID of group
 * @param int $userid  ID of user
 * @return boolean
 */
function group_user_can_assess_submitted_views($groupid, $userid) {
274
275
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);
276
277
278
279
280
281
282
283
284
285
286
287
288

    return get_field_sql('
        SELECT
            r.see_submitted_views
        FROM
            {group_member} m
            INNER JOIN {group} g ON (m.group = g.id AND g.deleted = 0)
            INNER JOIN {grouptype_roles} r ON (g.grouptype = r.grouptype AND r.role = m.role)
        WHERE
            m.member = ?
            AND m.group = ?', array($userid, $groupid));
}

289
290
// Functions for creation/deletion of groups, and adding/removing users to groups

291
292
293
/**
 * Creates a group.
 *
Aaron Wells's avatar
Aaron Wells committed
294
 * All group creation should be done through this function, as the
295
296
 * implementation of group creation may change over time.
 *
Aaron Wells's avatar
Aaron Wells committed
297
 * @param array $data Data required to create the group. The following
298
299
300
301
302
 * key/value pairs can be specified:
 *
 * - name: The group name [required, must be unique]
 * - description: The group description [optional, defaults to empty string]
 * - grouptype: The grouptype for the new group. Must be an installed grouptype.
303
304
305
 * - open (jointype): anyone can join the group
 * - controlled (jointype): admin adds members; members cannot leave the group
 * - request: allows membership requests
Aaron Wells's avatar
Aaron Wells committed
306
 * - ctime: The unix timestamp of the time the group will be recorded as having
307
308
309
310
311
312
313
 *          been created. Defaults to the current time.
 * - members: Array of users who should be in the group, structured like this:
 *            array(
 *                userid => role,
 *                userid => role,
 *                ...
 *            )
314
 * @return int The ID of the created group
315
316
317
318
319
 * @throws InvalidArgumentException
 *         UserException
 *         SystemException
 *         NotFoundException
 *         AccessDeniedException
320
321
322
323
324
325
326
327
328
329
 */
function group_create($data) {
    if (!is_array($data)) {
        throw new InvalidArgumentException("group_create: data must be an array, see the doc comment for this "
            . "function for details on its format");
    }

    if (!isset($data['name'])) {
        throw new InvalidArgumentException("group_create: must specify a name for the group");
    }
330
331
332
    if (get_records_sql_array('SELECT id FROM {group} WHERE LOWER(TRIM(name)) = ?', array(strtolower(trim($data['name']))))) {
        throw new UserException(get_string('groupalreadyexists', 'group') . ': ' . $data['name']);
    }
333
334
335
336
337

    if (!isset($data['grouptype']) || !in_array($data['grouptype'], group_get_grouptypes())) {
        throw new InvalidArgumentException("group_create: grouptype specified must be an installed grouptype");
    }

338
339
    safe_require('grouptype', $data['grouptype']);

340
341
342
343
344
345
    if (!empty($data['open'])) {
        if (!empty($data['controlled'])) {
            throw new InvalidArgumentException("group_create: a group cannot have both open and controlled membership");
        }
        if (!empty($data['request'])) {
            throw new InvalidArgumentException("group_create: open-membership groups don't accept membership requests");
346
        }
347
348
349
350
        $jointype = 'open';
    }
    else if (!empty($data['controlled'])) {
        $jointype = 'controlled';
351
352
    }
    else {
353
354
355
356
357
        $jointype = 'approve';
    }

    if (isset($data['jointype'])) {
        log_warn("group_create: ignoring supplied jointype");
358
359
360
361
362
363
364
    }

    if (!isset($data['ctime'])) {
        $data['ctime'] = time();
    }
    $data['ctime'] = db_format_timestamp($data['ctime']);

365
    $data['public'] = (isset($data['public'])) ? intval($data['public']) : 0;
366
    $data['hidden'] = (isset($data['hidden'])) ? intval($data['hidden']) : 0;
367
    $data['hidemembers'] = (isset($data['hidemembers'])) ? intval($data['hidemembers']) : 0;
368
    $data['hidemembersfrommembers'] = (isset($data['hidemembersfrommembers'])) ? intval($data['hidemembersfrommembers']) : 0;
369
    $data['groupparticipationreports'] = (isset($data['groupparticipationreports'])) ? intval($data['groupparticipationreports']) : 0;
370
    $data['usersautoadded'] = (isset($data['usersautoadded'])) ? intval($data['usersautoadded']) : 0;
371

Hugh Davenport's avatar
Hugh Davenport committed
372
373
    $data['quota'] = get_config_plugin('artefact', 'file', 'defaultgroupquota');

374
375
376
377
378
379
    if (!empty($data['invitefriends']) && !empty($data['suggestfriends'])) {
        throw new InvalidArgumentException("group_create: a group cannot enable both invitefriends and suggestfriends");
    }
    $data['invitefriends'] = (isset($data['invitefriends'])) ? intval($data['invitefriends']) : 0;
    $data['suggestfriends'] = (isset($data['suggestfriends'])) ? intval($data['suggestfriends']) : 0;

380
381
    if (!empty($data['shortname'])) {
        // make sure it is unique and is correct length
382
        $shortname = group_generate_shortname($data['shortname']);
383
384
385
        // If we want to retain the supplied shortname we need to make sure it can be done
        if (!empty($data['retainshortname'])) {
            if ($shortname != $data['shortname']) {
386
387
388
389
390
391
                if ($shortname == strtolower($data['shortname'])) {
                    throw new UserException('group_create: The supplied short name \'' . $data['shortname'] .
                        '\' needs to be lowercase, eg \'' . $shortname . '\'.');
                }
                else {
                    throw new UserException('group_create: The supplied short name \'' . $data['shortname'] .
392
                        '\' is already taken. This shortname \'' . $shortname . '\' is available.');
393
                }
394
395
396
397
398
399
400
401
            }
        }
        $data['shortname'] = $shortname;
    }
    else {
        // Create it from group name
        $data['shortname'] = group_generate_shortname($data['name']);
    }
402

403
    if (!empty($data['institution']) && $data['institution'] != 'mahara') {
404
        global $USER;
405
406
        if (!$USER->can_edit_institution($data['institution'], true)) {
            $data['institution'] = 'mahara';
407
408
409
        }
    }
    else {
410
        $data['institution'] = 'mahara';
411
412
    }

413
414
415
416
417
    if (get_config('cleanurls') && (!isset($data['urlid']) || strlen($data['urlid']) == 0)) {
        $data['urlid'] = generate_urlid($data['name'], get_config('cleanurlgroupdefault'), 3, 30);
        $data['urlid'] = group_get_new_homepage_urlid($data['urlid']);
    }

418
419
    // Need to make sure group has at least one member
    if (empty($data['members'])) {
420
        global $USER;
421
        $data['members'] = array($USER->get('id') => 'admin');
422
423
    }

424
425
426
427
    if (!isset($data['submittableto'])) {
        $data['submittableto'] = $data['grouptype'] != 'standard';
    }

428
429
430
431
432
433
434
    if (!isset($data['editroles'])) {
        $data['editroles'] = $data['grouptype'] == 'standard' ? 'all' : 'notmember';
    }
    else if (!in_array($data['editroles'], array_keys(group_get_editroles_options()))) {
        throw new InvalidArgumentException("group_create: invalid option for page editroles setting");
    }

435
436
437
438
439
440
    if (!isset($data['editwindowstart'])) {
        $data['editwindowstart'] = null;
    }
    if (!isset($data['editwindowend'])) {
        $data['editwindowend'] = null;
    }
441
442
443
    if (!isset($data['sendnow'])) {
        $data['sendnow'] = null;
    }
444

445
446
447
448
449
    db_begin();

    $id = insert_record(
        'group',
        (object) array(
450
            'name'           => $data['name'],
451
            'description'    => isset($data['description']) ? $data['description'] : null,
452
            'urlid'          => isset($data['urlid']) ? $data['urlid'] : null,
453
            'grouptype'      => $data['grouptype'],
454
            'category'       => isset($data['category']) && !empty($data['category']) ? intval($data['category']) : null,
455
            'jointype'       => $jointype,
456
457
458
459
            'ctime'          => $data['ctime'],
            'mtime'          => $data['ctime'],
            'public'         => $data['public'],
            'usersautoadded' => $data['usersautoadded'],
Hugh Davenport's avatar
Hugh Davenport committed
460
            'quota'          => $data['quota'],
461
462
            'institution'    => !empty($data['institution']) ? $data['institution'] : null,
            'shortname'      => $data['shortname'],
463
            'request'        => isset($data['request']) ? intval($data['request']) : 0,
464
            'submittableto'  => intval($data['submittableto']),
465
            'allowarchives'  => (!empty($data['submittableto']) && !empty($data['allowarchives'])) ? intval($data['allowarchives']) : 0,
466
            'editroles'      => $data['editroles'],
467
            'hidden'         => $data['hidden'],
468
            'hidemembers'    => $data['hidemembers'],
469
            'hidemembersfrommembers' => $data['hidemembersfrommembers'],
470
            'groupparticipationreports' => $data['groupparticipationreports'],
471
472
            'invitefriends'  => $data['invitefriends'],
            'suggestfriends' => $data['suggestfriends'],
473
            'editwindowstart' => $data['editwindowstart'],
474
            'editwindowend'  => $data['editwindowend'],
475
            'sendnow'        => isset($data['sendnow']) ? $data['sendnow'] : null,
476
            'viewnotify'     => !empty($data['viewnotify']) ? $data['viewnotify'] : null,
477
            'feedbacknotify' => isset($data['feedbacknotify']) ? $data['feedbacknotify'] : null,
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
        ),
        'id',
        true
    );

    foreach ($data['members'] as $userid => $role) {
        insert_record(
            'group_member',
            (object) array(
                'group'  => $id,
                'member' => $userid,
                'role'   => $role,
                'ctime'  => $data['ctime'],
            )
        );
    }

Richard Mansfield's avatar
Richard Mansfield committed
495
    // Copy views for the new group
496
    $artefactcopies = array();
497
    $templates = get_records_sql_array("
498
        SELECT v.id, v.title, v.description
499
500
        FROM {view} v
        INNER JOIN {view_autocreate_grouptype} vag ON vag.view = v.id
501
502
503
        LEFT JOIN {collection_view} cv ON v.id = cv.view
        WHERE vag.grouptype = 'standard'
            AND cv.view IS NULL", array());
Richard Mansfield's avatar
Richard Mansfield committed
504
505
    if ($templates) {
        require_once(get_config('libroot') . 'view.php');
506
507
        foreach ($templates as $template) {
            list($view) = View::create_from_template(array(
Richard Mansfield's avatar
Richard Mansfield committed
508
                'group'       => $id,
509
510
                'title'       => $template->title,
                'description' => $template->description,
511
            ), $template->id, null, false, false, $artefactcopies);
512
            $view->set_access(array(array(
Richard Mansfield's avatar
Richard Mansfield committed
513
514
515
516
517
518
519
520
                'type'      => 'group',
                'id'        => $id,
                'startdate' => null,
                'stopdate'  => null,
                'role'      => null
            )));
        }
    }
521
522
    // Copy collections for the new group
    $templates = get_records_sql_array("
523
        SELECT DISTINCT c.id, c.name
524
525
526
527
528
529
530
531
        FROM {view} v
        INNER JOIN {view_autocreate_grouptype} vag ON vag.view = v.id
        INNER JOIN {collection_view} cv ON v.id = cv.view
        INNER JOIN {collection} c ON cv.collection = c.id
        WHERE vag.grouptype = ?", array($data['grouptype']));
    if ($templates) {
        require_once('collection.php');
        foreach ($templates as $template) {
532
            Collection::create_from_template(array('group' => $id), $template->id, null, false, true);
533
534
        }
    }
Richard Mansfield's avatar
Richard Mansfield committed
535
    $data['id'] = $id;
536
    // install the homepage
537
538
    require_once('view.php');
    if ($t = get_record('view', 'type', 'grouphomepage', 'template', View::SITE_TEMPLATE, 'institution', 'mahara')) {
539
        $template = new View($t->id, (array)$t);
540
        list($homepage) = View::create_from_template(array(
541
542
543
544
            'group' => $id,
            'title' => $template->get('title'),
            'description' => $template->get('description'),
            'type' => 'grouphomepage',
545
        ), $t->id, 0, false, false, $artefactcopies);
546
    }
547
548
549
    else {
        throw new NotFoundException("group_create: group homepage is not found");
    }
550

551
    // If 'Allow submissions' is true we need to update the 'Group portfolios' block to show
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
    // the 'Submissions to this group' section by default
    if ($data['submittableto']) {
        $groupview = get_record_sql("SELECT bi.id, bi.configdata
                                     FROM {block_instance} bi
                                     INNER JOIN {view} v ON v.id = bi.view
                                     WHERE bi.blocktype = 'groupviews'
                                     AND v.id = ?", array($homepage->get('id')));
        if ($groupview) {
            $configdata = unserialize($groupview->configdata);
            if (!isset($configdata['showsubmitted'])) {
                $configdata['showsubmitted'] = 1;
                set_field('block_instance', 'configdata', serialize($configdata), 'id', $groupview->id);
            }
        }
    }
567
    $newaccess = (object) array(
568
        'view'       => $homepage->get('id'),
569
        'accesstype' => $data['public'] ? 'public' : 'loggedin',
570
        'ctime'      => db_format_timestamp(time()),
571
    );
572
573
574
575
576
577
578
579
    $vaid = insert_record('view_access', $newaccess, 'id', true);
    handle_event('updateviewaccess', array(
        'id' => $vaid,
        'eventfor' => $data['public'] ? 'public' : 'loggedin',
        'parentid' => $homepage->get('id'),
        'parenttype' => 'view',
        'rules' => $newaccess)
    );
Richard Mansfield's avatar
Richard Mansfield committed
580
    handle_event('creategroup', $data);
581
    db_commit();
582
583

    return $id;
584
585
}

586

587
588
589
590
591
592
593
594
595
596
597
/**
 * Update details of an existing group.
 *
 * @param array $new New values for the group table.
 * @param bool  $create Create the group if it doesn't exist yet
 */
function group_update($new, $create=false) {

    if (!empty($new->id)) {
        $old = get_record_select('group', 'id = ? AND deleted = 0', array($new->id));
    }
598
    else if (!empty($new->shortname)) {
599
600
        $old = get_record_select(
            'group',
601
602
            'shortname = ? AND deleted = 0',
            array($new->shortname)
603
        );
604

605
606
607
608
609
610
611
612
613
        if (!$old && $create) {
            return group_create((array)$new);
        }
    }

    if (!$old) {
        throw new NotFoundException("group_update: group not found");
    }

614
615
616
617
618
619
    if (
        (isset($new->submittableto) && empty($new->submittableto)) ||
        (!isset($new->submittableto) && empty($old->submittableto))
       ) {
        $new->allowarchives = 0;
    }
620

621
622
    $update_blog_access = ($new->editroles != $old->editroles);

623
    foreach (array('id', 'grouptype', 'public', 'request', 'submittableto', 'allowarchives', 'editroles',
624
        'hidden', 'hidemembers', 'hidemembersfrommembers', 'groupparticipationreports') as $f) {
625
626
627
628
        if (!isset($new->$f)) {
            $new->$f = $old->$f;
        }
    }
629

630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
    if (isset($new->jointype)) {
        log_warn("group_update: ignoring supplied jointype");
        unset($new->jointype);
    }

    // If the caller isn't trying to enable open/controlled, use the old values
    if (!isset($new->open)) {
        $new->open = empty($new->controlled) && $old->jointype == 'open';
    }
    if (!isset($new->controlled)) {
        $new->controlled = empty($new->open) && $old->jointype == 'controlled';
    }

    if ($new->open) {
        if ($new->controlled) {
            throw new InvalidArgumentException("group_update: a group cannot have both open and controlled membership");
        }
        $new->request = 0;
        $new->jointype = 'open';
    }
    else if ($new->controlled) {
        $new->jointype = 'controlled';
    }
    else {
        $new->jointype = 'approve';
    }

    unset($new->open);
    unset($new->controlled);

660
661
662
663
664
665
666
667
668
669
670
    // Ensure only one of invitefriends,suggestfriends gets enabled.
    if (!empty($new->invitefriends)) {
        $new->suggestfriends = 0;
    }
    else if (!isset($new->invitefriends)) {
        $new->invitefriends = (int) ($old->invitefriends && empty($new->suggestfriends));
    }
    if (!isset($new->suggestfriends)) {
        $new->suggestfriends = $old->suggestfriends;
    }

671
672
673
674
675
    $diff = array_diff_assoc((array)$new, (array)$old);
    if (empty($diff)) {
        return null;
    }

676
677
    db_begin();

678
679
680
681
682
    if (isset($new->members)) {
        group_update_members($new->id, $new->members);
        unset($new->members);
    }

683
684
    $new->mtime = db_format_timestamp(time());

685
686
    update_record('group', $new, 'id');

687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
    // Add users who have requested membership of a group that's becoming
    // open
    if ($old->jointype != 'open' && $new->jointype == 'open') {
        $userids = get_column_sql('
            SELECT u.id
            FROM {usr} u JOIN {group_member_request} r ON u.id = r.member
            WHERE r.group = ? AND u.deleted = 0',
            array($new->id)
        );
        if ($userids) {
            foreach ($userids as $uid) {
                group_add_user($new->id, $uid);
            }
        }
    }
702

703
704
705
706
    // Invitations to controlled groups are allowed, but if the admin is
    // changing a group to controlled membership, we'll assume they want
    // want to revoke all the existing invitations.
    if ($old->jointype != 'controlled' && $new->jointype == 'controlled') {
707
708
        delete_records('group_member_invite', 'group', $new->id);
    }
709
710
711
712

    // Remove requests
    if ($old->request && !$new->request) {
        delete_records('group_member_request', 'group', $new->id);
713
714
    }

715
    // When the group type changes, make sure everyone has a valid role.
716
717
    safe_require('grouptype', $new->grouptype);
    $allowedroles = call_static_method('GroupType' . ucfirst($new->grouptype), 'get_roles');
718
719
720
721
722
    set_field_select(
        'group_member', 'role', 'member',
        '"group" = ? AND NOT role IN (' . join(',', array_fill(0, count($allowedroles), '?')) . ')',
        array_merge(array($new->id), $allowedroles)
    );
723

724
725
726
727
    // When the group type changes, make sure the access for tutors
    // to the group artefacts are updated
    if ($old->grouptype != $new->grouptype) {
        if ($new->grouptype == 'course') {
728
            if ($ids = get_records_select_array('artefact',
729
                      '"group" = ' . $new->id . ' AND artefacttype IN (\'blog\', \'blogpost\')',
730
731
732
733
734
735
736
737
738
739
740
741
742
                      null, '', 'id')) {
                $access = ($old->editroles == 'all' || $old->editroles == 'notmember');
                db_begin();
                foreach ($ids as $i => $artefact) {
                    insert_record('artefact_access_role', (object) array(
                        'artefact'      => $artefact->id,
                        'role'          => 'tutor',
                        'can_view'      => 1,
                        'can_edit'      => (int) $access,
                        'can_republish' => (int) $access,
                    ));
                }
                db_commit();
743
744
745
746
747
748
749
750
751
752
753
754
755
756
            }
        }
        else { //grouptype = standard
            $query = 'DELETE FROM {artefact_access_role}
                      WHERE role = \'tutor\'
                      AND  artefact IN (
                          SELECT a.id FROM {artefact} a
                          WHERE a.group = ?
                          AND a.artefacttype IN (\'blog\', \'blogpost\')
                      )';
            execute_sql($query, array($new->id));
        }
    }

757
758
    // When a group changes from public -> private or vice versa, set the
    // appropriate access permissions on the group homepage view.
759
    $homepageid = get_field('view', 'id', 'type', 'grouphomepage', 'group', $new->id);
760
761
762
    if ($old->public != $new->public) {
        if ($old->public && !$new->public) {
            delete_records('view_access', 'view', $homepageid, 'accesstype', 'public');
763
            $newaccess = (object) array(
764
765
766
                'view'       => $homepageid,
                'accesstype' => 'loggedin',
                'ctime'      => db_format_timestamp(time()),
767
            );
768
769
770
771
772
773
774
775
            $vaid = insert_record('view_access', $newaccess, 'id', true);
            handle_event('updateviewaccess', array(
                'id' => $vaid,
                'eventfor' => 'loggedin',
                'parentid' => $homepageid,
                'parenttype' => 'view',
                'rules' => $newaccess)
            );
776
777
778
        }
        else if (!$old->public && $new->public) {
            delete_records('view_access', 'view', $homepageid, 'accesstype', 'loggedin');
779
            $newaccess = (object) array(
780
781
782
                'view'       => $homepageid,
                'accesstype' => 'public',
                'ctime'      => db_format_timestamp(time()),
783
            );
784
785
786
787
788
789
790
791
            $vaid = insert_record('view_access', $newaccess, 'id', true);
            handle_event('updateviewaccess', array(
                'id' => $vaid,
                'eventfor' => 'public',
                'parentid' => $homepageid,
                'parenttype' => 'view',
                'rules' => $newaccess)
            );
792
793
794
        }
    }

795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
    // When the create/edit permissions change, update permissions on journal and posts
    if ($update_blog_access) {
        $edit_access = array();
        if ($old->editroles == 'all') {
            $edit_access['member'] = 0;
        }
        else if ($old->editroles == 'admin') {
            $edit_access['tutor'] = 1;
        }
        if ($new->editroles == 'all') {
            $edit_access['member'] = 1;
        }
        else if ($new->editroles == 'admin') {
            $edit_access['tutor'] = 0;
        }

        foreach ($edit_access as $role => $value) {
            $query = 'UPDATE {artefact_access_role}
                      SET can_edit = ?, can_republish = ?
                      WHERE role = \'' . $role . '\'
                      AND artefact IN (
                          SELECT a.id FROM {artefact} a
                          WHERE a.group = ?
                          AND a.artefacttype IN (\'blog\', \'blogpost\')
                      )';
            execute_sql($query, array($value, $value, $new->id));
        }
    }

824
    // If 'Allow submissions' is changed we need to update the 'Group portfolios' block
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
    // to reflect the change
    $cansubmitto = 0;
    if (isset($new->submittableto) && !empty($new->submittableto)) {
        $cansubmitto = 1;
    }
    $groupview = get_record_sql("SELECT bi.id, bi.configdata
                                 FROM {block_instance} bi
                                 INNER JOIN {view} v ON v.id = bi.view
                                 WHERE bi.blocktype = 'groupviews'
                                 AND v.id = ?", array($homepageid));
    if ($groupview) {
        $configdata = unserialize($groupview->configdata);
        $configdata['showsubmitted'] = $cansubmitto;
        set_field('block_instance', 'configdata', serialize($configdata), 'id', $groupview->id);
    }

841
842
    db_commit();

843
    return $diff;
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
/**
 * Fetch group records from the db and convert them to a format suitable
 * for passing into group_update().
 *
 * @param array $ids List of group ids
 *
 * @return array of stdclass objects
 */
function group_get_groups_for_editing($ids=null) {
    if (empty($ids)) {
        return array();
    }

    $ids = array_map('intval', $ids);
    $groups = get_records_select_array(
        'group',
        'id IN (' . join(',', array_fill(0, count($ids), '?')) . ') AND deleted = 0',
        $ids
    );

    if (!$groups) {
        return array();
    }

    foreach ($groups as &$g) {
        $g->open       = (int) ($g->jointype == 'open');
        $g->controlled = (int) ($g->jointype == 'controlled');
        unset($g->jointype);
    }

    return $groups;
}
878

879
880
881
/**
 * Deletes a group.
 *
Aaron Wells's avatar
Aaron Wells committed
882
 * All group deleting should be done through this function, even though it is
883
884
885
 * simple. What is required to perform group deletion may change over time.
 *
 * @param int $groupid The group to delete
886
887
 * @param string $shortname   shortname of the group
 * @param string $institution institution of the group
888
 *
Aaron Wells's avatar
Aaron Wells committed
889
 * {{@internal Maybe later we can have a group_can_be_deleted function if
890
891
 * necessary}}
 */
892
function group_delete($groupid, $shortname=null, $institution=null, $notifymembers=true) {
893
894
    global $USER;

895
896
897
898
899
    if (empty($groupid) && !empty($institution) && !is_null($shortname) && strlen($shortname)) {
        // External call to delete a group, check permission of $USER.
        if (!$USER->can_edit_institution($institution)) {
            throw new AccessDeniedException("group_delete: cannot delete a group in this institution");
        }
900
901
902
903
904

        $group = get_record('group', 'shortname', $shortname, 'institution', $institution);
    }
    else {
        $groupid = group_param_groupid($groupid);
905
        $group = get_group_by_id($groupid, true);
906
907
    }

908
909
910
911
912
913
914
    db_begin();
    // Leave the group_member table alone, it's needed for the deleted
    // group notification that's about to happen on cron.
    delete_records('group_member_invite', 'group', $group->id);
    delete_records('group_member_request', 'group', $group->id);
    delete_records('view_access', 'group', $group->id);

915
916
917
918
    // Delete embedded images in the group description
    require_once('embeddedimage.php');
    EmbeddedImage::delete_embedded_images('group', $group->id);

919
920
921
922
923
924
925
    // Delete views owned by the group
    require_once(get_config('libroot') . 'view.php');
    foreach (get_column('view', 'id', 'group', $group->id) as $viewid) {
        $view = new View($viewid);
        $view->delete();
    }

926
927
928
929
930
931
932
    // Release collections submitted to the group
    require_once(get_config('libroot') . 'collection.php');
    foreach (get_column('collection', 'id', 'submittedgroup', $group->id) as $collectionid) {
        $collection = new Collection($collectionid);
        $collection->release();
    }

933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
    // Release views submitted to the group
    foreach (get_column('view', 'id', 'submittedgroup', $group->id) as $viewid) {
        $view = new View($viewid);
        $view->release();
    }

    // Delete artefacts
    require_once(get_config('docroot') . 'artefact/lib.php');
    ArtefactType::delete_by_artefacttype(get_column('artefact', 'id', 'group', $group->id));

    // Delete forums
    require_once(get_config('docroot') . 'interaction/lib.php');
    foreach (get_column('interaction_instance', 'id', 'group', $group->id) as $forumid) {
        $forum = interaction_instance_from_id($forumid);
        $forum->delete();
    }

950
951
952
953
954
955
956
957
    // Delete lti submissions to the group if they exist
    if (is_plugin_active('lti', 'module')) {
        foreach (get_column('lti_assessment', 'id', 'group', $group->id) as $assessmentid) {
            delete_records('lti_assessment_submission', 'ltiassessment', $assessmentid);
        }
        delete_records('lti_assessment', 'group', $group->id);
    }

958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
    if ($notifymembers) {
        require_once('activity.php');
        activity_occurred('groupmessage', array(
            'group'         => $group->id,
            'deletedgroup'  => true,
            'strings'       => (object) array(
                'subject' => (object) array(
                    'key'     => 'deletegroupnotificationsubject',
                    'section' => 'group',
                    'args'    => array(hsc($group->name)),
                ),
                'message' => (object) array(
                    'key'     => 'deletegroupnotificationmessage',
                    'section' => 'group',
                    'args'    => array(hsc($group->name), get_config('sitename')),
                ),
            ),
        ));
976
    }
977
978
979
980
981
    // make sure the group name + deleted suffix will fit within 128 chars
    $delete_name = $group->name;
    if (strlen($delete_name) > 100) {
        $delete_name = substr($delete_name, 0, 100) . '(...)';
    }
982
983
984
    update_record('group',
        array(
            'deleted' => 1,
985
            'name' => $delete_name . '.deleted.' . time(),
986
987
            'shortname' => null,
            'institution' => null,
988
            'category' => null,
989
            'urlid' => null,
990
            'mtime' => db_format_timestamp(time()),
991
992
        ),
        array(
993
            'id' => $group->id,
994
995
        )
    );
996
    db_commit();
997
998
999
    // Need to reset grouproles - normally done via group_remove_user() but we don't call
    // it due to notification reasons (see above)
    $USER->reset_grouproles();
1000
1001
}

1002
/**
1003
1004
1005
1006
1007
 * Adds a member to a group.
 *
 * Doesn't do any jointype checking, that should be handled by the caller.
 *
 * TODO: it should though. We should probably have group_user_can_be_added
1008
 *
1009
 * @param int $groupid
1010
 * @param int $userid
Richard Mansfield's avatar
Richard Mansfield committed
1011
 * @param string $role
1012
 */
1013
function group_add_user($groupid, $userid, $role=null, $method='internal') {
1014
1015
1016
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);

1017
    $gm = new stdClass();
1018
1019
1020
    $gm->member = $userid;
    $gm->group = $groupid;
    $gm->ctime =  db_format_timestamp(time());
Richard Mansfield's avatar
Richard Mansfield committed
1021
1022
1023
    if (!$role) {
        $role = get_field_sql('SELECT gt.defaultrole FROM {grouptype} gt, {group} g WHERE g.id = ? AND g.grouptype = gt.name', array($groupid));
    }
1024
    $gm->role = $role;
1025
    $gm->method = $method;
1026
1027

    db_begin();
1028
    insert_record('group_member', $gm);
1029
    delete_records('group_member_request', 'group', $groupid, 'member', $userid);
1030
    delete_records('group_member_invite', 'group', $groupid, 'member', $userid);
1031
1032
1033

    $gm->id = $gm->group;
    $gm->eventfor = 'group';
1034
    handle_event('userjoinsgroup', $gm);
1035
    db_commit();
1036
1037
    global $USER;
    $USER->reset_grouproles();
1038
1039
}

1040
1041
1042
1043
1044
1045
1046
1047
1048
/**
 * Checks whether a user is allowed to leave a group.
 *
 * This checks things like if they're the owner and the group membership type
 *
 * @param mixed $group  DB record or ID of group to check
 * @param int   $userid (optional, will default to logged in user)
 */
function group_user_can_leave($group, $userid=null) {
1049
    global $USER;
1050
1051
1052
1053
1054
    static $result;

    $userid = optional_userid($userid);

    if (is_numeric($group)) {
1055
        if (!$group = get_group_by_id($group)) {
1056
1057
1058
1059
1060
1061
1062
1063
1064
            return false;
        }
    }

    // Return cached value if we have it
    if (isset($result[$group->id][$userid])) {
        return $result[$group->id][$userid];
    }

1065
    if ($group->jointype == 'controlled' && group_user_access($group->id, $USER->get('id')) != 'admin') {
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
        return ($result[$group->id][$userid] = false);
    }

    if (group_is_only_admin($group->id, $userid)) {
        return ($result[$group->id][$userid] = false);
    }

    return ($result[$group->id][$userid] = true);
}

1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
/**
 * Checks whether a user is allowed to change the group's configuration settings.
 * (via edit/group.php)
 *
 * @param int $groupid Group to check
 * @param int $userid User to check (default: current user)
 * @param boolean $refresh Whether to re-check the user's role in the database (default: false)
 */
function group_user_can_configure($groupid, $userid = null, $refresh = false) {

    if ('admin' === group_user_access($groupid, $userid, $refresh)) {
        return true;
    }
    else {
        return false;
    }
}

1094
/**
1095
 * Removes a user from a group.
1096
 *
1097
1098
 * @param int $groupid ID of group
 * @param int $userid  ID of user to remove
1099
 */
1100
function group_remove_user($groupid, $userid=null, $force=false) {
1101
    // group_user_can_leave checks the validity of groupid and userid
1102
    if (!$force && !group_user_can_leave($groupid, $userid)) {
1103
1104
        throw new AccessDeniedException(get_string('usercantleavegroup', 'group'));
    }
1105
    $data = new stdClass();
1106
1107
1108
1109
    $data->user = $userid;
    $data->group = $groupid;
    $data->role = get_field('group_member', 'role', 'group', $groupid, 'member', $userid);
    handle_event('userleavesgroup', $data);
1110
    delete_records('group_member', 'group', $groupid, 'member', $userid);
1111

1112
1113
1114
    global $USER;
    $USER->reset_grouproles();

1115
    require_once(get_config('docroot') . 'interaction/lib.php');
1116
    $interactions = get_column('interaction_instance', 'id', 'group', $groupid);
1117
1118
1119
1120
1121
    foreach ($interactions as $interaction) {
        interaction_instance_from_id($interaction)->interaction_remove_user($userid);
    }
}

1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
/**
 * Completely update the membership of a group
 *
 * @param int $groupid ID of group
 * @param array $members list of members and roles, structured like this:
 *            array(
 *                userid => role,
 *                userid => role,
 *                ...
 *            )
1132
1133
1134
 * @param lines_done Number of lines in the file that have been completed so far
 * @param num_lines Number of lines in the file (this and the previous values
 *  are used to update the progress meter.
1135
 */
1136
function group_update_members($groupid, $members, $lines_done = 0, $num_lines = 0) {
1137
1138
1139
1140
    global $USER;

    $groupid = group_param_groupid($groupid);

1141
    if (!$group = get_group_by_id($groupid)) {
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
        throw new NotFoundException("group_update_members: group not found: $groupid");
    }

    if (($group->institution && !$USER->can_edit_institution($group->institution))
        || (!$group->institution && !$USER->get('admin'))) {
        throw new AccessDeniedException("group_update_members: access denied");
    }

    if (!is_array($members)) {
        throw new SystemException("group_update_members: members must be an array");
    }

    $badroles = array_unique(array_diff($members, array_keys(group_get_role_info($groupid))));

    if (!empty($badroles)) {
        throw new UserException("group_update_members: invalid role(s) specified for group $group->name (id $groupid): " . join(', ', $badroles));
    }

    if (!in_array('admin', $members)) {
        $groupname = get_field('group', 'name', 'id', $groupid);
        throw new UserException("group_update_members: no group admins listed for group $group->name (id $groupid)");
    }

    // Check the new members list for invalid users

    if (!empty($members)) {
        $userids = array_map('intval', array_keys($members));
1169
        if ($group->institution && $group->institution != 'mahara') {
1170
1171
1172
1173
1174
1175
            $gooduserids = get_column_sql('
                SELECT usr
                FROM {usr_institution}
                WHERE usr IN (' . join(',', $userids) . ') AND institution = ?',
                array($group->institution)
            );
1176

1177
            if ($baduserids = array_diff($userids, $gooduserids)) {
1178
1179
1180
                if (!(count($baduserids) == 1 && $baduserids[0] == $USER->id)) {
                    throw new UserException("group_update_members: some members are not in the institution $group->institution: " . join(',', $baduserids));
                }
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
            }
        }
        else {
            $gooduserids = get_column_sql('
                SELECT id FROM {usr} WHERE id IN (' . join(',', $userids) . ') AND deleted = 0',
                array()</