group.php 106 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 20 21 22 23
// Constants for the different group roles
define('GROUP_HIDE_NONE', 0);
define('GROUP_HIDE_MEMBERS', 1);
define('GROUP_HIDE_TUTORS', 2);

24
// Role related functions
25

26 27 28 29 30 31
/**
 * 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
32
 * @param mixed $userid   ID of the user to check. Defaults to the logged in
33
 *                        user.
34
 * @return mixed          The role the user has in the group, or false if they
35 36
 *                        have no role in the group
 */
37
function group_user_access($groupid, $userid=null, $refresh=null) {
38
    static $result;
39

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

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

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

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

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

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

70 71 72 73 74 75
    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);
76 77 78
}

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

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

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

    return true;
}

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

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

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

139
    if (empty($userid) && !is_logged_in()) {
140 141 142
        return false;
    }

143
    $groupid = is_numeric($group) ? group_param_groupid($group) : intval($group->id);
144
    $userid  = group_param_userid($userid);
145

146 147 148 149 150 151 152 153
    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) {

154 155 156 157
    if (empty($role)) {
        return false;
    }

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    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') {
173
        return ($editroles == 'all' && group_within_edit_window($group));
174 175 176
    }

    return $editroles != 'admin';
177 178
}

179 180 181 182 183 184 185 186 187 188

/**
 * 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)) {
189
        $group = get_group_by_id($group, true);
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    }

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

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
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]);
}

226 227 228 229 230 231 232 233 234 235
/**
 * 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;

236 237 238 239
    if (!$group->groupparticipationreports) {
        return false;
    }

240 241 242 243 244 245 246
    if (group_user_access($group->id) && ($role == 'admin' || $USER->get('admin') || $USER->is_institutional_admin() || $USER->is_institutional_staff())) {
        return true;
    }

    return false;
}

247
/**
248
 * Returns whether a user is allowed to assess views that have been submitted
249 250 251 252 253 254 255
 * 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) {
256 257
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);
258 259 260 261 262 263 264 265 266 267 268 269 270

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

271 272
// Functions for creation/deletion of groups, and adding/removing users to groups

273 274 275
/**
 * Creates a group.
 *
276
 * All group creation should be done through this function, as the
277 278
 * implementation of group creation may change over time.
 *
279
 * @param array $data Data required to create the group. The following
280 281 282 283 284
 * 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.
285 286 287
 * - open (jointype): anyone can join the group
 * - controlled (jointype): admin adds members; members cannot leave the group
 * - request: allows membership requests
288
 * - ctime: The unix timestamp of the time the group will be recorded as having
289 290 291 292 293 294 295
 *          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,
 *                ...
 *            )
296
 * @return int The ID of the created group
297 298 299 300 301
 * @throws InvalidArgumentException
 *         UserException
 *         SystemException
 *         NotFoundException
 *         AccessDeniedException
302 303 304 305 306 307 308 309 310 311
 */
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");
    }
312 313 314
    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']);
    }
315 316 317 318 319

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

320 321
    safe_require('grouptype', $data['grouptype']);

322 323 324 325 326 327
    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");
328
        }
329 330 331 332
        $jointype = 'open';
    }
    else if (!empty($data['controlled'])) {
        $jointype = 'controlled';
333 334
    }
    else {
335 336 337 338 339
        $jointype = 'approve';
    }

    if (isset($data['jointype'])) {
        log_warn("group_create: ignoring supplied jointype");
340 341 342 343 344 345 346
    }

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

347
    $data['public'] = (isset($data['public'])) ? intval($data['public']) : 0;
348
    $data['hidden'] = (isset($data['hidden'])) ? intval($data['hidden']) : 0;
349
    $data['hidemembers'] = (isset($data['hidemembers'])) ? intval($data['hidemembers']) : 0;
350
    $data['hidemembersfrommembers'] = (isset($data['hidemembersfrommembers'])) ? intval($data['hidemembersfrommembers']) : 0;
351
    $data['groupparticipationreports'] = (isset($data['groupparticipationreports'])) ? intval($data['groupparticipationreports']) : 0;
352
    $data['usersautoadded'] = (isset($data['usersautoadded'])) ? intval($data['usersautoadded']) : 0;
353

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

356 357 358 359 360 361
    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;

362 363
    if (!empty($data['shortname'])) {
        // make sure it is unique and is correct length
364
        $shortname = group_generate_shortname($data['shortname']);
365 366 367
        // 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']) {
368 369
                throw new UserException('group_create: The supplied shortname \'' . $data['shortname'] .
                        '\' is already taken. This shortname \'' . $shortname . '\' is available.');
370 371 372 373 374 375 376 377
            }
        }
        $data['shortname'] = $shortname;
    }
    else {
        // Create it from group name
        $data['shortname'] = group_generate_shortname($data['name']);
    }
378

379
    if (!empty($data['institution']) && $data['institution'] != 'mahara') {
380
        global $USER;
381 382
        if (!$USER->can_edit_institution($data['institution'], true)) {
            $data['institution'] = 'mahara';
383 384 385
        }
    }
    else {
386
        $data['institution'] = 'mahara';
387 388
    }

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

394 395 396
    // Need to make sure group has at least one member
    if (empty($data['members'])) {
        $data['members'] = array($USER->get('id') => 'admin');
397 398
    }

399 400 401 402
    if (!isset($data['submittableto'])) {
        $data['submittableto'] = $data['grouptype'] != 'standard';
    }

403 404 405 406 407 408 409
    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");
    }

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

420 421 422 423 424
    db_begin();

    $id = insert_record(
        'group',
        (object) array(
425
            'name'           => $data['name'],
426
            'description'    => isset($data['description']) ? $data['description'] : null,
427
            'urlid'          => isset($data['urlid']) ? $data['urlid'] : null,
428
            'grouptype'      => $data['grouptype'],
429
            'category'       => isset($data['category']) ? intval($data['category']) : null,
430
            'jointype'       => $jointype,
431 432 433 434
            'ctime'          => $data['ctime'],
            'mtime'          => $data['ctime'],
            'public'         => $data['public'],
            'usersautoadded' => $data['usersautoadded'],
Hugh Davenport's avatar
Hugh Davenport committed
435
            'quota'          => $data['quota'],
436 437
            'institution'    => !empty($data['institution']) ? $data['institution'] : null,
            'shortname'      => $data['shortname'],
438
            'request'        => isset($data['request']) ? intval($data['request']) : 0,
439
            'submittableto'  => intval($data['submittableto']),
440
            'allowarchives'  => (!empty($data['submittableto']) && !empty($data['allowarchives'])) ? intval($data['allowarchives']) : 0,
441
            'editroles'      => $data['editroles'],
442
            'hidden'         => $data['hidden'],
443
            'hidemembers'    => $data['hidemembers'],
444
            'hidemembersfrommembers' => $data['hidemembersfrommembers'],
445
            'groupparticipationreports' => $data['groupparticipationreports'],
446 447
            'invitefriends'  => $data['invitefriends'],
            'suggestfriends' => $data['suggestfriends'],
448
            'editwindowstart' => $data['editwindowstart'],
449
            'editwindowend'  => $data['editwindowend'],
450
            'sendnow'        => isset($data['sendnow']) ? $data['sendnow'] : null,
451 452
            'viewnotify'     => isset($data['viewnotify']) ? $data['viewnotify'] : null,
            'feedbacknotify' => isset($data['feedbacknotify']) ? $data['feedbacknotify'] : null,
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        ),
        'id',
        true
    );

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

470
    // Copy views for the new group
471
    $artefactcopies = array();
472
    $templates = get_records_sql_array("
473
        SELECT v.id, v.title, v.description
474 475
        FROM {view} v
        INNER JOIN {view_autocreate_grouptype} vag ON vag.view = v.id
476 477 478
        LEFT JOIN {collection_view} cv ON v.id = cv.view
        WHERE vag.grouptype = 'standard'
            AND cv.view IS NULL", array());
479 480
    if ($templates) {
        require_once(get_config('libroot') . 'view.php');
481 482
        foreach ($templates as $template) {
            list($view) = View::create_from_template(array(
483
                'group'       => $id,
484 485
                'title'       => $template->title,
                'description' => $template->description,
486
            ), $template->id, null, false, false, $artefactcopies);
487
            $view->set_access(array(array(
488 489 490 491 492 493 494 495
                'type'      => 'group',
                'id'        => $id,
                'startdate' => null,
                'stopdate'  => null,
                'role'      => null
            )));
        }
    }
496 497
    // Copy collections for the new group
    $templates = get_records_sql_array("
498
        SELECT DISTINCT c.id, c.name
499 500 501 502 503 504 505 506
        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) {
507
            Collection::create_from_template(array('group' => $id), $template->id, null, false, true);
508 509
        }
    }
510
    $data['id'] = $id;
511
    // install the homepage
512 513
    require_once('view.php');
    if ($t = get_record('view', 'type', 'grouphomepage', 'template', View::SITE_TEMPLATE, 'institution', 'mahara')) {
514
        $template = new View($t->id, (array)$t);
515
        list($homepage) = View::create_from_template(array(
516 517 518 519
            'group' => $id,
            'title' => $template->get('title'),
            'description' => $template->get('description'),
            'type' => 'grouphomepage',
520
        ), $t->id, 0, false, false, $artefactcopies);
521
    }
522 523 524
    else {
        throw new NotFoundException("group_create: group homepage is not found");
    }
525

526
    // If 'Allow submissions' is true we need to update the 'Group portfolios' block to show
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    // 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);
            }
        }
    }

543
    insert_record('view_access', (object) array(
544
        'view'       => $homepage->get('id'),
545
        'accesstype' => $data['public'] ? 'public' : 'loggedin',
546
        'ctime'      => db_format_timestamp(time()),
547
    ));
548
    handle_event('creategroup', $data);
549
    db_commit();
550 551

    return $id;
552 553
}

554

555 556 557 558 559 560 561 562 563 564 565
/**
 * 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));
    }
566
    else if (!empty($new->shortname)) {
567 568
        $old = get_record_select(
            'group',
569 570
            'shortname = ? AND deleted = 0',
            array($new->shortname)
571
        );
572

573 574 575 576 577 578 579 580 581
        if (!$old && $create) {
            return group_create((array)$new);
        }
    }

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

582 583 584 585 586 587
    if (
        (isset($new->submittableto) && empty($new->submittableto)) ||
        (!isset($new->submittableto) && empty($old->submittableto))
       ) {
        $new->allowarchives = 0;
    }
588

589
    // Institution cannot be updated (yet)
590 591
    unset($new->institution);

592 593
    $update_blog_access = ($new->editroles != $old->editroles);

594
    foreach (array('id', 'grouptype', 'public', 'request', 'submittableto', 'allowarchives', 'editroles',
595
        'hidden', 'hidemembers', 'hidemembersfrommembers', 'groupparticipationreports') as $f) {
596 597 598 599
        if (!isset($new->$f)) {
            $new->$f = $old->$f;
        }
    }
600

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    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);

631 632 633 634 635 636 637 638 639 640 641
    // 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;
    }

642 643 644 645 646
    $diff = array_diff_assoc((array)$new, (array)$old);
    if (empty($diff)) {
        return null;
    }

647 648
    db_begin();

649 650 651 652 653
    if (isset($new->members)) {
        group_update_members($new->id, $new->members);
        unset($new->members);
    }

654 655
    update_record('group', $new, 'id');

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
    // 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);
            }
        }
    }
671

672 673 674 675
    // 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') {
676 677
        delete_records('group_member_invite', 'group', $new->id);
    }
678 679 680 681

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

684
    // When the group type changes, make sure everyone has a valid role.
685 686
    safe_require('grouptype', $new->grouptype);
    $allowedroles = call_static_method('GroupType' . ucfirst($new->grouptype), 'get_roles');
687 688 689 690 691
    set_field_select(
        'group_member', 'role', 'member',
        '"group" = ? AND NOT role IN (' . join(',', array_fill(0, count($allowedroles), '?')) . ')',
        array_merge(array($new->id), $allowedroles)
    );
692

693 694 695 696
    // 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') {
697
            if ($ids = get_records_select_array('artefact',
698
                      '"group" = ' . $new->id . ' AND artefacttype IN (\'blog\', \'blogpost\')',
699 700 701 702 703 704 705 706 707 708 709 710 711
                      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();
712 713 714 715 716 717 718 719 720 721 722 723 724 725
            }
        }
        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));
        }
    }

726 727
    // When a group changes from public -> private or vice versa, set the
    // appropriate access permissions on the group homepage view.
728
    $homepageid = get_field('view', 'id', 'type', 'grouphomepage', 'group', $new->id);
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    if ($old->public != $new->public) {
        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()),
            ));
        }
    }

748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
    // 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));
        }
    }

777
    // If 'Allow submissions' is changed we need to update the 'Group portfolios' block
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    // 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);
    }

794 795
    db_commit();

796
    return $diff;
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 824 825 826 827 828 829 830
/**
 * 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;
}
831

832 833 834
/**
 * Deletes a group.
 *
835
 * All group deleting should be done through this function, even though it is
836 837 838
 * simple. What is required to perform group deletion may change over time.
 *
 * @param int $groupid The group to delete
839 840
 * @param string $shortname   shortname of the group
 * @param string $institution institution of the group
841
 *
842
 * {{@internal Maybe later we can have a group_can_be_deleted function if
843 844
 * necessary}}
 */
845
function group_delete($groupid, $shortname=null, $institution=null, $notifymembers=true) {
846 847
    global $USER;

848 849 850 851 852
    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");
        }
853 854 855 856 857

        $group = get_record('group', 'shortname', $shortname, 'institution', $institution);
    }
    else {
        $groupid = group_param_groupid($groupid);
858
        $group = get_group_by_id($groupid, true);
859 860
    }

861 862 863 864 865 866 867
    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);

868 869 870 871
    // Delete embedded images in the group description
    require_once('embeddedimage.php');
    EmbeddedImage::delete_embedded_images('group', $group->id);

872 873 874 875 876 877 878
    // 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();
    }

879 880 881 882 883 884 885
    // 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();
    }

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    // 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();
    }

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
    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')),
                ),
            ),
        ));
921
    }
922 923 924 925 926
    // 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) . '(...)';
    }
927 928 929
    update_record('group',
        array(
            'deleted' => 1,
930
            'name' => $delete_name . '.deleted.' . time(),
931 932
            'shortname' => null,
            'institution' => null,
933
            'category' => null,
934
            'urlid' => null,
935 936
        ),
        array(
937
            'id' => $group->id,
938 939
        )
    );
940
    db_commit();
941 942 943
    // 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();
944 945
}

946
/**
947 948 949 950 951
 * 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
952
 *
953
 * @param int $groupid
954
 * @param int $userid
955
 * @param string $role
956
 */
957
function group_add_user($groupid, $userid, $role=null, $method='internal') {
958 959 960
    $groupid = group_param_groupid($groupid);
    $userid  = group_param_userid($userid);

961 962 963 964
    $gm = new StdClass;
    $gm->member = $userid;
    $gm->group = $groupid;
    $gm->ctime =  db_format_timestamp(time());
965 966 967
    if (!$role) {
        $role = get_field_sql('SELECT gt.defaultrole FROM {grouptype} gt, {group} g WHERE g.id = ? AND g.grouptype = gt.name', array($groupid));
    }
968
    $gm->role = $role;
969
    $gm->method = $method;
970 971

    db_begin();
972
    insert_record('group_member', $gm);
973
    delete_records('group_member_request', 'group', $groupid, 'member', $userid);
974
    delete_records('group_member_invite', 'group', $groupid, 'member', $userid);
975
    handle_event('userjoinsgroup', $gm);
976
    db_commit();
977 978
    global $USER;
    $USER->reset_grouproles();
979 980
}

981 982 983 984 985 986 987 988 989
/**
 * 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) {
990
    global $USER;
991 992 993 994 995
    static $result;

    $userid = optional_userid($userid);

    if (is_numeric($group)) {
996
        if (!$group = get_group_by_id($group)) {
997 998 999 1000 1001 1002 1003 1004 1005
            return false;
        }
    }

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

1006
    if ($group->jointype == 'controlled' && group_user_access($group->id, $USER->get('id')) != 'admin') {
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
        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);
}

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
/**
 * 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;
    }
}

1035
/**
1036
 * Removes a user from a group.
1037
 *
1038 1039
 * @param int $groupid ID of group
 * @param int $userid  ID of user to remove
1040
 */
1041
function group_remove_user($groupid, $userid=null, $force=false) {
1042
    // group_user_can_leave checks the validity of groupid and userid
1043
    if (!$force && !group_user_can_leave($groupid, $userid)) {
1044 1045
        throw new AccessDeniedException(get_string('usercantleavegroup', 'group'));
    }
1046
    delete_records('group_member', 'group', $groupid, 'member', $userid);
1047

1048 1049 1050
    global $USER;
    $USER->reset_grouproles();

1051
    require_once(get_config('docroot') . 'interaction/lib.php');
1052
    $interactions = get_column('interaction_instance', 'id', 'group', $groupid);
1053 1054 1055 1056 1057
    foreach ($interactions as $interaction) {
        interaction_instance_from_id($interaction)->interaction_remove_user($userid);
    }
}

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
/**
 * 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,
 *                ...
 *            )
1068 1069 1070
 * @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.
1071
 */
1072
function group_update_members($groupid, $members, $lines_done = 0, $num_lines = 0) {
1073 1074 1075 1076
    global $USER;

    $groupid = group_param_groupid($groupid);

1077
    if (!$group = get_group_by_id($groupid)) {
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        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));
1105
        if ($group->institution && $group->institution != 'mahara') {
1106 1107 1108 1109 1110 1111
            $gooduserids = get_column_sql('
                SELECT usr
                FROM {usr_institution}
                WHERE usr IN (' . join(',', $userids) . ') AND institution = ?',
                array($group->institution)
            );
1112

1113
            if ($baduserids = array_diff($userids, $gooduserids)) {
1114 1115 1116
                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));
                }
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
            }
        }
        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');

1134 1135 1136 1137
    $added = 0;
    $removed = 0;
    $updated = 0;

1138 1139 1140 1141
    $to_add = count(array_diff_key($members, $oldmembers));
    $to_remove = count(array_diff_key($oldmembers, $members));
    $to_update = count($members) - $to_add;

1142 1143 1144 1145 1146
    db_begin();

    foreach ($members as $userid => $role) {
        if (!isset($oldmembers[$userid])) {
            group_add_user($groupid, $userid, $role);
1147
            $added ++;
1148 1149 1150
            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'));
            }
1151 1152 1153
        }
        else if ($oldmembers[$userid]->role != $role) {
            set_field('group_member', 'role', $role, 'group', $groupid, 'member', $userid);
1154
            $updated ++;
1155 1156 1157 1158 1159 1160
        }
    }

    foreach (array_keys($oldmembers) as $userid) {
        if (!isset($members[$userid])) {
            group_remove_user($groupid, $userid, true);
1161
            $removed ++;
1162 1163 1164
            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'));
            }
1165 1166 1167 1168
        }
    }

    db_commit();
1169 1170 1171 1172 1173 1174

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

    return array('added' => $added, 'removed' => $removed, 'updated' => $updated);
1175 1176
}

1177 1178 1179 1180 1181 1182 1183
/**
 * Invite a user to a group.
 *
 * @param object $group group
 * @param object $userid  User to invite
 * @param object $userfrom  User sending the invitation
 */
1184
function group_invite_user($group, $userid, $userfrom, $role='member', $delay=null) {
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    $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');
1195
    $activitydata = array(
1196 1197 1198
        '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),
1199
        'url'     => group_homepage_url($group, false),
1200
        'urltext' => $group->name,
1201 1202
    );
    activity_occurred('maharamessage', $activitydata, null, null, $delay);
1203 1204
}

1205 1206
// Pieforms for various operations on groups

1207
/**
1208
 * Form for users to join a given group
1209
 */
1210
function group_get_join_form($name, $groupid, $returnto='view') {
1211 1212 1213
    return pieform(array(
        'name' => $name,
        'successcallback' => 'joingroup_submit',
1214
        'autofocus' => false,
1215
        'elements' => array(
1216 1217
            'btngroup' => array(
                'type'  => 'fieldset',
1218
                'class' => 'group-request btn-top-right btn-group btn-group-top',
1219 1220 1221 1222
                'elements'     => array(
                    'join' => array(
                        'type' => 'button',
                        'usebuttontag' => true,
1223
                        'class' => 'btn-default',
1224
                        'value' => '<span class="icon icon-lg icon-plus left" role="presentation" aria-hidden="true"></span> ' . get_string('joingroup', 'group')
1225 1226
                    )
                )
1227 1228 1229
            ),
            'group' => array(
                'type' => 'hidden',
1230 1231
                'value' => $groupid,
                'sesskey' => true,
1232 1233 1234 1235 1236
            ),
            'returnto' => array(
                'type' => 'hidden',
                'value' => $returnto
            ),
1237 1238 1239 1240
        )
    ));
}

1241 1242 1243
/**
 * Form for accepting/declining a group invite
 */
1244 1245 1246
function group_get_accept_form($name, $groupid, $returnto) {
    return pieform(array(
       'name'     => $name,
1247
       'renderer' => 'div',
1248 1249
       'successcallback' => 'group_invite_submit',
       'elements' => array(
1250 1251
           'btngroup' => array(
                'type'  => 'fieldset',
1252
                'class' => 'group-request btn-top-right btn-group btn-group-top',
1253 1254 1255 1256
                'elements'     => array(
                    'accept' => array(
                        'type'  => 'button',
                        'usebuttontag' => true,
1257
                        'class' => 'btn-default form-as-button pull-left',
1258
                        'value' => '<span class="icon icon-lg icon-check text-success left" role="presentation" aria-hidden="true"></span> ' . get_string('acceptinvitegroup', 'group')
1259 1260 1261 1262
                    ),
                    'decline' => array(
                        'type'  => 'button',
                        'usebuttontag' => true,
1263
                        'class' => 'btn-default form-as-button pull-left',
1264
                        'value' => '<span class="icon icon-lg icon-ban text-danger left" role="presentation" aria-hidden="true"></span> ' . get_string('declineinvitegroup', 'group')
1265 1266
                    )
                ),
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
            ),
            'group' => array(
                'type' => 'hidden',
                'value' => $groupid
            ),
            'returnto' => array(
                'type' => 'hidden',
                'value' => $returnto
            )
        )
    ));
}

1280 1281 1282
/**
 * Form for adding a user to a group
 */
1283
function group_get_adduser_form($userid, $groupid) {
1284
    return pieform(array(
1285
        'name'                => 'adduser' . $userid,
1286
        'successcallback'     => 'group_adduser_submit',
1287
        'renderer'            => 'div',
1288
        'class'               => 'form-as-button pull-left',
1289 1290 1291 1292 1293 1294 1295 1296 1297
        'elements'            => array(
            'group' => array(
                'type'    => 'hidden',
                'value' => $groupid,
            ),
            'member' => array(
                'type'  => 'hidden',
                'value' => $userid,
            ),
1298 1299 1300 1301
            'adduser' => array(
                'type' => 'hidden',
                'value' => true,
            ),
1302
            'submit' => array(
1303 1304
                'type'  => 'button',
                'usebuttontag' => true,
1305
                'class' => 'btn-default',
1306
                'value' => '<span class="icon icon-lg icon-check left text-success" role="presentation" aria-hidden="true"></span> ' .get_string('add'),
1307 1308 1309 1310 1311
            ),
        ),
    ));
}

1312 1313 1314
/**
 * Form for removing a user from a group
 */
1315 1316 1317 1318 1319
function group_get_removeuser_form($userid, $groupid) {
    return pieform(array(
        'name'                => 'removeuser' . $userid,
        'validatecallback'    => 'group_removeuser_validate',
        'successcallback'     => 'group_removeuser_submit',
1320
        'renderer'            => 'div',
1321
        'class'               => 'pull-left',
1322 1323 1324 1325 1326 1327 1328 1329 1330
        'elements'            => array(
            'group' => array(
                'type'    => 'hidden',
                'value' => $groupid,
            ),
            'member' => array(
                'type'  => 'hidden',
                'value' => $userid,
            ),
1331
            'removeuser' => array(
1332 1333 1334 1335
                'type'  => 'hidden',
                'value' => true,
            ),
            'submit' => array(
1336 1337
                'type'  => 'button',
                'usebuttontag' => true,
1338
                'class' => 'btn-default',
1339
                'value' => '<span class="icon icon-times icon-lg text-danger left" role="presentation" aria-hidden="true"></span>' . get_string('removefromgroup', 'group'),
1340 1341 1342 1343 1344
            ),
        ),
    ));
}

1345
/**
1346
 * Form for denying request (request group)
1347 1348 1349 1350 1351
 */
function group_get_denyuser_form($userid, $groupid) {
    return pieform(array(
        'name'                => 'denyuser' . $userid,
        'successcallback'     => 'group_denyuser_submit',
1352 1353
        'renderer'            => 'div',
        'class'               => 'form-as-button pull-left',
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
        'elements'            => array(
            'group' => array(
                'type'    => 'hidden',
                'value' => $groupid,
            ),
            'member' => array(
                'type'  => 'hidden',
                'value' => $userid,
            ),
            'denyuser' => array(
1364 1365 1366 1367
                'type'  => 'hidden',
                'value' => true,
            ),
            'submit' => array(
1368 1369
                'type'  => 'button',
                'usebuttontag' => true,
1370
                'class' => 'btn-default',
1371
                'value' => '<span class="icon icon-ban icon-lg text-danger left" role="presentation" aria-hidden="true"></span>' . get_string('declinerequest', 'group'),
1372 1373 1374 1375 1376
            ),
        ),
    ));
}

1377
// Functions for handling submission of group related forms
1378 1379 1380

function joingroup_submit(Pieform $form, $values) {
    global $SESSION, $USER;
1381
    group_add_user($values['group'], $USER->get('id'));
1382
    $SESSION->add_ok_msg(get_string('joinedgroup', 'group'));
1383 1384 1385 1386
    if (substr($values['returnto'], 0, 1) == '/') {
        $next = $values['returnto'];
    }
    else {
1387
        $next = group_homepage_url(get_group_by_id($values['group'], true));
1388 1389
    }
    redirect($next);
1390 1391 1392 1393
}

function group_invite_submit(Pieform $form, $values) {
    global $SESSION, $USER;
1394 1395
    $inviterecord = get_record('group_member_invite', 'member', $USER->get('id'), 'group', $values['group']);
    if ($inviterecord) {
1396 1397
        delete_records('group_member_invite', 'group', $values['group'], 'member', $USER->get('id'));
        if (isset($values['accept'])) {
1398
            group_add_user($values['group'], $USER->get('id'), $inviterecord->role);
1399
            $SESSION->add_ok_msg(get_string('groupinviteaccepted', 'group'));
1400 1401 1402 1403
            if (substr($values['returnto'], 0, 1) == '/') {
                $next = $values['returnto'];
            }
            else {
1404
                $next = group_homepage_url(get_group_by_id($values['group'], true));
1405 1406
            }
            redirect($next);
1407 1408
        }
        else {
1409
            $SESSION->add_ok_msg(get_string('groupinvitedeclined', 'group'));
1410 1411 1412 1413 1414
            redirect($values['returnto'] == 'find' ? '/group/find.php' : '/group/mygroups.php');
        }
    }
}

1415
function group_adduser_submit(Pieform $form, $values) {
1416 1417 1418 1419 1420 1421
    global $SESSION;
    $group = (int)$values['group'];
    if (group_user_access($group) != 'admin') {
        $SESSION->add_error_msg(get_string('accessdenied', 'error'));
        redirect('/group/members.php?id=' . $group . '&membershiptype=request');
    }
1422
    group_add_user($group, $values['member']);
1423 1424 1425 1426 1427 1428 1429
    $SESSION->add_ok_msg(get_string('useradded', 'group'));
    if (count_records('group_member_request', 'group', $group)) {
        redirect('/group/members.php?id=' . $group . '&membershiptype=request');
    }
    redirect('/group/members.php?id=' . $group);
}

1430
/**
1431