group.php 85.2 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
15
16
17
18
// Constants for the different group roles
define('GROUP_ROLES_ALL', 1);
define('GROUP_ROLES_NONMEMBER', 2);
define('GROUP_ROLES_ADMIN', 3);

19
// Role related functions
20

21
22
23
24
25
26
/**
 * 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
27
 * @param mixed $userid   ID of the user to check. Defaults to the logged in
28
 *                        user.
Aaron Wells's avatar
Aaron Wells committed
29
 * @return mixed          The role the user has in the group, or false if they
30
31
 *                        have no role in the group
 */
32
function group_user_access($groupid, $userid=null, $refresh=null) {
33
    static $result;
34

35
    if (empty($userid) && !is_logged_in()) {
36
37
38
        return false;
    }

39
40
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);
41

42
    if (isset($result[$groupid][$userid]) && !isset($refresh)) {
43
44
45
46
        return $result[$groupid][$userid];
    }

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

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

62
63
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);
64

65
66
67
68
69
70
    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);
71
72
73
}

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

    if (!group_user_access($groupid, $userid)) {
90
91
92
93
        return false;
    }

    // Sole remaining admins can never change their role
94
    if (group_is_only_admin($groupid, $userid)) {
95
96
97
98
99
100
101
102
103
        return false;
    }

    return true;
}

/**
 * Changes a user role in a group, if this is allowed.
 *
104
105
 * @param int $groupid The ID of the group
 * @param int $userid  The ID of the user whose role needs changing
106
 * @param string $role The role the user wishes to switch to
Aaron Wells's avatar
Aaron Wells committed
107
108
 * @throws AccessDeniedException If the specified role change is not allowed.
 *                               Check with group_can_change_role first if you
109
110
 *                               need to.
 */
111
112
113
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)) {
114
        throw new AccessDeniedException(get_string('usercannotchangetothisrole', 'group'));
115
116
    }

117
    set_field('group_member', 'role', $role, 'group', $groupid, 'member', $userid);
118
119
}

120
121
122
/**
 * Returns whether a user is allowed to edit views in a given group
 *
123
 * @param mixed $group The ID of the group
124
125
126
 * @param int $userid The ID of the user
 * @returns boolean
 */
127
function group_user_can_edit_views($group, $userid=null) {
128
129
130
131
132
133
    // root user can always do whatever it wants
    $sysuser = get_record('usr', 'username', 'root');
    if ($sysuser->id == $userid) {
        return true;
    }

134
    if (empty($userid) && !is_logged_in()) {
135
136
137
        return false;
    }

138
    $groupid = is_numeric($group) ? group_param_groupid($group) : intval($group->id);
139
    $userid  = group_param_userid($userid);
140

141
142
143
144
145
146
147
148
    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) {

149
150
151
152
    if (empty($role)) {
        return false;
    }

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    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') {
168
        return ($editroles == 'all' && group_within_edit_window($group));
169
170
171
    }

    return $editroles != 'admin';
172
173
}

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

/**
 * 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
 */
function group_within_edit_window($group, $admin_always=true) {
    if (is_numeric($group)) {
        $group = get_record('group', 'id', $group);
    }

    if ($admin_always && group_user_access($group->id) == 'admin') {
      return true;
    }

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

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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]);
}

221
222
223
224
225
226
227
228
229
230
/**
 * 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;

231
232
233
234
    if (!$group->groupparticipationreports) {
        return false;
    }

235
236
237
238
239
240
241
    if (group_user_access($group->id) && ($role == 'admin' || $USER->get('admin') || $USER->is_institutional_admin() || $USER->is_institutional_staff())) {
        return true;
    }

    return false;
}

242
/**
Aaron Wells's avatar
Aaron Wells committed
243
 * Returns whether a user is allowed to assess views that have been submitted
244
245
246
247
248
249
250
 * 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) {
251
252
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);
253
254
255
256
257
258
259
260
261
262
263
264
265

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

266
267
// Functions for creation/deletion of groups, and adding/removing users to groups

268
269
270
/**
 * Creates a group.
 *
Aaron Wells's avatar
Aaron Wells committed
271
 * All group creation should be done through this function, as the
272
273
 * implementation of group creation may change over time.
 *
Aaron Wells's avatar
Aaron Wells committed
274
 * @param array $data Data required to create the group. The following
275
276
277
278
279
 * 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.
280
281
282
 * - 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
283
 * - ctime: The unix timestamp of the time the group will be recorded as having
284
285
286
287
288
289
290
 *          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,
 *                ...
 *            )
291
 * @return int The ID of the created group
292
293
294
295
296
297
298
299
300
301
 */
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");
    }
302
303
304
    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']);
    }
305
306
307
308
309

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

310
311
    safe_require('grouptype', $data['grouptype']);

312
313
314
315
316
317
    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");
318
        }
319
320
321
322
        $jointype = 'open';
    }
    else if (!empty($data['controlled'])) {
        $jointype = 'controlled';
323
324
    }
    else {
325
326
327
328
329
        $jointype = 'approve';
    }

    if (isset($data['jointype'])) {
        log_warn("group_create: ignoring supplied jointype");
330
331
332
333
334
335
336
    }

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

337
    $data['public'] = (isset($data['public'])) ? intval($data['public']) : 0;
338
    $data['hidden'] = (isset($data['hidden'])) ? intval($data['hidden']) : 0;
339
    $data['hidemembers'] = (isset($data['hidemembers'])) ? intval($data['hidemembers']) : 0;
340
    $data['hidemembersfrommembers'] = (isset($data['hidemembersfrommembers'])) ? intval($data['hidemembersfrommembers']) : 0;
341
    $data['groupparticipationreports'] = (isset($data['groupparticipationreports'])) ? intval($data['groupparticipationreports']) : 0;
342
    $data['usersautoadded'] = (isset($data['usersautoadded'])) ? intval($data['usersautoadded']) : 0;
343

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

346
347
348
349
350
351
    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;

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
382
383
384
385
386
    if (isset($data['shortname']) && strlen($data['shortname'])) {
        // This is a group whose details and membership can be updated automatically, using a
        // webservice api or possibly csv upload.

        // On updates to this group, it will be identified using the institution and shortname
        // which must be unique.

        // The $USER object will be set to someone with at least institutional admin permission.
        global $USER;

        if (empty($data['institution'])) {
            throw new SystemException("group_create: a group with a shortname must have an institution; shortname: " . $data['shortname']);
        }
        if (!$USER->can_edit_institution($data['institution'])) {
            throw new AccessDeniedException("group_create: cannot create a group in this institution");
        }
        if (!preg_match('/^[a-zA-Z0-9_.-]{2,255}$/', $data['shortname'])) {
            $message = get_string('invalidshortname', 'group') . ': ' . $data['shortname'];
            $message .= "\n" . get_string('shortnameformat', 'group');
            throw new UserException($message);
        }
        if (record_exists('group', 'shortname', $data['shortname'], 'institution', $data['institution'])) {
            throw new UserException('group_create: group with shortname ' . $data['shortname'] . ' and institution ' . $data['institution'] . ' already exists');
        }
        if (empty($data['members'])) {
            $data['members'] = array($USER->get('id') => 'admin');
        }
    }
    else {
        if (!empty($data['institution'])) {
            throw new SystemException("group_create: group institution only available for api-controlled groups");
        }
        $data['shortname'] = null;
    }

387
388
389
390
391
    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']);
    }

392
393
394
395
    if (!is_array($data['members']) || count($data['members']) == 0) {
        throw new InvalidArgumentException("group_create: at least one member must be specified for adding to the group");
    }

396
397
398
399
    if (!isset($data['submittableto'])) {
        $data['submittableto'] = $data['grouptype'] != 'standard';
    }

400
401
402
403
404
405
406
    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");
    }

407
408
409
410
411
412
    if (!isset($data['editwindowstart'])) {
        $data['editwindowstart'] = null;
    }
    if (!isset($data['editwindowend'])) {
        $data['editwindowend'] = null;
    }
413
414
415
    if (!isset($data['sendnow'])) {
        $data['sendnow'] = null;
    }
416

417
418
419
420
421
    db_begin();

    $id = insert_record(
        'group',
        (object) array(
422
            'name'           => $data['name'],
423
            'description'    => isset($data['description']) ? $data['description'] : null,
424
            'urlid'          => isset($data['urlid']) ? $data['urlid'] : null,
425
            'grouptype'      => $data['grouptype'],
426
            'category'       => isset($data['category']) ? intval($data['category']) : null,
427
            'jointype'       => $jointype,
428
429
430
431
            'ctime'          => $data['ctime'],
            'mtime'          => $data['ctime'],
            'public'         => $data['public'],
            'usersautoadded' => $data['usersautoadded'],
Hugh Davenport's avatar
Hugh Davenport committed
432
            'quota'          => $data['quota'],
433
434
            'institution'    => !empty($data['institution']) ? $data['institution'] : null,
            'shortname'      => $data['shortname'],
435
            'request'        => isset($data['request']) ? intval($data['request']) : 0,
436
            'submittableto'  => intval($data['submittableto']),
437
            'allowarchives'  => (!empty($data['submittableto']) && !empty($data['allowarchives'])) ? intval($data['allowarchives']) : 0,
438
            'editroles'      => $data['editroles'],
439
            'hidden'         => $data['hidden'],
440
            'hidemembers'    => $data['hidemembers'],
441
            'hidemembersfrommembers' => $data['hidemembersfrommembers'],
442
            'groupparticipationreports' => $data['groupparticipationreports'],
443
444
            'invitefriends'  => $data['invitefriends'],
            'suggestfriends' => $data['suggestfriends'],
445
            'editwindowstart' => $data['editwindowstart'],
446
            'editwindowend'  => $data['editwindowend'],
447
            'sendnow'        => isset($data['sendnow']) ? $data['sendnow'] : null,
448
449
            'viewnotify'     => isset($data['viewnotify']) ? $data['viewnotify'] : null,
            'feedbacknotify' => isset($data['feedbacknotify']) ? $data['feedbacknotify'] : null,
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
        ),
        '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
467
468
    // Copy views for the new group
    $templates = get_column('view_autocreate_grouptype', 'view', 'grouptype', $data['grouptype']);
469
    $templates = get_records_sql_array("
470
        SELECT v.id, v.title, v.description
471
472
        FROM {view} v
        INNER JOIN {view_autocreate_grouptype} vag ON vag.view = v.id
473
474
475
        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
476
477
    if ($templates) {
        require_once(get_config('libroot') . 'view.php');
478
479
        foreach ($templates as $template) {
            list($view) = View::create_from_template(array(
Richard Mansfield's avatar
Richard Mansfield committed
480
                'group'       => $id,
481
482
                'title'       => $template->title,
                'description' => $template->description,
483
            ), $template->id, null, false);
484
            $view->set_access(array(array(
Richard Mansfield's avatar
Richard Mansfield committed
485
486
487
488
489
490
491
492
                'type'      => 'group',
                'id'        => $id,
                'startdate' => null,
                'stopdate'  => null,
                'role'      => null
            )));
        }
    }
493
494
    // Copy collections for the new group
    $templates = get_records_sql_array("
495
        SELECT DISTINCT c.id, c.name
496
497
498
499
500
501
502
503
        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) {
504
            Collection::create_from_template(array('group' => $id), $template->id, null, false, true);
505
506
        }
    }
Richard Mansfield's avatar
Richard Mansfield committed
507
    $data['id'] = $id;
508
    // install the homepage
509
    if ($t = get_record('view', 'type', 'grouphomepage', 'template', 1, 'owner', 0)) {
510
511
        require_once('view.php');
        $template = new View($t->id, (array)$t);
512
        list($homepage) = View::create_from_template(array(
513
514
515
516
517
518
            'group' => $id,
            'title' => $template->get('title'),
            'description' => $template->get('description'),
            'type' => 'grouphomepage',
        ), $t->id, 0, false);
    }
519
    insert_record('view_access', (object) array(
520
        'view'       => $homepage->get('id'),
521
        'accesstype' => $data['public'] ? 'public' : 'loggedin',
522
        'ctime'      => db_format_timestamp(time()),
523
    ));
Richard Mansfield's avatar
Richard Mansfield committed
524
    handle_event('creategroup', $data);
525
    db_commit();
526
527

    return $id;
528
529
}

530

531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/**
 * 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));
    }
    else if (!empty($new->institution) && isset($new->shortname) && strlen($new->shortname)) {
        $old = get_record_select(
            'group',
            'shortname = ? AND institution = ? AND deleted = 0',
            array($new->shortname, $new->institution)
        );
548

549
550
551
552
553
554
555
556
557
        if (!$old && $create) {
            return group_create((array)$new);
        }
    }

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

558
    if (!empty($old->institution) && $old->institution != 'mahara') {
559
560
561
562
563
564
565
        // Api-controlled group; check permissions.
        global $USER;

        if (!$USER->can_edit_institution($old->institution)) {
            throw new AccessDeniedException("group_update: cannot update a group in this institution");
        }
    }
566
567
568
569
570
571
    if (
        (isset($new->submittableto) && empty($new->submittableto)) ||
        (!isset($new->submittableto) && empty($old->submittableto))
       ) {
        $new->allowarchives = 0;
    }
572
573
574
575
576

    // Institution and shortname cannot be updated (yet)
    unset($new->institution);
    unset($new->shortname);

577
    foreach (array('id', 'grouptype', 'public', 'request', 'submittableto', 'allowarchives', 'editroles',
578
        'hidden', 'hidemembers', 'hidemembersfrommembers', 'groupparticipationreports') as $f) {
579
580
581
582
        if (!isset($new->$f)) {
            $new->$f = $old->$f;
        }
    }
583

584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
    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);

614
615
616
617
618
619
620
621
622
623
624
    // 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;
    }

625
626
627
628
629
    $diff = array_diff_assoc((array)$new, (array)$old);
    if (empty($diff)) {
        return null;
    }

630
631
    db_begin();

632
633
634
635
636
    if (isset($new->members)) {
        group_update_members($new->id, $new->members);
        unset($new->members);
    }

637
638
    update_record('group', $new, 'id');

639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
    // 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);
            }
        }
    }
654

655
656
657
658
    // 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') {
659
660
        delete_records('group_member_invite', 'group', $new->id);
    }
661
662
663
664

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

667
    // When the group type changes, make sure everyone has a valid role.
668
669
    safe_require('grouptype', $new->grouptype);
    $allowedroles = call_static_method('GroupType' . ucfirst($new->grouptype), 'get_roles');
670
671
672
673
674
    set_field_select(
        'group_member', 'role', 'member',
        '"group" = ? AND NOT role IN (' . join(',', array_fill(0, count($allowedroles), '?')) . ')',
        array_merge(array($new->id), $allowedroles)
    );
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699

    // When a group changes from public -> private or vice versa, set the
    // appropriate access permissions on the group homepage view.
    if ($old->public != $new->public) {
        $homepageid = get_field('view', 'id', 'type', 'grouphomepage', 'group', $new->id);
        if ($old->public && !$new->public) {
            delete_records('view_access', 'view', $homepageid, 'accesstype', 'public');
            insert_record('view_access', (object) array(
                'view'       => $homepageid,
                'accesstype' => 'loggedin',
                'ctime'      => db_format_timestamp(time()),
            ));
        }
        else if (!$old->public && $new->public) {
            delete_records('view_access', 'view', $homepageid, 'accesstype', 'loggedin');
            insert_record('view_access', (object) array(
                'view'       => $homepageid,
                'accesstype' => 'public',
                'ctime'      => db_format_timestamp(time()),
            ));
        }
    }

    db_commit();

700
    return $diff;
701
702
}

703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
/**
 * 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;
}
735

736
737
738
/**
 * Deletes a group.
 *
Aaron Wells's avatar
Aaron Wells committed
739
 * All group deleting should be done through this function, even though it is
740
741
742
 * simple. What is required to perform group deletion may change over time.
 *
 * @param int $groupid The group to delete
743
744
 * @param string $shortname   shortname of the group
 * @param string $institution institution of the group
745
 *
Aaron Wells's avatar
Aaron Wells committed
746
 * {{@internal Maybe later we can have a group_can_be_deleted function if
747
748
 * necessary}}
 */
749
function group_delete($groupid, $shortname=null, $institution=null, $notifymembers=true) {
750
751
752
753
754
755
    if (empty($groupid) && !empty($institution) && !is_null($shortname) && strlen($shortname)) {
        // External call to delete a group, check permission of $USER.
        global $USER;
        if (!$USER->can_edit_institution($institution)) {
            throw new AccessDeniedException("group_delete: cannot delete a group in this institution");
        }
756
757
758
759
760
761
762
763

        $group = get_record('group', 'shortname', $shortname, 'institution', $institution);
    }
    else {
        $groupid = group_param_groupid($groupid);
        $group = get_record('group', 'id', $groupid);
    }

764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
    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);

    // 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();
    }

    // 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();
    }

795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
    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')),
                ),
            ),
        ));
813
    }
814
815
816
817
818
    // 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) . '(...)';
    }
819
820
821
    update_record('group',
        array(
            'deleted' => 1,
822
            'name' => $delete_name . '.deleted.' . time(),
823
824
            'shortname' => null,
            'institution' => null,
825
            'category' => null,
826
            'urlid' => null,
827
828
        ),
        array(
829
            'id' => $group->id,
830
831
        )
    );
832
    db_commit();
833
834
}

835
/**
836
837
838
839
840
 * 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
841
 *
842
 * @param int $groupid
843
 * @param int $userid
Richard Mansfield's avatar
Richard Mansfield committed
844
 * @param string $role
845
 */
846
function group_add_user($groupid, $userid, $role=null, $method='internal') {
847
848
849
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);

850
851
852
853
    $gm = new StdClass;
    $gm->member = $userid;
    $gm->group = $groupid;
    $gm->ctime =  db_format_timestamp(time());
Richard Mansfield's avatar
Richard Mansfield committed
854
855
856
    if (!$role) {
        $role = get_field_sql('SELECT gt.defaultrole FROM {grouptype} gt, {group} g WHERE g.id = ? AND g.grouptype = gt.name', array($groupid));
    }
857
    $gm->role = $role;
858
    $gm->method = $method;
859
860

    db_begin();
861
    insert_record('group_member', $gm);
862
    delete_records('group_member_request', 'group', $groupid, 'member', $userid);
863
    delete_records('group_member_invite', 'group', $groupid, 'member', $userid);
864
    handle_event('userjoinsgroup', $gm);
865
    db_commit();
866
867
    global $USER;
    $USER->reset_grouproles();
868
869
}

870
871
872
873
874
875
876
877
878
/**
 * 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) {
879
    global $USER;
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
    static $result;

    $userid = optional_userid($userid);

    if (is_numeric($group)) {
        if (!$group = get_record('group', 'id', $group, 'deleted', 0)) {
            return false;
        }
    }

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

895
    if ($group->jointype == 'controlled' && group_user_access($group->id, $USER->get('id')) != 'admin') {
896
897
898
899
900
901
902
903
904
905
906
        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);
}

/**
907
 * Removes a user from a group.
908
 *
909
910
 * @param int $groupid ID of group
 * @param int $userid  ID of user to remove
911
 */
912
function group_remove_user($groupid, $userid=null, $force=false) {
913
    // group_user_can_leave checks the validity of groupid and userid
914
    if (!$force && !group_user_can_leave($groupid, $userid)) {
915
916
        throw new AccessDeniedException(get_string('usercantleavegroup', 'group'));
    }
917
    delete_records('group_member', 'group', $groupid, 'member', $userid);
918

919
920
921
    global $USER;
    $USER->reset_grouproles();

922
    require_once(get_config('docroot') . 'interaction/lib.php');
923
    $interactions = get_column('interaction_instance', 'id', 'group', $groupid);
924
925
926
927
928
    foreach ($interactions as $interaction) {
        interaction_instance_from_id($interaction)->interaction_remove_user($userid);
    }
}

929
930
931
932
933
934
935
936
937
938
/**
 * 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,
 *                ...
 *            )
939
940
941
 * @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.
942
 */
943
function group_update_members($groupid, $members, $lines_done = 0, $num_lines = 0) {
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
    global $USER;

    $groupid = group_param_groupid($groupid);

    if (!$group = get_record('group', 'id', $groupid, 'deleted', 0)) {
        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));
976
        if ($group->institution && $group->institution != 'mahara') {
977
978
979
980
981
982
            $gooduserids = get_column_sql('
                SELECT usr
                FROM {usr_institution}
                WHERE usr IN (' . join(',', $userids) . ') AND institution = ?',
                array($group->institution)
            );
983

984
            if ($baduserids = array_diff($userids, $gooduserids)) {
985
986
987
                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));
                }
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
            }
        }
        else {
            $gooduserids = get_column_sql('
                SELECT id FROM {usr} WHERE id IN (' . join(',', $userids) . ') AND deleted = 0',
                array()
            );
            if ($baduserids = array_diff($userids, $gooduserids)) {
                throw new UserException("group_update_members: some new members do not exist: " . join(',', $baduserids));
            }
        }
    }

    // Update group members

    $oldmembers = get_records_assoc('group_member', 'group', $groupid, '', 'member,role');

1005
1006
1007
1008
    $added = 0;
    $removed = 0;
    $updated = 0;

1009
1010
1011
1012
    $to_add = count(array_diff_key($members, $oldmembers));
    $to_remove = count(array_diff_key($oldmembers, $members));
    $to_update = count($members) - $to_add;

1013
1014
1015
1016
1017
    db_begin();

    foreach ($members as $userid => $role) {
        if (!isset($oldmembers[$userid])) {
            group_add_user($groupid, $userid, $role);
1018
            $added ++;
1019
1020
1021
            if (!(($lines_done + $added) % 25)) {
                set_progress_info('uploadgroupmemberscsv', $num_lines + 9 * ($lines_done + count($members) * $added / ($to_add + $to_remove)), $num_lines * 10, get_string('committingchanges', 'admin'));
            }
1022
1023
1024
        }
        else if ($oldmembers[$userid]->role != $role) {
            set_field('group_member', 'role', $role, 'group', $groupid, 'member', $userid);
1025
            $updated ++;
1026
1027
1028
1029
1030
1031
        }
    }

    foreach (array_keys($oldmembers) as $userid) {
        if (!isset($members[$userid])) {
            group_remove_user($groupid, $userid, true);
1032
            $removed ++;
1033
1034
1035
            if (!(($lines_done + $added + $removed) % 25)) {
                set_progress_info('uploadgroupmemberscsv', $num_lines + 9 * ($lines_done + count($members) * ($added + $removed) / ($to_add + $to_remove)), $num_lines * 10, get_string('committingchanges', 'admin'));
            }
1036
1037
1038
1039
        }
    }

    db_commit();
1040
1041
1042
1043
1044
1045

    if ($added == 0 && $removed == 0 && $updated == 0) {
        return null;
    }

    return array('added' => $added, 'removed' => $removed, 'updated' => $updated);
1046
1047
}

1048
1049
1050
1051
1052
1053
1054
/**
 * Invite a user to a group.
 *
 * @param object $group group
 * @param object $userid  User to invite
 * @param object $userfrom  User sending the invitation
 */
1055
function group_invite_user($group, $userid, $userfrom, $role='member', $delay=null) {
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
    $user = optional_userobj($userid);

    $data = new StdClass;
    $data->group = $group->id;
    $data->member= $user->id;
    $data->ctime = db_format_timestamp(time());
    $data->role = $role;
    ensure_record_exists('group_member_invite', $data, $data);
    $lang = get_user_language($user->id);
    require_once('activity.php');
1066
    $activitydata = array(
1067
1068
1069
        'users'   => array($user->id),
        'subject' => get_string_from_language($lang, 'invitetogroupsubject', 'group'),
        'message' => get_string_from_language($lang, 'invitetogroupmessage', 'group', display_name($userfrom, $user), $group->name),
1070
        'url'     => group_homepage_url($group, false),
1071
        'urltext' => $group->name,
1072
1073
    );
    activity_occurred('maharamessage', $activitydata, null, null, $delay);
1074
1075
}

1076
1077
// Pieforms for various operations on groups

1078
/**
1079
 * Form for users to join a given group
1080
 */
1081
function group_get_join_form($name, $groupid, $returnto='view') {
1082
1083
1084
    return pieform(array(
        'name' => $name,
        'successcallback' => 'joingroup_submit',
1085
        'autofocus' => false,
1086
1087
1088
        'elements' => array(
            'join' => array(
                'type' => 'submit',
1089
                'class' => 'btn btn-primary btn-xs',
1090
1091
1092
1093
1094
                'value' => get_string('joingroup', 'group')
            ),
            'group' => array(
                'type' => 'hidden',
                'value' => $groupid
1095
1096
1097
1098
1099
            ),
            'returnto' => array(
                'type' => 'hidden',
                'value' => $returnto
            ),
1100
1101
1102
1103
        )
    ));
}

1104
1105
1106
/**
 * Form for accepting/declining a group invite
 */
1107
1108
1109
function group_get_accept_form($name, $groupid, $returnto) {
    return pieform(array(
       'name'     => $name,
1110
       'class' => 'group-request',
1111
1112
1113
1114
1115
       'renderer' => 'oneline',
       'successcallback' => 'group_invite_submit',
       'elements' => array(
            'accept' => array(
                'type'  => 'submit',
1116
                'class' => 'btn btn-primary btn-xs',
1117
1118
1119
1120
                'value' => get_string('acceptinvitegroup', 'group')
            ),
            'decline' => array(
                'type'  => 'submit',
1121
                'class' => 'btn btn-default btn-xs',
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
                'value' => get_string('declineinvitegroup', 'group')
            ),
            'group' => array(
                'type' => 'hidden',
                'value' => $groupid
            ),
            'returnto' => array(
                'type' => 'hidden',
                'value' => $returnto
            )
        )
    ));
}

1136
1137
1138
/**
 * Form for adding a user to a group
 */
1139
function group_get_adduser_form($userid, $groupid) {
1140
    return pieform(array(
1141
        'name'                => 'adduser' . $userid,
1142
        'successcallback'     => 'group_adduser_submit',
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
        'renderer'            => 'div',
        'elements'            => array(
            'group' => array(
                'type'    => 'hidden',
                'value' => $groupid,
            ),
            'member' => array(
                'type'  => 'hidden',
                'value' => $userid,
            ),
            'submit' => array(
                'type'  => 'submit',
1155
                'value' => get_string('add') . ' ' . display_name($userid),
1156
1157
1158
1159
1160
            ),
        ),
    ));
}

1161
1162
1163
/**
 * Form for removing a user from a group
 */
1164
function group_get_removeuser_form($userid, $groupid) {
1165
    require_once('pieforms/pieform.php');
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
    return pieform(array(
        'name'                => 'removeuser' . $userid,
        'validatecallback'    => 'group_removeuser_validate',
        'successcallback'     => 'group_removeuser_submit',
        'renderer'            => 'oneline',
        'elements'            => array(
            'group' => array(
                'type'    => 'hidden',
                'value' => $groupid,
            ),
            'member' => array(
                'type'  => 'hidden',
                'value' => $userid,
            ),
1180
            'removeuser' => array(
1181
1182
1183
1184
1185
1186
1187
                'type'  => 'submit',
                'value' => get_string('removefromgroup', 'group'),
            ),
        ),
    ));
}

1188
/**
1189
 * Form for denying request (request group)
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
 */
function group_get_denyuser_form($userid, $groupid) {
    require_once('pieforms/pieform.php');
    return pieform(array(
        'name'                => 'denyuser' . $userid,
        'successcallback'     => 'group_denyuser_submit',
        'renderer'            => 'oneline',
        'elements'            => array(
            'group' => array(
                'type'    => 'hidden',
                'value' => $groupid,
            ),
            'member' => array(
                'type'  => 'hidden',
                'value' => $userid,
            ),
            'denyuser' => array(
                'type'  => 'submit',
                'value' => get_string('declinerequest', 'group'),
            ),
        ),
    ));
}

1214
// Functions for handling submission of group related forms
1215
1216
1217

function joingroup_submit(Pieform $form, $values) {
    global $SESSION, $USER;
1218
    group_add_user($values['group'], $USER->get('id'));
Clare Lenihan's avatar
Clare Lenihan committed
1219
    $SESSION->add_ok_msg(get_string('joinedgroup', 'group'));
1220
1221
1222
1223
    if (substr($values['returnto'], 0, 1) == '/') {
        $next = $values['returnto'];
    }
    else {
1224
        $next = group_homepage_url(get_record('group', 'id', $values['group']));
1225
1226
    }
    redirect($next);
1227
1228
1229
1230
}

function group_invite_submit(Pieform $form, $values) {
    global $SESSION, $USER;
1231
1232
    $inviterecord = get_record('group_member_invite', 'member', $USER->get('id'), 'group', $values['group']);
    if ($inviterecord) {
1233
1234
        delete_records('group_member_invite', 'group', $values['group'], 'member', $USER->get('id'));
        if (isset($values['accept'])) {
1235
            group_add_user($values['group'], $USER->get('id'), $inviterecord->role);
Clare Lenihan's avatar
Clare Lenihan committed
1236
            $SESSION->add_ok_msg(get_string('groupinviteaccepted', 'group'));