Merge branch 'MDL-80220-main' of https://github.com/laurentdavid/moodle
[moodle.git] / lib / grouplib.php
blob63a65da6626d01ea824ae72b49a61ba999c3f0f5
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21 * @package core_group
24 defined('MOODLE_INTERNAL') || die();
26 /**
27 * Groups not used in course or activity
29 define('NOGROUPS', 0);
31 /**
32 * Groups used, users do not see other groups
34 define('SEPARATEGROUPS', 1);
36 /**
37 * Groups used, students see other groups
39 define('VISIBLEGROUPS', 2);
41 /**
42 * This is for filtering users without any group.
44 define('USERSWITHOUTGROUP', -1);
46 /**
47 * 'None' join type, used when filtering by groups (logical NOT)
49 define('GROUPS_JOIN_NONE', 0);
51 /**
52 * 'Any' join type, used when filtering by groups (logical OR)
54 define('GROUPS_JOIN_ANY', 1);
56 /**
57 * 'All' join type, used when filtering by groups (logical AND)
59 define('GROUPS_JOIN_ALL', 2);
61 /**
62 * All users can see this group and its members.
64 define('GROUPS_VISIBILITY_ALL', 0);
66 /**
67 * Members of this group can see this group and other members.
69 define('GROUPS_VISIBILITY_MEMBERS', 1);
71 /**
72 * Members of this group can see the group and their own membership, but not each other's membership
74 define('GROUPS_VISIBILITY_OWN', 2);
76 /**
77 * No-one can see this group or its members. Members of the group will not know they are in the group.
79 define('GROUPS_VISIBILITY_NONE', 3);
81 /**
82 * Determines if a group with a given groupid exists.
84 * @category group
85 * @param int $groupid The groupid to check for
86 * @return bool True if the group exists, false otherwise or if an error
87 * occurred.
89 function groups_group_exists($groupid) {
90 global $DB;
91 return $DB->record_exists('groups', array('id'=>$groupid));
94 /**
95 * Gets the name of a group with a specified id
97 * Before output, you should call {@see format_string} on the result
99 * @category group
100 * @param int $groupid The id of the group
101 * @return string The name of the group
103 function groups_get_group_name($groupid) {
104 global $DB;
105 return $DB->get_field('groups', 'name', array('id'=>$groupid));
109 * Gets the name of a grouping with a specified id
111 * Before output, you should call {@see format_string} on the result
113 * @category group
114 * @param int $groupingid The id of the grouping
115 * @return string The name of the grouping
117 function groups_get_grouping_name($groupingid) {
118 global $DB;
119 return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
123 * Returns the groupid of a group with the name specified for the course.
124 * Group names should be unique in course
126 * @category group
127 * @param int $courseid The id of the course
128 * @param string $name name of group (without magic quotes)
129 * @return int $groupid
131 function groups_get_group_by_name($courseid, $name) {
132 $data = groups_get_course_data($courseid);
133 foreach ($data->groups as $group) {
134 if ($group->name == $name) {
135 return $group->id;
138 return false;
142 * Returns the groupid of a group with the idnumber specified for the course.
143 * Group idnumbers should be unique within course
145 * @category group
146 * @param int $courseid The id of the course
147 * @param string $idnumber idnumber of group
148 * @return group object
150 function groups_get_group_by_idnumber($courseid, $idnumber) {
151 if (empty($idnumber)) {
152 return false;
154 $data = groups_get_course_data($courseid);
155 foreach ($data->groups as $group) {
156 if ($group->idnumber == $idnumber) {
157 return $group;
160 return false;
164 * Returns the groupingid of a grouping with the name specified for the course.
165 * Grouping names should be unique in course
167 * @category group
168 * @param int $courseid The id of the course
169 * @param string $name name of group (without magic quotes)
170 * @return int $groupid
172 function groups_get_grouping_by_name($courseid, $name) {
173 $data = groups_get_course_data($courseid);
174 foreach ($data->groupings as $grouping) {
175 if ($grouping->name == $name) {
176 return $grouping->id;
179 return false;
183 * Returns the groupingid of a grouping with the idnumber specified for the course.
184 * Grouping names should be unique within course
186 * @category group
187 * @param int $courseid The id of the course
188 * @param string $idnumber idnumber of the group
189 * @return grouping object
191 function groups_get_grouping_by_idnumber($courseid, $idnumber) {
192 if (empty($idnumber)) {
193 return false;
195 $data = groups_get_course_data($courseid);
196 foreach ($data->groupings as $grouping) {
197 if ($grouping->idnumber == $idnumber) {
198 return $grouping;
201 return false;
205 * Get the group object
207 * @category group
208 * @param int $groupid ID of the group.
209 * @param string $fields (default is all fields)
210 * @param int $strictness (IGNORE_MISSING - default)
211 * @return bool|stdClass group object or false if not found
212 * @throws dml_exception
214 function groups_get_group($groupid, $fields = '*', $strictness = IGNORE_MISSING, $withcustomfields = false) {
215 global $DB;
216 $group = $DB->get_record('groups', ['id' => $groupid], $fields, $strictness);
217 if ($withcustomfields) {
218 $customfieldsdata = get_group_custom_fields_data([$groupid]);
219 $group->customfields = $customfieldsdata[$groupid] ?? [];
221 return $group;
225 * Get the grouping object
227 * @category group
228 * @param int $groupingid ID of the group.
229 * @param string $fields
230 * @param int $strictness (IGNORE_MISSING - default)
231 * @return stdClass group object
233 function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING, $withcustomfields = false) {
234 global $DB;
235 $grouping = $DB->get_record('groupings', ['id' => $groupingid], $fields, $strictness);
236 if ($withcustomfields) {
237 $customfieldsdata = get_grouping_custom_fields_data([$groupingid]);
238 $grouping->customfields = $customfieldsdata[$groupingid] ?? [];
240 return $grouping;
244 * Gets array of all groups in a specified course (subject to the conditions imposed by the other arguments).
246 * If a user does not have moodle/course:viewhiddengroups, the list of groups and members will be restricted based on the
247 * visibility setting of each group.
249 * @category group
250 * @param int $courseid The id of the course.
251 * @param int|int[] $userid optional user id or array of ids, returns only groups continaing one or more of those users.
252 * @param int $groupingid optional returns only groups in the specified grouping.
253 * @param string $fields defaults to g.*. This allows you to vary which fields are returned.
254 * If $groupingid is specified, the groupings_groups table will be available with alias gg.
255 * If $userid is specified, the groups_members table will be available as gm.
256 * @param bool $withmembers if true return an extra field members (int[]) which is the list of userids that
257 * are members of each group. For this to work, g.id (or g.*) must be included in $fields.
258 * In this case, the final results will always be an array indexed by group id.
259 * @param bool $participationonly Only return groups where the participation field is true.
260 * @return array returns an array of the group objects (unless you have done something very weird
261 * with the $fields option).
263 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false, $participationonly = false) {
264 global $DB, $USER;
266 // We need to check that we each field in the fields list belongs to the group table and that it has not being
267 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
268 $knownfields = true;
269 if ($fields !== 'g.*') {
270 // Quickly check if the first field is no longer g.id as using the
271 // cache will return an array indexed differently than when expect
272 if (strpos($fields, 'g.*') !== 0 && strpos($fields, 'g.id') !== 0) {
273 $knownfields = false;
274 } else {
275 $fieldbits = explode(',', $fields);
276 foreach ($fieldbits as $bit) {
277 $bit = trim($bit);
278 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
279 $knownfields = false;
280 break;
286 if (empty($userid) && $knownfields && !$withmembers && \core_group\visibility::can_view_all_groups($courseid)) {
287 // We can use the cache.
288 $data = groups_get_course_data($courseid);
289 if (empty($groupingid)) {
290 // All groups.. Easy!
291 $groups = $data->groups;
292 } else {
293 $groups = array();
294 foreach ($data->mappings as $mapping) {
295 if ($mapping->groupingid != $groupingid) {
296 continue;
298 if (isset($data->groups[$mapping->groupid])) {
299 $groups[$mapping->groupid] = $data->groups[$mapping->groupid];
303 if ($participationonly) {
304 $groups = array_filter($groups, fn($group) => $group->participation);
306 // Yay! We could use the cache. One more query saved.
307 return $groups;
310 $params = [];
311 $userfrom = '';
312 $userwhere = '';
313 if (!empty($userid)) {
314 list($usql, $params) = $DB->get_in_or_equal($userid);
315 $userfrom = "JOIN {groups_members} gm ON gm.groupid = g.id";
316 $userwhere = "AND gm.userid $usql";
319 $groupingfrom = '';
320 $groupingwhere = '';
321 if (!empty($groupingid)) {
322 $groupingfrom = "JOIN {groupings_groups} gg ON gg.groupid = g.id";
323 $groupingwhere = "AND gg.groupingid = ?";
324 $params[] = $groupingid;
327 array_unshift($params, $courseid);
329 $visibilityfrom = '';
330 $visibilitywhere = '';
331 $viewhidden = has_capability('moodle/course:viewhiddengroups', context_course::instance($courseid));
332 if (!$viewhidden) {
333 // Apply group visibility restrictions. Only return groups where visibility is ALL, or the current user is a member and the
334 // visibility is MEMBERS or OWN.
335 $userids = [];
336 if (empty($userid)) {
337 $userids = [$USER->id];
338 $visibilityfrom = "LEFT JOIN {groups_members} gm ON gm.groupid = g.id AND gm.userid = ?";
340 [$insql, $inparams] = $DB->get_in_or_equal([GROUPS_VISIBILITY_MEMBERS, GROUPS_VISIBILITY_OWN]);
341 $visibilitywhere = " AND (g.visibility = ? OR (g.visibility $insql AND gm.id IS NOT NULL))";
342 $params = array_merge(
343 $userids,
344 $params,
345 [GROUPS_VISIBILITY_ALL],
346 $inparams
350 $participationwhere = '';
351 if ($participationonly) {
352 $participationwhere = "AND g.participation = ?";
353 $params = array_merge($params, [1]);
356 $results = $DB->get_records_sql("
357 SELECT $fields
358 FROM {groups} g
359 $userfrom
360 $groupingfrom
361 $visibilityfrom
362 WHERE g.courseid = ?
363 $userwhere
364 $groupingwhere
365 $visibilitywhere
366 $participationwhere
367 ORDER BY g.name ASC", $params);
369 if (!$withmembers) {
370 return $results;
373 // We also want group members. We do this in a separate query, becuse the above
374 // query will return a lot of data (e.g. g.description) for each group, and
375 // some groups may contain hundreds of members. We don't want the results
376 // to contain hundreds of copies of long descriptions.
377 $groups = [];
378 foreach ($results as $row) {
379 $groups[$row->id] = $row;
380 $groups[$row->id]->members = [];
383 $gmvisibilityfrom = '';
384 $gmvisibilitywhere = '';
385 $gmvisibilityparams = [];
386 if (!$viewhidden) {
387 // Only return membership records where visibility is ALL, visibility is MEMBERS and the current user is a member,
388 // or visibility is OWN and the record is for the current user.
389 $gmvisibilityfrom = "
390 JOIN {groups} g ON gm.groupid = g.id
392 $gmvisibilitywhere = "
393 AND (g.visibility = ?
394 OR (g.visibility = ?
395 AND g.id IN (SELECT gm2.groupid FROM {groups_members} gm2 WHERE gm2.groupid = g.id AND gm2.userid = ?))
396 OR (g.visibility = ?
397 AND gm.userid = ?))";
398 $gmvisibilityparams = [
399 GROUPS_VISIBILITY_ALL,
400 GROUPS_VISIBILITY_MEMBERS,
401 $USER->id,
402 GROUPS_VISIBILITY_OWN,
403 $USER->id
407 $groupmembers = [];
408 if (!empty($groups)) {
409 [$gmin, $gmparams] = $DB->get_in_or_equal(array_keys($groups));
410 $params = array_merge($gmparams, $gmvisibilityparams);
411 $gmsql = "
412 SELECT gm.*
413 FROM {groups_members} gm
414 $gmvisibilityfrom
415 WHERE gm.groupid $gmin
416 $gmvisibilitywhere";
417 $groupmembers = $DB->get_records_sql($gmsql, $params);
420 foreach ($groupmembers as $gm) {
421 $groups[$gm->groupid]->members[$gm->userid] = $gm->userid;
423 return $groups;
427 * Gets array of all groups in current user.
429 * @since Moodle 2.5
430 * @category group
431 * @return array Returns an array of the group objects.
433 function groups_get_my_groups() {
434 global $DB, $USER;
436 $params = ['userid' => $USER->id];
438 $viewhidden = has_capability('moodle/course:viewhiddengroups', context_system::instance());
439 $visibilitywhere = '';
440 if (!$viewhidden) {
441 $params['novisibility'] = GROUPS_VISIBILITY_NONE;
442 $visibilitywhere = ' AND g.visibility != :novisibility';
445 return $DB->get_records_sql("SELECT *
446 FROM {groups_members} gm
447 JOIN {groups} g
448 ON g.id = gm.groupid
449 WHERE gm.userid = :userid
450 $visibilitywhere
451 ORDER BY name ASC", $params);
455 * Returns info about user's groups in course.
457 * @category group
458 * @param int $courseid
459 * @param int $userid $USER if not specified
460 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
462 function groups_get_user_groups($courseid, $userid=0) {
463 global $USER, $DB;
465 if (empty($courseid)) {
466 return ['0' => []];
469 if (empty($userid)) {
470 $userid = $USER->id;
473 $usergroups = false;
474 $viewhidden = has_capability('moodle/course:viewhiddengroups', context_course::instance($courseid));
475 $viewall = \core_group\visibility::can_view_all_groups($courseid);
477 $cache = cache::make('core', 'user_group_groupings');
479 if ($viewall) {
480 // Try to retrieve group ids from the cache.
481 $usergroups = $cache->get($userid);
484 if ($usergroups === false) {
486 $sql = "SELECT g.id, g.courseid, gg.groupingid
487 FROM {groups} g
488 JOIN {groups_members} gm ON gm.groupid = g.id
489 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
490 WHERE gm.userid = :userid";
492 $params = ['userid' => $userid];
494 if (!$viewhidden) {
495 // Apply visibility restrictions.
496 // Everyone can see who is in groups with ALL visibility.
497 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_group_visibility_where($userid);
498 $sql .= " AND " . $visibilitywhere;
499 $params = array_merge($params, $visibilityparams);
502 $sql .= ' ORDER BY g.id'; // To make results deterministic.
504 $rs = $DB->get_recordset_sql($sql, $params);
506 $usergroups = array();
507 $allgroups = array();
509 foreach ($rs as $group) {
510 if (!array_key_exists($group->courseid, $allgroups)) {
511 $allgroups[$group->courseid] = array();
513 $allgroups[$group->courseid][$group->id] = $group->id;
514 if (!array_key_exists($group->courseid, $usergroups)) {
515 $usergroups[$group->courseid] = array();
517 if (is_null($group->groupingid)) {
518 continue;
520 if (!array_key_exists($group->groupingid, $usergroups[$group->courseid])) {
521 $usergroups[$group->courseid][$group->groupingid] = array();
523 $usergroups[$group->courseid][$group->groupingid][$group->id] = $group->id;
525 $rs->close();
527 foreach (array_keys($allgroups) as $cid) {
528 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
531 if ($viewall) {
532 // Cache the data, if we got the full list of groups.
533 $cache->set($userid, $usergroups);
537 if (array_key_exists($courseid, $usergroups)) {
538 return $usergroups[$courseid];
539 } else {
540 return array('0' => array());
545 * Gets an array of all groupings in a specified course. This value is cached
546 * for a single course (so you can call it repeatedly for the same course
547 * without a performance penalty).
549 * @category group
550 * @param int $courseid return all groupings from course with this courseid
551 * @return array Returns an array of the grouping objects (empty if none)
553 function groups_get_all_groupings($courseid) {
554 $data = groups_get_course_data($courseid);
555 return $data->groupings;
559 * Determines if the user is a member of the given group.
561 * If $userid is null, use the global object.
563 * @category group
564 * @param int $groupid The group to check for membership.
565 * @param int $userid The user to check against the group.
566 * @return bool True if the user is a member, false otherwise.
568 function groups_is_member($groupid, $userid=null) {
569 global $USER, $DB;
571 if (!$userid) {
572 $userid = $USER->id;
575 $courseid = $DB->get_field('groups', 'courseid', ['id' => $groupid]);
576 if (!$courseid) {
577 return false;
580 if (\core_group\visibility::can_view_all_groups($courseid)) {
581 return $DB->record_exists('groups_members', ['groupid' => $groupid, 'userid' => $userid]);
584 $sql = "SELECT *
585 FROM {groups_members} gm
586 JOIN {groups} g ON gm.groupid = g.id
587 WHERE g.id = :groupid
588 AND gm.userid = :userid";
589 $params = ['groupid' => $groupid, 'userid' => $userid];
591 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_group_visibility_where($userid);
593 $sql .= " AND " . $visibilitywhere;
594 $params = array_merge($params, $visibilityparams);
596 return $DB->record_exists_sql($sql, $params);
600 * Determines if current or specified is member of any active group in activity
602 * @category group
603 * @staticvar array $cache
604 * @param stdClass|cm_info $cm course module object
605 * @param int $userid id of user, null means $USER->id
606 * @return bool true if user member of at least one group used in activity
608 function groups_has_membership($cm, $userid=null) {
609 global $CFG, $USER, $DB;
611 static $cache = array();
613 if (empty($userid)) {
614 $userid = $USER->id;
617 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
618 if (isset($cache[$cachekey])) {
619 return($cache[$cachekey]);
622 if ($cm->groupingid) {
623 // find out if member of any group in selected activity grouping
624 $sql = "SELECT 'x'
625 FROM {groups_members} gm, {groupings_groups} gg
626 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
627 $params = array($userid, $cm->groupingid);
629 } else {
630 // no grouping used - check all groups in course
631 $sql = "SELECT 'x'
632 FROM {groups_members} gm, {groups} g
633 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
634 $params = array($userid, $cm->course);
637 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
639 return $cache[$cachekey];
643 * Returns the users in the specified group.
645 * @category group
646 * @param int $groupid The groupid to get the users for
647 * @param int $fields The fields to return
648 * @param int $sort optional sorting of returned users
649 * @return array Returns an array of the users for the specified group
651 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
652 global $DB;
654 if (empty($groupid)) {
655 return [];
658 $courseid = $DB->get_field('groups', 'courseid', ['id' => $groupid]);
659 if ($courseid === false) {
660 return [];
663 $select = "SELECT $fields";
664 $from = "FROM {user} u
665 JOIN {groups_members} gm ON gm.userid = u.id";
666 $where = "WHERE gm.groupid = :groupid";
667 $order = "ORDER BY $sort";
669 $params = ['groupid' => $groupid];
671 if (!\core_group\visibility::can_view_all_groups($courseid)) {
672 $from .= " JOIN {groups} g ON g.id = gm.groupid";
673 // Can view memberships of visibility is ALL, visibility is MEMBERS and current user is a member,
674 // or visibility is OWN and this is their membership.
675 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_member_visibility_where();
676 $params = array_merge($params, $visibilityparams);
677 $where .= ' AND ' . $visibilitywhere;
680 $sql = implode(PHP_EOL, [$select, $from, $where, $order]);
682 return $DB->get_records_sql($sql, $params);
687 * Returns the users in the specified grouping.
689 * @category group
690 * @param int $groupingid The groupingid to get the users for
691 * @param string $fields The fields to return
692 * @param string $sort optional sorting of returned users
693 * @return array|bool Returns an array of the users for the specified
694 * group or false if no users or an error returned.
696 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
697 global $DB;
699 return $DB->get_records_sql("SELECT $fields
700 FROM {user} u
701 INNER JOIN {groups_members} gm ON u.id = gm.userid
702 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
703 WHERE gg.groupingid = ?
704 ORDER BY $sort", array($groupingid));
708 * Returns effective groupmode used in course
710 * @category group
711 * @param stdClass $course course object.
712 * @return int group mode
714 function groups_get_course_groupmode($course) {
715 return $course->groupmode;
719 * Returns effective groupmode used in activity, course setting
720 * overrides activity setting if groupmodeforce enabled.
722 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
724 * @category group
725 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
726 * @param stdClass $course object optional course object to improve perf
727 * @return int group mode
729 function groups_get_activity_groupmode($cm, $course=null) {
730 if ($cm instanceof cm_info) {
731 return $cm->effectivegroupmode;
733 if (isset($course->id) and $course->id == $cm->course) {
734 //ok
735 } else {
736 // Get course object (reuse $COURSE if possible).
737 $course = get_course($cm->course, false);
740 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
744 * Print group menu selector for course level.
746 * @category group
747 * @param stdClass $course course object
748 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
749 * @param bool $return return as string instead of printing
750 * @return mixed void or string depending on $return param
752 function groups_print_course_menu($course, $urlroot, $return=false) {
753 global $USER, $OUTPUT;
755 if (!$groupmode = $course->groupmode) {
756 if ($return) {
757 return '';
758 } else {
759 return;
763 $context = context_course::instance($course->id);
764 $aag = has_capability('moodle/site:accessallgroups', $context);
766 $usergroups = array();
767 if ($groupmode == VISIBLEGROUPS or $aag) {
768 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
769 // Get user's own groups and put to the top.
770 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
771 } else {
772 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
775 $activegroup = groups_get_course_group($course, true, $allowedgroups);
777 $groupsmenu = array();
778 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
779 $groupsmenu[0] = get_string('allparticipants');
782 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
784 if ($groupmode == VISIBLEGROUPS) {
785 $grouplabel = get_string('groupsvisible');
786 } else {
787 $grouplabel = get_string('groupsseparate');
790 if ($aag and $course->defaultgroupingid) {
791 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
792 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
796 if (count($groupsmenu) == 1) {
797 $groupname = reset($groupsmenu);
798 $output = $grouplabel.': '.$groupname;
799 } else {
800 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
801 $select->label = $grouplabel;
802 $output = $OUTPUT->render($select);
805 $output = '<div class="groupselector">'.$output.'</div>';
807 if ($return) {
808 return $output;
809 } else {
810 echo $output;
815 * Turn an array of groups into an array of menu options.
816 * @param array $groups of group objects.
817 * @return array groupid => formatted group name.
819 function groups_list_to_menu($groups) {
820 $groupsmenu = array();
821 foreach ($groups as $group) {
822 $groupsmenu[$group->id] = format_string($group->name);
824 return $groupsmenu;
828 * Takes user's allowed groups and own groups and formats for use in group selector menu
829 * If user has allowed groups + own groups will add to an optgroup
830 * Own groups are removed from allowed groups
831 * @param array $allowedgroups All groups user is allowed to see
832 * @param array $usergroups Groups user belongs to
833 * @return array
835 function groups_sort_menu_options($allowedgroups, $usergroups) {
836 $useroptions = array();
837 if ($usergroups) {
838 $useroptions = groups_list_to_menu($usergroups);
840 // Remove user groups from other groups list.
841 foreach ($usergroups as $group) {
842 unset($allowedgroups[$group->id]);
846 $allowedoptions = array();
847 if ($allowedgroups) {
848 $allowedoptions = groups_list_to_menu($allowedgroups);
851 if ($useroptions && $allowedoptions) {
852 return array(
853 1 => array(get_string('mygroups', 'group') => $useroptions),
854 2 => array(get_string('othergroups', 'group') => $allowedoptions)
856 } else if ($useroptions) {
857 return $useroptions;
858 } else {
859 return $allowedoptions;
864 * Generates html to print menu selector for course level, listing all groups.
865 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
867 * @param stdclass $course course object.
868 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
869 * @param bool $update set this to true to update current active group based on the group param.
870 * @param int $activegroup Change group active to this group if $update set to true.
872 * @return string html or void
874 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
875 global $SESSION, $OUTPUT, $USER;
877 $groupmode = groups_get_course_groupmode($course);
878 $context = context_course::instance($course->id);
879 $groupsmenu = array();
881 if (has_capability('moodle/site:accessallgroups', $context)) {
882 $groupsmenu[0] = get_string('allparticipants');
883 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
884 } else {
885 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
888 $groupsmenu += groups_list_to_menu($allowedgroups);
890 if ($update) {
891 // Init activegroup array if necessary.
892 if (!isset($SESSION->activegroup)) {
893 $SESSION->activegroup = array();
895 if (!isset($SESSION->activegroup[$course->id])) {
896 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
898 if (empty($groupsmenu[$activegroup])) {
899 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
901 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
904 $grouplabel = get_string('groups');
905 if (count($groupsmenu) == 0) {
906 return '';
907 } else if (count($groupsmenu) == 1) {
908 $groupname = reset($groupsmenu);
909 $output = $grouplabel.': '.$groupname;
910 } else {
911 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
912 $select->label = $grouplabel;
913 $output = $OUTPUT->render($select);
916 return $output;
921 * Print group menu selector for activity.
923 * @category group
924 * @param stdClass|cm_info $cm course module object
925 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
926 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
927 * @param bool $return return as string instead of printing
928 * @param bool $hideallparticipants If true, this prevents the 'All participants'
929 * option from appearing in cases where it normally would. This is intended for
930 * use only by activities that cannot display all groups together. (Note that
931 * selecting this option does not prevent groups_get_activity_group from
932 * returning 0; it will still do that if the user has chosen 'all participants'
933 * in another activity, or not chosen anything.)
934 * @return mixed void or string depending on $return param
936 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
937 global $USER, $OUTPUT;
939 if ($urlroot instanceof moodle_url) {
940 // no changes necessary
942 } else {
943 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
944 // Display error if urlroot is not absolute (this causes the non-JS version to break)
945 debugging('groups_print_activity_menu requires absolute URL for ' .
946 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
947 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
948 DEBUG_DEVELOPER);
950 $urlroot = new moodle_url($urlroot);
953 if (!$groupmode = groups_get_activity_groupmode($cm)) {
954 if ($return) {
955 return '';
956 } else {
957 return;
961 $context = context_module::instance($cm->id);
962 $aag = has_capability('moodle/site:accessallgroups', $context);
964 $usergroups = array();
965 if ($groupmode == VISIBLEGROUPS or $aag) {
966 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true); // Any group in grouping.
967 // Get user's own groups and put to the top.
968 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
969 } else {
970 // Only assigned groups.
971 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
974 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
976 $groupsmenu = array();
977 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
978 $groupsmenu[0] = get_string('allparticipants');
981 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
983 if ($groupmode == VISIBLEGROUPS) {
984 $grouplabel = get_string('groupsvisible');
985 } else {
986 $grouplabel = get_string('groupsseparate');
989 if ($aag and $cm->groupingid) {
990 if ($grouping = groups_get_grouping($cm->groupingid)) {
991 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
995 if (count($groupsmenu) == 1) {
996 $groupname = reset($groupsmenu);
997 $output = $grouplabel.': '.$groupname;
998 } else {
999 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
1000 $select->label = $grouplabel;
1001 $output = $OUTPUT->render($select);
1004 $output = '<div class="groupselector">'.$output.'</div>';
1006 if ($return) {
1007 return $output;
1008 } else {
1009 echo $output;
1014 * Returns group active in course, changes the group by default if 'group' page param present
1016 * @category group
1017 * @param stdClass $course course bject
1018 * @param bool $update change active group if group param submitted
1019 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
1020 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
1022 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
1023 global $USER, $SESSION;
1025 if (!$groupmode = $course->groupmode) {
1026 // NOGROUPS used
1027 return false;
1030 $context = context_course::instance($course->id);
1031 if (has_capability('moodle/site:accessallgroups', $context)) {
1032 $groupmode = 'aag';
1035 if (!is_array($allowedgroups)) {
1036 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1037 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
1038 } else {
1039 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
1043 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
1045 // set new active group if requested
1046 $changegroup = optional_param('group', -1, PARAM_INT);
1047 if ($update and $changegroup != -1) {
1049 if ($changegroup == 0) {
1050 // do not allow changing to all groups without accessallgroups capability
1051 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1052 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
1055 } else {
1056 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1057 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
1062 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
1066 * Returns group active in activity, changes the group by default if 'group' page param present
1068 * @category group
1069 * @param stdClass|cm_info $cm course module object
1070 * @param bool $update change active group if group param submitted
1071 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
1072 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
1074 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
1075 global $USER, $SESSION;
1077 if (!$groupmode = groups_get_activity_groupmode($cm)) {
1078 // NOGROUPS used
1079 return false;
1082 $context = context_module::instance($cm->id);
1083 if (has_capability('moodle/site:accessallgroups', $context)) {
1084 $groupmode = 'aag';
1087 if (!is_array($allowedgroups)) {
1088 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1089 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true);
1090 } else {
1091 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
1095 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
1097 // set new active group if requested
1098 $changegroup = optional_param('group', -1, PARAM_INT);
1099 if ($update and $changegroup != -1) {
1101 if ($changegroup == 0) {
1102 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
1103 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1104 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
1107 } else {
1108 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1109 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
1114 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
1118 * Gets a list of groups that the user is allowed to access within the
1119 * specified activity.
1121 * @category group
1122 * @param stdClass|cm_info $cm Course-module
1123 * @param int $userid User ID (defaults to current user)
1124 * @return array An array of group objects, or false if none
1126 function groups_get_activity_allowed_groups($cm,$userid=0) {
1127 // Use current user by default
1128 global $USER;
1129 if(!$userid) {
1130 $userid=$USER->id;
1133 // Get groupmode for activity, taking into account course settings
1134 $groupmode=groups_get_activity_groupmode($cm);
1136 // If visible groups mode, or user has the accessallgroups capability,
1137 // then they can access all groups for the activity...
1138 $context = context_module::instance($cm->id);
1139 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
1140 return groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true);
1141 } else {
1142 // ...otherwise they can only access groups they belong to
1143 return groups_get_all_groups($cm->course, $userid, $cm->groupingid, 'g.*', false, true);
1148 * Determine if a given group is visible to user or not in a given context.
1150 * @since Moodle 2.6
1151 * @param int $groupid Group id to test. 0 for all groups.
1152 * @param stdClass $course Course object.
1153 * @param stdClass $cm Course module object.
1154 * @param int $userid user id to test against. Defaults to $USER.
1155 * @return boolean true if visible, false otherwise
1157 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
1158 global $USER;
1160 if (empty($userid)) {
1161 $userid = $USER->id;
1164 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1165 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1166 // Groups are not used, or everything is visible, no need to go any further.
1167 return true;
1170 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1171 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
1172 // User can see everything. Groupid = 0 is handled here as well.
1173 return true;
1174 } else if ($groupid != 0) {
1175 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
1176 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
1177 if (array_key_exists($groupid, $groups)) {
1178 // User can see the group.
1179 return true;
1182 return false;
1186 * Get sql and parameters that will return user ids for a group or groups
1188 * @param int|array $groupids Where this is an array of multiple groups, it will match on members of any of the groups
1189 * @param context $context Course context or a context within a course. Mandatory when $groupid = USERSWITHOUTGROUP
1190 * @param int $groupsjointype Join type logic used. Defaults to 'Any' (logical OR).
1191 * @return array($sql, $params)
1192 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1194 function groups_get_members_ids_sql($groupids, context $context = null, $groupsjointype = GROUPS_JOIN_ANY) {
1195 if (!is_array($groupids)) {
1196 $groupids = [$groupids];
1199 $groupjoin = groups_get_members_join($groupids, 'u.id', $context, $groupsjointype);
1201 $sql = "SELECT DISTINCT u.id
1202 FROM {user} u
1203 $groupjoin->joins
1204 WHERE u.deleted = 0";
1205 if (!empty($groupjoin->wheres)) {
1206 $sql .= ' AND '. $groupjoin->wheres;
1209 return array($sql, $groupjoin->params);
1213 * Returns array with SQL and parameters returning userids and concatenated group names for given course
1215 * This function uses 'gn[0-9]+_' prefix for table names and parameters
1217 * @param int $courseid
1218 * @param string $separator
1219 * @return array [$sql, $params]
1221 function groups_get_names_concat_sql(int $courseid, string $separator = ', '): array {
1222 global $DB;
1224 // Use unique prefix just in case somebody makes some SQL magic with the result.
1225 static $i = 0;
1226 $i++;
1227 $prefix = "gn{$i}_";
1229 $groupalias = $prefix . 'g';
1230 $groupmemberalias = $prefix . 'gm';
1231 $groupcourseparam = $prefix . 'courseid';
1233 $sqlgroupconcat = $DB->sql_group_concat("{$groupalias}.name", $separator, "{$groupalias}.name");
1235 $sql = "SELECT {$groupmemberalias}.userid, {$sqlgroupconcat} AS groupnames
1236 FROM {groups} {$groupalias}
1237 JOIN {groups_members} {$groupmemberalias} ON {$groupmemberalias}.groupid = {$groupalias}.id
1238 WHERE {$groupalias}.courseid = :{$groupcourseparam}
1239 GROUP BY {$groupmemberalias}.userid";
1241 return [$sql, [$groupcourseparam => $courseid]];
1245 * Get sql join to return users in a group
1247 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1248 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1249 * @param context $context Course context or a context within a course. Mandatory when $groupids includes USERSWITHOUTGROUP
1250 * @param int $jointype Join type logic used. Defaults to 'Any' (logical OR).
1251 * @return \core\dml\sql_join Contains joins, wheres, params
1252 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1254 function groups_get_members_join($groupids, $useridcolumn, context $context = null, int $jointype = GROUPS_JOIN_ANY) {
1255 global $DB;
1257 // Use unique prefix just in case somebody makes some SQL magic with the result.
1258 static $i = 0;
1259 $i++;
1260 $prefix = 'gm' . $i . '_';
1262 if (!is_array($groupids)) {
1263 $groupids = $groupids ? [$groupids] : [];
1266 $joins = [];
1267 $where = '';
1268 $param = [];
1270 $coursecontext = (!empty($context)) ? $context->get_course_context() : null;
1271 if (in_array(USERSWITHOUTGROUP, $groupids) && empty($coursecontext)) {
1272 // Throw an exception if $context is empty or invalid because it's needed to get the users without any group.
1273 throw new coding_exception('Missing or wrong $context parameter in an attempt to get members without any group');
1275 // Can we view hidden groups within a course?
1276 [$ualias] = explode('.', $useridcolumn);
1277 $viewhidden = false;
1278 if (!empty($coursecontext)) {
1279 $viewhidden = \core_group\visibility::can_view_all_groups($coursecontext->instanceid);
1282 // Handle cases where we need to include/exclude users not in any groups.
1283 if (($nogroupskey = array_search(USERSWITHOUTGROUP, $groupids)) !== false) {
1284 $visibilityjoin = '';
1285 $visibilitywhere = '';
1287 if (!$viewhidden) {
1288 $visibilityjoin = 'JOIN {user} u ON u.id = m.userid';
1289 [$visibilitywhere, $visibilityparams] = \core_group\visibility::sql_member_visibility_where('g', 'm');
1290 $param = array_merge($param, $visibilityparams);
1291 $visibilitywhere = 'WHERE ' . $visibilitywhere;
1293 // Get members without any group, or only in groups we cannot see membership of.
1294 $joins[] = "LEFT JOIN (
1295 SELECT g.courseid, m.groupid, m.userid
1296 FROM {groups_members} m
1297 JOIN {groups} g ON g.id = m.groupid
1298 {$visibilityjoin}
1299 {$visibilitywhere}
1300 ) {$prefix}gm ON ({$prefix}gm.userid = {$useridcolumn} AND {$prefix}gm.courseid = :{$prefix}gcourseid)";
1302 // Join type 'None' when filtering by 'no groups' means match users in at least one group.
1303 if ($jointype == GROUPS_JOIN_NONE) {
1304 $where = "{$prefix}gm.userid IS NOT NULL";
1305 } else {
1306 // All other cases need to match users not in any group.
1307 $where = "{$prefix}gm.userid IS NULL";
1310 $param["{$prefix}gcourseid"] = $coursecontext->instanceid;
1311 unset($groupids[$nogroupskey]);
1314 // Handle any specified groups that need to be included.
1315 if (!empty($groupids)) {
1316 switch ($jointype) {
1317 case GROUPS_JOIN_ALL:
1318 // Handle matching all of the provided groups (logical AND).
1319 $joinallwheres = [];
1320 $aliaskey = 0;
1321 foreach ($groupids as $groupid) {
1322 $gmalias = "{$prefix}gm{$aliaskey}";
1323 $aliaskey++;
1324 $joins[] = "LEFT JOIN {groups_members} {$gmalias}
1325 ON ({$gmalias}.userid = {$useridcolumn} AND {$gmalias}.groupid = :{$gmalias}param)";
1326 $joinallwheres[] = "{$gmalias}.userid IS NOT NULL";
1327 $param["{$gmalias}param"] = $groupid;
1328 if (!$viewhidden) {
1329 $galias = "{$prefix}g{$aliaskey}";
1330 $joins[] = "LEFT JOIN {groups} {$galias} ON {$gmalias}.groupid = {$galias}.id";
1331 [$visibilitywhere, $visibilityparams] = \core_group\visibility::sql_member_visibility_where(
1332 $galias,
1333 $gmalias,
1334 $ualias,
1335 $prefix . $aliaskey . '_'
1337 $joinallwheres[] = $visibilitywhere;
1338 $param = array_merge($param, $visibilityparams);
1342 // Members of all of the specified groups only.
1343 if (empty($where)) {
1344 $where = '(' . implode(' AND ', $joinallwheres) . ')';
1345 } else {
1346 // Members of the specified groups and also no groups.
1347 // NOTE: This will always return no results, because you cannot be in specified groups and also be in no groups.
1348 $where = '(' . $where . ' AND ' . implode(' AND ', $joinallwheres) . ')';
1351 break;
1353 case GROUPS_JOIN_ANY:
1354 // Handle matching any of the provided groups (logical OR).
1355 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1357 $joins[] = "LEFT JOIN {groups_members} {$prefix}gm2
1358 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1359 $param = array_merge($param, $groupsparams);
1361 // Members of any of the specified groups only.
1362 if (empty($where)) {
1363 $where = "{$prefix}gm2.userid IS NOT NULL";
1364 } else {
1365 // Members of any of the specified groups or no groups.
1366 $where = "({$where} OR {$prefix}gm2.userid IS NOT NULL)";
1369 if (!$viewhidden) {
1370 $joins[] = "LEFT JOIN {groups} {$prefix}g2 ON {$prefix}gm2.groupid = {$prefix}g2.id";
1371 [$visibilitywhere, $visibilityparams] = \core_group\visibility::sql_member_visibility_where(
1372 $prefix . 'g2',
1373 $prefix . 'gm2',
1374 $ualias,
1375 $prefix . 'param_'
1377 $where .= ' AND ' . $visibilitywhere;
1378 $param = array_merge($param, $visibilityparams);
1381 break;
1383 case GROUPS_JOIN_NONE:
1384 // Handle matching none of the provided groups (logical NOT).
1385 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1387 $joins[] = "LEFT JOIN {groups_members} {$prefix}gm2
1388 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1389 $param = array_merge($param, $groupsparams);
1391 // Members of none of the specified groups only.
1392 if (empty($where)) {
1393 $where = "{$prefix}gm2.userid IS NULL";
1394 } else {
1395 // Members of any unspecified groups (not a member of the specified groups, and not a member of no groups).
1396 $where = "({$where} AND {$prefix}gm2.userid IS NULL)";
1399 if (!$viewhidden) {
1400 $joins[] = "LEFT JOIN {groups} {$prefix}g2 ON {$prefix}gm2.groupid = {$prefix}g2.id";
1401 [$visibilitywhere, $visibilityparams] = \core_group\visibility::sql_member_visibility_where(
1402 $prefix . 'g2',
1403 $prefix . 'gm2',
1404 $ualias
1406 $where .= ' OR NOT ' . $visibilitywhere;
1407 $param = array_merge($param, $visibilityparams);
1410 break;
1414 return new \core\dml\sql_join(implode("\n", $joins), $where, $param);
1418 * Internal method, sets up $SESSION->activegroup and verifies previous value
1420 * @param int $courseid
1421 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1422 * @param int $groupingid 0 means all groups
1423 * @param array $allowedgroups list of groups user can see
1425 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1426 global $SESSION, $USER;
1428 // init activegroup array if necessary
1429 if (!isset($SESSION->activegroup)) {
1430 $SESSION->activegroup = array();
1432 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1433 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1436 // make sure that the current group info is ok
1437 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1438 // active group does not exist anymore or is 0
1439 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1440 // do not do this if all groups selected and groupmode is not separate
1441 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1445 // set up defaults if necessary
1446 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1447 if ($groupmode == 'aag') {
1448 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1450 } else if ($allowedgroups) {
1451 if ($groupmode != SEPARATEGROUPS
1452 && $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid, 'g.*', false, true)) {
1453 $firstgroup = reset($mygroups);
1454 } else {
1455 $firstgroup = reset($allowedgroups);
1457 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1459 } else {
1460 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1461 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1462 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1468 * Caches group data for a particular course to speed up subsequent requests.
1470 * @param int $courseid The course id to cache data for.
1471 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1472 * @return stdClass A data object containing groups, groupings, and mappings.
1474 function groups_cache_groupdata($courseid, cache $cache = null) {
1475 global $DB;
1477 if ($cache === null) {
1478 // Initialise a cache if we wern't given one.
1479 $cache = cache::make('core', 'groupdata');
1482 // Get the groups that belong to the course.
1483 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1484 // Get the groupings that belong to the course.
1485 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1487 if (!is_array($groups)) {
1488 $groups = array();
1491 if (!is_array($groupings)) {
1492 $groupings = array();
1495 if (!empty($groupings)) {
1496 // Finally get the mappings between the two.
1497 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1498 $mappings = $DB->get_records_sql("
1499 SELECT gg.id, gg.groupingid, gg.groupid
1500 FROM {groupings_groups} gg
1501 JOIN {groups} g ON g.id = gg.groupid
1502 WHERE gg.groupingid $insql
1503 ORDER BY g.name ASC", $params);
1504 } else {
1505 $mappings = array();
1508 // Prepare the data array.
1509 $data = new stdClass;
1510 $data->groups = $groups;
1511 $data->groupings = $groupings;
1512 $data->mappings = $mappings;
1513 // Cache the data.
1514 $cache->set($courseid, $data);
1515 // Finally return it so it can be used if desired.
1516 return $data;
1520 * Gets group data for a course.
1522 * This returns an object with the following properties:
1523 * - groups : An array of all the groups in the course.
1524 * - groupings : An array of all the groupings within the course.
1525 * - mappings : An array of group to grouping mappings.
1527 * @param int $courseid The course id to get data for.
1528 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1529 * @return stdClass
1531 function groups_get_course_data($courseid, cache $cache = null) {
1532 if ($cache === null) {
1533 // Initialise a cache if we wern't given one.
1534 $cache = cache::make('core', 'groupdata');
1536 // Try to retrieve it from the cache.
1537 $data = $cache->get($courseid);
1538 if ($data === false) {
1539 $data = groups_cache_groupdata($courseid, $cache);
1541 return $data;
1545 * Determine if the current user can see at least one of the groups of the specified user.
1547 * @param stdClass $course Course object.
1548 * @param int $userid user id to check against.
1549 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1550 * @return boolean true if visible, false otherwise
1551 * @since Moodle 2.9
1553 function groups_user_groups_visible($course, $userid, $cm = null) {
1554 global $USER;
1556 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1557 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1558 // Groups are not used, or everything is visible, no need to go any further.
1559 return true;
1562 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1563 if (has_capability('moodle/site:accessallgroups', $context)) {
1564 // User can see everything.
1565 return true;
1566 } else {
1567 // Group mode is separate, and user doesn't have access all groups capability.
1568 if (empty($cm)) {
1569 $usergroups = groups_get_all_groups($course->id, $userid);
1570 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1571 } else {
1572 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1573 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1576 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1577 if (!empty($samegroups)) {
1578 // We share groups!
1579 return true;
1582 return false;
1586 * Returns the users in the specified groups.
1588 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1590 * @param array $groupsids The list of groups ids to check
1591 * @param array $extrafields extra fields to be included in result
1592 * @param int $sort optional sorting of returned users
1593 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1594 * @since Moodle 3.3
1596 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1597 global $DB;
1599 $wheres = [];
1600 $userfieldsapi = \core_user\fields::for_userpic()->including(...($extrafields ?? []));
1601 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1602 list($insql, $params) = $DB->get_in_or_equal($groupsids, SQL_PARAMS_NAMED);
1603 $wheres[] = "gm.groupid $insql";
1605 $courseids = $DB->get_fieldset_sql("SELECT DISTINCT courseid FROM {groups} WHERE id $insql", $params);
1607 if (count($courseids) > 1) {
1608 // Groups from multiple courses. Have to check permission in system context.
1609 $context = context_system::instance();
1610 } else {
1611 $courseid = reset($courseids);
1612 $context = context_course::instance($courseid);
1615 if (!has_capability('moodle/course:viewhiddengroups', $context)) {
1616 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_member_visibility_where();
1617 $params = array_merge($params, $visibilityparams);
1618 $wheres[] = $visibilitywhere;
1621 $where = implode(' AND ', $wheres);
1622 return $DB->get_records_sql("SELECT $userfields
1623 FROM {user} u
1624 JOIN {groups_members} gm ON u.id = gm.userid
1625 JOIN {groups} g ON g.id = gm.groupid
1626 WHERE {$where}
1627 GROUP BY $userfields
1628 ORDER BY $sort", $params);
1632 * Returns users who share group membership with the specified user in the given actiivty.
1634 * @param stdClass|cm_info $cm course module
1635 * @param int $userid user id (empty for current user)
1636 * @return array a list of user
1637 * @since Moodle 3.3
1639 function groups_get_activity_shared_group_members($cm, $userid = null) {
1640 global $USER;
1642 if (empty($userid)) {
1643 $userid = $USER->id;
1646 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1647 // No groups no users.
1648 if (empty($groupsids)) {
1649 return [];
1651 return groups_get_groups_members($groupsids);