MDL-78962 core/loadingicon: remove jQuery requirement in the API
[moodle.git] / lib / grouplib.php
bloba6f9388fd1aad135ac32c53627ff8d02e3badbc9
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) {
215 global $DB;
216 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
220 * Get the grouping object
222 * @category group
223 * @param int $groupingid ID of the group.
224 * @param string $fields
225 * @param int $strictness (IGNORE_MISSING - default)
226 * @return stdClass group object
228 function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING) {
229 global $DB;
230 return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
234 * Gets array of all groups in a specified course (subject to the conditions imposed by the other arguments).
236 * If a user does not have moodle/course:viewhiddengroups, the list of groups and members will be restricted based on the
237 * visibility setting of each group.
239 * @category group
240 * @param int $courseid The id of the course.
241 * @param int|int[] $userid optional user id or array of ids, returns only groups continaing one or more of those users.
242 * @param int $groupingid optional returns only groups in the specified grouping.
243 * @param string $fields defaults to g.*. This allows you to vary which fields are returned.
244 * If $groupingid is specified, the groupings_groups table will be available with alias gg.
245 * If $userid is specified, the groups_members table will be available as gm.
246 * @param bool $withmembers if true return an extra field members (int[]) which is the list of userids that
247 * are members of each group. For this to work, g.id (or g.*) must be included in $fields.
248 * In this case, the final results will always be an array indexed by group id.
249 * @param bool $participationonly Only return groups where the participation field is true.
250 * @return array returns an array of the group objects (unless you have done something very weird
251 * with the $fields option).
253 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false, $participationonly = false) {
254 global $DB, $USER;
256 // We need to check that we each field in the fields list belongs to the group table and that it has not being
257 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
258 $knownfields = true;
259 if ($fields !== 'g.*') {
260 // Quickly check if the first field is no longer g.id as using the
261 // cache will return an array indexed differently than when expect
262 if (strpos($fields, 'g.*') !== 0 && strpos($fields, 'g.id') !== 0) {
263 $knownfields = false;
264 } else {
265 $fieldbits = explode(',', $fields);
266 foreach ($fieldbits as $bit) {
267 $bit = trim($bit);
268 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
269 $knownfields = false;
270 break;
276 if (empty($userid) && $knownfields && !$withmembers && \core_group\visibility::can_view_all_groups($courseid)) {
277 // We can use the cache.
278 $data = groups_get_course_data($courseid);
279 if (empty($groupingid)) {
280 // All groups.. Easy!
281 $groups = $data->groups;
282 } else {
283 $groups = array();
284 foreach ($data->mappings as $mapping) {
285 if ($mapping->groupingid != $groupingid) {
286 continue;
288 if (isset($data->groups[$mapping->groupid])) {
289 $groups[$mapping->groupid] = $data->groups[$mapping->groupid];
293 if ($participationonly) {
294 $groups = array_filter($groups, fn($group) => $group->participation);
296 // Yay! We could use the cache. One more query saved.
297 return $groups;
300 $params = [];
301 $userfrom = '';
302 $userwhere = '';
303 if (!empty($userid)) {
304 list($usql, $params) = $DB->get_in_or_equal($userid);
305 $userfrom = "JOIN {groups_members} gm ON gm.groupid = g.id";
306 $userwhere = "AND gm.userid $usql";
309 $groupingfrom = '';
310 $groupingwhere = '';
311 if (!empty($groupingid)) {
312 $groupingfrom = "JOIN {groupings_groups} gg ON gg.groupid = g.id";
313 $groupingwhere = "AND gg.groupingid = ?";
314 $params[] = $groupingid;
317 array_unshift($params, $courseid);
319 $visibilityfrom = '';
320 $visibilitywhere = '';
321 $viewhidden = has_capability('moodle/course:viewhiddengroups', context_course::instance($courseid));
322 if (!$viewhidden) {
323 // Apply group visibility restrictions. Only return groups where visibility is ALL, or the current user is a member and the
324 // visibility is MEMBERS or OWN.
325 $userids = [];
326 if (empty($userid)) {
327 $userids = [$USER->id];
328 $visibilityfrom = "LEFT JOIN {groups_members} gm ON gm.groupid = g.id AND gm.userid = ?";
330 [$insql, $inparams] = $DB->get_in_or_equal([GROUPS_VISIBILITY_MEMBERS, GROUPS_VISIBILITY_OWN]);
331 $visibilitywhere = "AND (g.visibility = ? OR (g.visibility $insql AND gm.id IS NOT NULL))";
332 $params = array_merge(
333 $userids,
334 $params,
335 [GROUPS_VISIBILITY_ALL],
336 $inparams
340 $participationwhere = '';
341 if ($participationonly) {
342 $participationwhere = "AND g.participation = ?";
343 $params = array_merge($params, [1]);
346 $results = $DB->get_records_sql("
347 SELECT $fields
348 FROM {groups} g
349 $userfrom
350 $groupingfrom
351 $visibilityfrom
352 WHERE g.courseid = ?
353 $userwhere
354 $groupingwhere
355 $visibilitywhere
356 $participationwhere
357 ORDER BY g.name ASC", $params);
359 if (!$withmembers) {
360 return $results;
363 // We also want group members. We do this in a separate query, becuse the above
364 // query will return a lot of data (e.g. g.description) for each group, and
365 // some groups may contain hundreds of members. We don't want the results
366 // to contain hundreds of copies of long descriptions.
367 $groups = [];
368 foreach ($results as $row) {
369 $groups[$row->id] = $row;
370 $groups[$row->id]->members = [];
373 $gmvisibilityfrom = '';
374 $gmvisibilitywhere = '';
375 $gmvisibilityparams = [];
376 if (!$viewhidden) {
377 // Only return membership records where visibility is ALL, visibility is MEMBERS and the current user is a member,
378 // or visibility is OWN and the record is for the current user.
379 $gmvisibilityfrom = "
380 JOIN {groups} g ON gm.groupid = g.id
382 $gmvisibilitywhere = "
383 AND (g.visibility = ?
384 OR (g.visibility = ?
385 AND g.id IN (SELECT gm2.groupid FROM {groups_members} gm2 WHERE gm2.groupid = g.id AND gm2.userid = ?))
386 OR (g.visibility = ?
387 AND gm.userid = ?))";
388 $gmvisibilityparams = [
389 GROUPS_VISIBILITY_ALL,
390 GROUPS_VISIBILITY_MEMBERS,
391 $USER->id,
392 GROUPS_VISIBILITY_OWN,
393 $USER->id
397 $groupmembers = [];
398 if (!empty($groups)) {
399 [$gmin, $gmparams] = $DB->get_in_or_equal(array_keys($groups));
400 $params = array_merge($gmparams, $gmvisibilityparams);
401 $gmsql = "
402 SELECT gm.*
403 FROM {groups_members} gm
404 $gmvisibilityfrom
405 WHERE gm.groupid $gmin
406 $gmvisibilitywhere";
407 $groupmembers = $DB->get_records_sql($gmsql, $params);
410 foreach ($groupmembers as $gm) {
411 $groups[$gm->groupid]->members[$gm->userid] = $gm->userid;
413 return $groups;
417 * Gets array of all groups in current user.
419 * @since Moodle 2.5
420 * @category group
421 * @return array Returns an array of the group objects.
423 function groups_get_my_groups() {
424 global $DB, $USER;
426 $params = ['userid' => $USER->id];
428 $viewhidden = has_capability('moodle/course:viewhiddengroups', context_system::instance());
429 $visibilitywhere = '';
430 if (!$viewhidden) {
431 $params['novisibility'] = GROUPS_VISIBILITY_NONE;
432 $visibilitywhere = 'AND g.visibility != :novisibility';
435 return $DB->get_records_sql("SELECT *
436 FROM {groups_members} gm
437 JOIN {groups} g
438 ON g.id = gm.groupid
439 WHERE gm.userid = :userid
440 $visibilitywhere
441 ORDER BY name ASC", $params);
445 * Returns info about user's groups in course.
447 * @category group
448 * @param int $courseid
449 * @param int $userid $USER if not specified
450 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
452 function groups_get_user_groups($courseid, $userid=0) {
453 global $USER, $DB;
455 if (empty($courseid)) {
456 return ['0' => []];
459 if (empty($userid)) {
460 $userid = $USER->id;
463 $usergroups = false;
464 $viewhidden = has_capability('moodle/course:viewhiddengroups', context_course::instance($courseid));
465 $viewall = \core_group\visibility::can_view_all_groups($courseid);
467 $cache = cache::make('core', 'user_group_groupings');
469 if ($viewall) {
470 // Try to retrieve group ids from the cache.
471 $usergroups = $cache->get($userid);
474 if ($usergroups === false) {
476 $sql = "SELECT g.id, g.courseid, gg.groupingid
477 FROM {groups} g
478 JOIN {groups_members} gm ON gm.groupid = g.id
479 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
480 WHERE gm.userid = :userid";
482 $params = ['userid' => $userid];
484 if (!$viewhidden) {
485 // Apply visibility restrictions.
486 // Everyone can see who is in groups with ALL visibility.
487 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_group_visibility_where($userid);
488 $sql .= " AND " . $visibilitywhere;
489 $params = array_merge($params, $visibilityparams);
492 $sql .= ' ORDER BY g.id'; // To make results deterministic.
494 $rs = $DB->get_recordset_sql($sql, $params);
496 $usergroups = array();
497 $allgroups = array();
499 foreach ($rs as $group) {
500 if (!array_key_exists($group->courseid, $allgroups)) {
501 $allgroups[$group->courseid] = array();
503 $allgroups[$group->courseid][$group->id] = $group->id;
504 if (!array_key_exists($group->courseid, $usergroups)) {
505 $usergroups[$group->courseid] = array();
507 if (is_null($group->groupingid)) {
508 continue;
510 if (!array_key_exists($group->groupingid, $usergroups[$group->courseid])) {
511 $usergroups[$group->courseid][$group->groupingid] = array();
513 $usergroups[$group->courseid][$group->groupingid][$group->id] = $group->id;
515 $rs->close();
517 foreach (array_keys($allgroups) as $cid) {
518 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
521 if ($viewall) {
522 // Cache the data, if we got the full list of groups.
523 $cache->set($userid, $usergroups);
527 if (array_key_exists($courseid, $usergroups)) {
528 return $usergroups[$courseid];
529 } else {
530 return array('0' => array());
535 * Gets an array of all groupings in a specified course. This value is cached
536 * for a single course (so you can call it repeatedly for the same course
537 * without a performance penalty).
539 * @category group
540 * @param int $courseid return all groupings from course with this courseid
541 * @return array Returns an array of the grouping objects (empty if none)
543 function groups_get_all_groupings($courseid) {
544 $data = groups_get_course_data($courseid);
545 return $data->groupings;
549 * Determines if the user is a member of the given group.
551 * If $userid is null, use the global object.
553 * @category group
554 * @param int $groupid The group to check for membership.
555 * @param int $userid The user to check against the group.
556 * @return bool True if the user is a member, false otherwise.
558 function groups_is_member($groupid, $userid=null) {
559 global $USER, $DB;
561 if (!$userid) {
562 $userid = $USER->id;
565 $courseid = $DB->get_field('groups', 'courseid', ['id' => $groupid]);
566 if (!$courseid) {
567 return false;
570 if (\core_group\visibility::can_view_all_groups($courseid)) {
571 return $DB->record_exists('groups_members', ['groupid' => $groupid, 'userid' => $userid]);
574 $sql = "SELECT *
575 FROM {groups_members} gm
576 JOIN {groups} g ON gm.groupid = g.id
577 WHERE g.id = :groupid
578 AND gm.userid = :userid";
579 $params = ['groupid' => $groupid, 'userid' => $userid];
581 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_group_visibility_where($userid);
583 $sql .= " AND " . $visibilitywhere;
584 $params = array_merge($params, $visibilityparams);
586 return $DB->record_exists_sql($sql, $params);
590 * Determines if current or specified is member of any active group in activity
592 * @category group
593 * @staticvar array $cache
594 * @param stdClass|cm_info $cm course module object
595 * @param int $userid id of user, null means $USER->id
596 * @return bool true if user member of at least one group used in activity
598 function groups_has_membership($cm, $userid=null) {
599 global $CFG, $USER, $DB;
601 static $cache = array();
603 if (empty($userid)) {
604 $userid = $USER->id;
607 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
608 if (isset($cache[$cachekey])) {
609 return($cache[$cachekey]);
612 if ($cm->groupingid) {
613 // find out if member of any group in selected activity grouping
614 $sql = "SELECT 'x'
615 FROM {groups_members} gm, {groupings_groups} gg
616 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
617 $params = array($userid, $cm->groupingid);
619 } else {
620 // no grouping used - check all groups in course
621 $sql = "SELECT 'x'
622 FROM {groups_members} gm, {groups} g
623 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
624 $params = array($userid, $cm->course);
627 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
629 return $cache[$cachekey];
633 * Returns the users in the specified group.
635 * @category group
636 * @param int $groupid The groupid to get the users for
637 * @param int $fields The fields to return
638 * @param int $sort optional sorting of returned users
639 * @return array|bool Returns an array of the users for the specified
640 * group or false if no users or an error returned.
642 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
643 global $DB, $USER;
645 if (empty($groupid)) {
646 return [];
649 $courseid = $DB->get_field('groups', 'courseid', ['id' => $groupid]);
651 $select = "SELECT $fields";
652 $from = "FROM {user} u
653 JOIN {groups_members} gm ON gm.userid = u.id";
654 $where = "WHERE gm.groupid = :groupid";
655 $order = "ORDER BY $sort";
657 $params = ['groupid' => $groupid];
659 if (!\core_group\visibility::can_view_all_groups($courseid)) {
660 $from .= " JOIN {groups} g ON g.id = gm.groupid";
661 // Can view memberships of visibility is ALL, visibility is MEMBERS and current user is a member,
662 // or visibility is OWN and this is their membership.
663 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_member_visibility_where();
664 $params = array_merge($params, $visibilityparams);
665 $where .= $visibilitywhere;
668 $sql = implode(PHP_EOL, [$select, $from, $where, $order]);
670 return $DB->get_records_sql($sql, $params);
675 * Returns the users in the specified grouping.
677 * @category group
678 * @param int $groupingid The groupingid to get the users for
679 * @param string $fields The fields to return
680 * @param string $sort optional sorting of returned users
681 * @return array|bool Returns an array of the users for the specified
682 * group or false if no users or an error returned.
684 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
685 global $DB;
687 return $DB->get_records_sql("SELECT $fields
688 FROM {user} u
689 INNER JOIN {groups_members} gm ON u.id = gm.userid
690 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
691 WHERE gg.groupingid = ?
692 ORDER BY $sort", array($groupingid));
696 * Returns effective groupmode used in course
698 * @category group
699 * @param stdClass $course course object.
700 * @return int group mode
702 function groups_get_course_groupmode($course) {
703 return $course->groupmode;
707 * Returns effective groupmode used in activity, course setting
708 * overrides activity setting if groupmodeforce enabled.
710 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
712 * @category group
713 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
714 * @param stdClass $course object optional course object to improve perf
715 * @return int group mode
717 function groups_get_activity_groupmode($cm, $course=null) {
718 if ($cm instanceof cm_info) {
719 return $cm->effectivegroupmode;
721 if (isset($course->id) and $course->id == $cm->course) {
722 //ok
723 } else {
724 // Get course object (reuse $COURSE if possible).
725 $course = get_course($cm->course, false);
728 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
732 * Print group menu selector for course level.
734 * @category group
735 * @param stdClass $course course object
736 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
737 * @param bool $return return as string instead of printing
738 * @return mixed void or string depending on $return param
740 function groups_print_course_menu($course, $urlroot, $return=false) {
741 global $USER, $OUTPUT;
743 if (!$groupmode = $course->groupmode) {
744 if ($return) {
745 return '';
746 } else {
747 return;
751 $context = context_course::instance($course->id);
752 $aag = has_capability('moodle/site:accessallgroups', $context);
754 $usergroups = array();
755 if ($groupmode == VISIBLEGROUPS or $aag) {
756 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
757 // Get user's own groups and put to the top.
758 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
759 } else {
760 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
763 $activegroup = groups_get_course_group($course, true, $allowedgroups);
765 $groupsmenu = array();
766 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
767 $groupsmenu[0] = get_string('allparticipants');
770 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
772 if ($groupmode == VISIBLEGROUPS) {
773 $grouplabel = get_string('groupsvisible');
774 } else {
775 $grouplabel = get_string('groupsseparate');
778 if ($aag and $course->defaultgroupingid) {
779 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
780 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
784 if (count($groupsmenu) == 1) {
785 $groupname = reset($groupsmenu);
786 $output = $grouplabel.': '.$groupname;
787 } else {
788 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
789 $select->label = $grouplabel;
790 $output = $OUTPUT->render($select);
793 $output = '<div class="groupselector">'.$output.'</div>';
795 if ($return) {
796 return $output;
797 } else {
798 echo $output;
803 * Turn an array of groups into an array of menu options.
804 * @param array $groups of group objects.
805 * @return array groupid => formatted group name.
807 function groups_list_to_menu($groups) {
808 $groupsmenu = array();
809 foreach ($groups as $group) {
810 $groupsmenu[$group->id] = format_string($group->name);
812 return $groupsmenu;
816 * Takes user's allowed groups and own groups and formats for use in group selector menu
817 * If user has allowed groups + own groups will add to an optgroup
818 * Own groups are removed from allowed groups
819 * @param array $allowedgroups All groups user is allowed to see
820 * @param array $usergroups Groups user belongs to
821 * @return array
823 function groups_sort_menu_options($allowedgroups, $usergroups) {
824 $useroptions = array();
825 if ($usergroups) {
826 $useroptions = groups_list_to_menu($usergroups);
828 // Remove user groups from other groups list.
829 foreach ($usergroups as $group) {
830 unset($allowedgroups[$group->id]);
834 $allowedoptions = array();
835 if ($allowedgroups) {
836 $allowedoptions = groups_list_to_menu($allowedgroups);
839 if ($useroptions && $allowedoptions) {
840 return array(
841 1 => array(get_string('mygroups', 'group') => $useroptions),
842 2 => array(get_string('othergroups', 'group') => $allowedoptions)
844 } else if ($useroptions) {
845 return $useroptions;
846 } else {
847 return $allowedoptions;
852 * Generates html to print menu selector for course level, listing all groups.
853 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
855 * @param stdclass $course course object.
856 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
857 * @param bool $update set this to true to update current active group based on the group param.
858 * @param int $activegroup Change group active to this group if $update set to true.
860 * @return string html or void
862 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
863 global $SESSION, $OUTPUT, $USER;
865 $groupmode = groups_get_course_groupmode($course);
866 $context = context_course::instance($course->id);
867 $groupsmenu = array();
869 if (has_capability('moodle/site:accessallgroups', $context)) {
870 $groupsmenu[0] = get_string('allparticipants');
871 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
872 } else {
873 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
876 $groupsmenu += groups_list_to_menu($allowedgroups);
878 if ($update) {
879 // Init activegroup array if necessary.
880 if (!isset($SESSION->activegroup)) {
881 $SESSION->activegroup = array();
883 if (!isset($SESSION->activegroup[$course->id])) {
884 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
886 if (empty($groupsmenu[$activegroup])) {
887 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
889 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
892 $grouplabel = get_string('groups');
893 if (count($groupsmenu) == 0) {
894 return '';
895 } else if (count($groupsmenu) == 1) {
896 $groupname = reset($groupsmenu);
897 $output = $grouplabel.': '.$groupname;
898 } else {
899 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
900 $select->label = $grouplabel;
901 $output = $OUTPUT->render($select);
904 return $output;
909 * Print group menu selector for activity.
911 * @category group
912 * @param stdClass|cm_info $cm course module object
913 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
914 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
915 * @param bool $return return as string instead of printing
916 * @param bool $hideallparticipants If true, this prevents the 'All participants'
917 * option from appearing in cases where it normally would. This is intended for
918 * use only by activities that cannot display all groups together. (Note that
919 * selecting this option does not prevent groups_get_activity_group from
920 * returning 0; it will still do that if the user has chosen 'all participants'
921 * in another activity, or not chosen anything.)
922 * @return mixed void or string depending on $return param
924 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
925 global $USER, $OUTPUT;
927 if ($urlroot instanceof moodle_url) {
928 // no changes necessary
930 } else {
931 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
932 // Display error if urlroot is not absolute (this causes the non-JS version to break)
933 debugging('groups_print_activity_menu requires absolute URL for ' .
934 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
935 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
936 DEBUG_DEVELOPER);
938 $urlroot = new moodle_url($urlroot);
941 if (!$groupmode = groups_get_activity_groupmode($cm)) {
942 if ($return) {
943 return '';
944 } else {
945 return;
949 $context = context_module::instance($cm->id);
950 $aag = has_capability('moodle/site:accessallgroups', $context);
952 $usergroups = array();
953 if ($groupmode == VISIBLEGROUPS or $aag) {
954 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true); // Any group in grouping.
955 // Get user's own groups and put to the top.
956 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
957 } else {
958 // Only assigned groups.
959 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
962 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
964 $groupsmenu = array();
965 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
966 $groupsmenu[0] = get_string('allparticipants');
969 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
971 if ($groupmode == VISIBLEGROUPS) {
972 $grouplabel = get_string('groupsvisible');
973 } else {
974 $grouplabel = get_string('groupsseparate');
977 if ($aag and $cm->groupingid) {
978 if ($grouping = groups_get_grouping($cm->groupingid)) {
979 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
983 if (count($groupsmenu) == 1) {
984 $groupname = reset($groupsmenu);
985 $output = $grouplabel.': '.$groupname;
986 } else {
987 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
988 $select->label = $grouplabel;
989 $output = $OUTPUT->render($select);
992 $output = '<div class="groupselector">'.$output.'</div>';
994 if ($return) {
995 return $output;
996 } else {
997 echo $output;
1002 * Returns group active in course, changes the group by default if 'group' page param present
1004 * @category group
1005 * @param stdClass $course course bject
1006 * @param bool $update change active group if group param submitted
1007 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
1008 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
1010 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
1011 global $USER, $SESSION;
1013 if (!$groupmode = $course->groupmode) {
1014 // NOGROUPS used
1015 return false;
1018 $context = context_course::instance($course->id);
1019 if (has_capability('moodle/site:accessallgroups', $context)) {
1020 $groupmode = 'aag';
1023 if (!is_array($allowedgroups)) {
1024 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1025 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
1026 } else {
1027 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
1031 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
1033 // set new active group if requested
1034 $changegroup = optional_param('group', -1, PARAM_INT);
1035 if ($update and $changegroup != -1) {
1037 if ($changegroup == 0) {
1038 // do not allow changing to all groups without accessallgroups capability
1039 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1040 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
1043 } else {
1044 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1045 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
1050 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
1054 * Returns group active in activity, changes the group by default if 'group' page param present
1056 * @category group
1057 * @param stdClass|cm_info $cm course module object
1058 * @param bool $update change active group if group param submitted
1059 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
1060 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
1062 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
1063 global $USER, $SESSION;
1065 if (!$groupmode = groups_get_activity_groupmode($cm)) {
1066 // NOGROUPS used
1067 return false;
1070 $context = context_module::instance($cm->id);
1071 if (has_capability('moodle/site:accessallgroups', $context)) {
1072 $groupmode = 'aag';
1075 if (!is_array($allowedgroups)) {
1076 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1077 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true);
1078 } else {
1079 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
1083 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
1085 // set new active group if requested
1086 $changegroup = optional_param('group', -1, PARAM_INT);
1087 if ($update and $changegroup != -1) {
1089 if ($changegroup == 0) {
1090 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
1091 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1092 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
1095 } else {
1096 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1097 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
1102 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
1106 * Gets a list of groups that the user is allowed to access within the
1107 * specified activity.
1109 * @category group
1110 * @param stdClass|cm_info $cm Course-module
1111 * @param int $userid User ID (defaults to current user)
1112 * @return array An array of group objects, or false if none
1114 function groups_get_activity_allowed_groups($cm,$userid=0) {
1115 // Use current user by default
1116 global $USER;
1117 if(!$userid) {
1118 $userid=$USER->id;
1121 // Get groupmode for activity, taking into account course settings
1122 $groupmode=groups_get_activity_groupmode($cm);
1124 // If visible groups mode, or user has the accessallgroups capability,
1125 // then they can access all groups for the activity...
1126 $context = context_module::instance($cm->id);
1127 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
1128 return groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true);
1129 } else {
1130 // ...otherwise they can only access groups they belong to
1131 return groups_get_all_groups($cm->course, $userid, $cm->groupingid, 'g.*', false, true);
1136 * Determine if a given group is visible to user or not in a given context.
1138 * @since Moodle 2.6
1139 * @param int $groupid Group id to test. 0 for all groups.
1140 * @param stdClass $course Course object.
1141 * @param stdClass $cm Course module object.
1142 * @param int $userid user id to test against. Defaults to $USER.
1143 * @return boolean true if visible, false otherwise
1145 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
1146 global $USER;
1148 if (empty($userid)) {
1149 $userid = $USER->id;
1152 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1153 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1154 // Groups are not used, or everything is visible, no need to go any further.
1155 return true;
1158 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1159 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
1160 // User can see everything. Groupid = 0 is handled here as well.
1161 return true;
1162 } else if ($groupid != 0) {
1163 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
1164 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
1165 if (array_key_exists($groupid, $groups)) {
1166 // User can see the group.
1167 return true;
1170 return false;
1174 * Get sql and parameters that will return user ids for a group or groups
1176 * @param int|array $groupids Where this is an array of multiple groups, it will match on members of any of the groups
1177 * @param context $context Course context or a context within a course. Mandatory when $groupid = USERSWITHOUTGROUP
1178 * @param int $groupsjointype Join type logic used. Defaults to 'Any' (logical OR).
1179 * @return array($sql, $params)
1180 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1182 function groups_get_members_ids_sql($groupids, context $context = null, $groupsjointype = GROUPS_JOIN_ANY) {
1183 if (!is_array($groupids)) {
1184 $groupids = [$groupids];
1187 $groupjoin = groups_get_members_join($groupids, 'u.id', $context, $groupsjointype);
1189 $sql = "SELECT DISTINCT u.id
1190 FROM {user} u
1191 $groupjoin->joins
1192 WHERE u.deleted = 0";
1193 if (!empty($groupjoin->wheres)) {
1194 $sql .= ' AND '. $groupjoin->wheres;
1197 return array($sql, $groupjoin->params);
1201 * Returns array with SQL and parameters returning userids and concatenated group names for given course
1203 * This function uses 'gn[0-9]+_' prefix for table names and parameters
1205 * @param int $courseid
1206 * @param string $separator
1207 * @return array [$sql, $params]
1209 function groups_get_names_concat_sql(int $courseid, string $separator = ', '): array {
1210 global $DB;
1212 // Use unique prefix just in case somebody makes some SQL magic with the result.
1213 static $i = 0;
1214 $i++;
1215 $prefix = "gn{$i}_";
1217 $groupalias = $prefix . 'g';
1218 $groupmemberalias = $prefix . 'gm';
1219 $groupcourseparam = $prefix . 'courseid';
1221 $sqlgroupconcat = $DB->sql_group_concat("{$groupalias}.name", $separator, "{$groupalias}.name");
1223 $sql = "SELECT {$groupmemberalias}.userid, {$sqlgroupconcat} AS groupnames
1224 FROM {groups} {$groupalias}
1225 JOIN {groups_members} {$groupmemberalias} ON {$groupmemberalias}.groupid = {$groupalias}.id
1226 WHERE {$groupalias}.courseid = :{$groupcourseparam}
1227 GROUP BY {$groupmemberalias}.userid";
1229 return [$sql, [$groupcourseparam => $courseid]];
1233 * Get sql join to return users in a group
1235 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1236 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1237 * @param context $context Course context or a context within a course. Mandatory when $groupids includes USERSWITHOUTGROUP
1238 * @param int $jointype Join type logic used. Defaults to 'Any' (logical OR).
1239 * @return \core\dml\sql_join Contains joins, wheres, params
1240 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1242 function groups_get_members_join($groupids, $useridcolumn, context $context = null, int $jointype = GROUPS_JOIN_ANY) {
1243 global $DB;
1245 // Use unique prefix just in case somebody makes some SQL magic with the result.
1246 static $i = 0;
1247 $i++;
1248 $prefix = 'gm' . $i . '_';
1250 if (!is_array($groupids)) {
1251 $groupids = $groupids ? [$groupids] : [];
1254 $join = '';
1255 $where = '';
1256 $param = [];
1258 $coursecontext = (!empty($context)) ? $context->get_course_context() : null;
1259 if (in_array(USERSWITHOUTGROUP, $groupids) && empty($coursecontext)) {
1260 // Throw an exception if $context is empty or invalid because it's needed to get the users without any group.
1261 throw new coding_exception('Missing or wrong $context parameter in an attempt to get members without any group');
1264 // Handle cases where we need to include/exclude users not in any groups.
1265 if (($nogroupskey = array_search(USERSWITHOUTGROUP, $groupids)) !== false) {
1266 // Get members without any group.
1267 $join .= "LEFT JOIN (
1268 SELECT g.courseid, m.groupid, m.userid
1269 FROM {groups_members} m
1270 JOIN {groups} g ON g.id = m.groupid
1271 ) {$prefix}gm ON ({$prefix}gm.userid = {$useridcolumn} AND {$prefix}gm.courseid = :{$prefix}gcourseid)";
1273 // Join type 'None' when filtering by 'no groups' means match users in at least one group.
1274 if ($jointype == GROUPS_JOIN_NONE) {
1275 $where = "{$prefix}gm.userid IS NOT NULL";
1276 } else {
1277 // All other cases need to match users not in any group.
1278 $where = "{$prefix}gm.userid IS NULL";
1281 $param = ["{$prefix}gcourseid" => $coursecontext->instanceid];
1282 unset($groupids[$nogroupskey]);
1285 // Handle any specified groups that need to be included.
1286 if (!empty($groupids)) {
1287 switch ($jointype) {
1288 case GROUPS_JOIN_ALL:
1289 // Handle matching all of the provided groups (logical AND).
1290 $joinallwheres = [];
1291 $aliaskey = 0;
1292 foreach ($groupids as $groupid) {
1293 $gmalias = "{$prefix}gm{$aliaskey}";
1294 $aliaskey++;
1295 $join .= "LEFT JOIN {groups_members} {$gmalias}
1296 ON ({$gmalias}.userid = {$useridcolumn} AND {$gmalias}.groupid = :{$gmalias}param)";
1297 $joinallwheres[] = "{$gmalias}.userid IS NOT NULL";
1298 $param["{$gmalias}param"] = $groupid;
1301 // Members of all of the specified groups only.
1302 if (empty($where)) {
1303 $where = '(' . implode(' AND ', $joinallwheres) . ')';
1304 } else {
1305 // Members of the specified groups and also no groups.
1306 // NOTE: This will always return no results, because you cannot be in specified groups and also be in no groups.
1307 $where = '(' . $where . ' AND ' . implode(' AND ', $joinallwheres) . ')';
1310 break;
1312 case GROUPS_JOIN_ANY:
1313 // Handle matching any of the provided groups (logical OR).
1314 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1316 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1317 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1318 $param = array_merge($param, $groupsparams);
1320 // Members of any of the specified groups only.
1321 if (empty($where)) {
1322 $where = "{$prefix}gm2.userid IS NOT NULL";
1323 } else {
1324 // Members of any of the specified groups or no groups.
1325 $where = "({$where} OR {$prefix}gm2.userid IS NOT NULL)";
1328 break;
1330 case GROUPS_JOIN_NONE:
1331 // Handle matching none of the provided groups (logical NOT).
1332 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1334 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1335 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1336 $param = array_merge($param, $groupsparams);
1338 // Members of none of the specified groups only.
1339 if (empty($where)) {
1340 $where = "{$prefix}gm2.userid IS NULL";
1341 } else {
1342 // Members of any unspecified groups (not a member of the specified groups, and not a member of no groups).
1343 $where = "({$where} AND {$prefix}gm2.userid IS NULL)";
1346 break;
1350 return new \core\dml\sql_join($join, $where, $param);
1354 * Internal method, sets up $SESSION->activegroup and verifies previous value
1356 * @param int $courseid
1357 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1358 * @param int $groupingid 0 means all groups
1359 * @param array $allowedgroups list of groups user can see
1361 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1362 global $SESSION, $USER;
1364 // init activegroup array if necessary
1365 if (!isset($SESSION->activegroup)) {
1366 $SESSION->activegroup = array();
1368 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1369 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1372 // make sure that the current group info is ok
1373 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1374 // active group does not exist anymore or is 0
1375 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1376 // do not do this if all groups selected and groupmode is not separate
1377 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1381 // set up defaults if necessary
1382 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1383 if ($groupmode == 'aag') {
1384 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1386 } else if ($allowedgroups) {
1387 if ($groupmode != SEPARATEGROUPS
1388 && $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid, 'g.*', false, true)) {
1389 $firstgroup = reset($mygroups);
1390 } else {
1391 $firstgroup = reset($allowedgroups);
1393 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1395 } else {
1396 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1397 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1398 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1404 * Caches group data for a particular course to speed up subsequent requests.
1406 * @param int $courseid The course id to cache data for.
1407 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1408 * @return stdClass A data object containing groups, groupings, and mappings.
1410 function groups_cache_groupdata($courseid, cache $cache = null) {
1411 global $DB;
1413 if ($cache === null) {
1414 // Initialise a cache if we wern't given one.
1415 $cache = cache::make('core', 'groupdata');
1418 // Get the groups that belong to the course.
1419 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1420 // Get the groupings that belong to the course.
1421 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1423 if (!is_array($groups)) {
1424 $groups = array();
1427 if (!is_array($groupings)) {
1428 $groupings = array();
1431 if (!empty($groupings)) {
1432 // Finally get the mappings between the two.
1433 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1434 $mappings = $DB->get_records_sql("
1435 SELECT gg.id, gg.groupingid, gg.groupid
1436 FROM {groupings_groups} gg
1437 JOIN {groups} g ON g.id = gg.groupid
1438 WHERE gg.groupingid $insql
1439 ORDER BY g.name ASC", $params);
1440 } else {
1441 $mappings = array();
1444 // Prepare the data array.
1445 $data = new stdClass;
1446 $data->groups = $groups;
1447 $data->groupings = $groupings;
1448 $data->mappings = $mappings;
1449 // Cache the data.
1450 $cache->set($courseid, $data);
1451 // Finally return it so it can be used if desired.
1452 return $data;
1456 * Gets group data for a course.
1458 * This returns an object with the following properties:
1459 * - groups : An array of all the groups in the course.
1460 * - groupings : An array of all the groupings within the course.
1461 * - mappings : An array of group to grouping mappings.
1463 * @param int $courseid The course id to get data for.
1464 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1465 * @return stdClass
1467 function groups_get_course_data($courseid, cache $cache = null) {
1468 if ($cache === null) {
1469 // Initialise a cache if we wern't given one.
1470 $cache = cache::make('core', 'groupdata');
1472 // Try to retrieve it from the cache.
1473 $data = $cache->get($courseid);
1474 if ($data === false) {
1475 $data = groups_cache_groupdata($courseid, $cache);
1477 return $data;
1481 * Determine if the current user can see at least one of the groups of the specified user.
1483 * @param stdClass $course Course object.
1484 * @param int $userid user id to check against.
1485 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1486 * @return boolean true if visible, false otherwise
1487 * @since Moodle 2.9
1489 function groups_user_groups_visible($course, $userid, $cm = null) {
1490 global $USER;
1492 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1493 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1494 // Groups are not used, or everything is visible, no need to go any further.
1495 return true;
1498 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1499 if (has_capability('moodle/site:accessallgroups', $context)) {
1500 // User can see everything.
1501 return true;
1502 } else {
1503 // Group mode is separate, and user doesn't have access all groups capability.
1504 if (empty($cm)) {
1505 $usergroups = groups_get_all_groups($course->id, $userid);
1506 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1507 } else {
1508 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1509 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1512 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1513 if (!empty($samegroups)) {
1514 // We share groups!
1515 return true;
1518 return false;
1522 * Returns the users in the specified groups.
1524 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1526 * @param array $groupsids The list of groups ids to check
1527 * @param array $extrafields extra fields to be included in result
1528 * @param int $sort optional sorting of returned users
1529 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1530 * @since Moodle 3.3
1532 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1533 global $DB;
1535 $userfieldsapi = \core_user\fields::for_userpic()->including(...($extrafields ?? []));
1536 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1537 list($insql, $params) = $DB->get_in_or_equal($groupsids, SQL_PARAMS_NAMED);
1539 $courseids = $DB->get_fieldset_sql("SELECT DISTINCT courseid FROM {groups} WHERE id $insql", $params);
1541 if (count($courseids) > 1) {
1542 // Groups from multiple courses. Have to check permission in system context.
1543 $context = context_system::instance();
1544 } else {
1545 $courseid = reset($courseids);
1546 $context = context_course::instance($courseid);
1549 $visibilitywhere = '';
1550 if (!has_capability('moodle/course:viewhiddengroups', $context)) {
1551 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_member_visibility_where();
1552 $params = array_merge($params, $visibilityparams);
1555 return $DB->get_records_sql("SELECT $userfields
1556 FROM {user} u
1557 JOIN {groups_members} gm ON u.id = gm.userid
1558 JOIN {groups} g ON g.id = gm.groupid
1559 WHERE gm.groupid $insql $visibilitywhere
1560 GROUP BY $userfields
1561 ORDER BY $sort", $params);
1565 * Returns users who share group membership with the specified user in the given actiivty.
1567 * @param stdClass|cm_info $cm course module
1568 * @param int $userid user id (empty for current user)
1569 * @return array a list of user
1570 * @since Moodle 3.3
1572 function groups_get_activity_shared_group_members($cm, $userid = null) {
1573 global $USER;
1575 if (empty($userid)) {
1576 $userid = $USER->id;
1579 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1580 // No groups no users.
1581 if (empty($groupsids)) {
1582 return [];
1584 return groups_get_groups_members($groupsids);