MDL-67271 core: Add test to find missing SVG icons
[moodle.git] / lib / grouplib.php
blob181b508fb4368e0ab44a7ba84b51ef6ad3da866f
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|bool Returns an array of the users for the specified
650 * group or false if no users or an error returned.
652 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
653 global $DB, $USER;
655 if (empty($groupid)) {
656 return [];
659 $courseid = $DB->get_field('groups', 'courseid', ['id' => $groupid]);
661 $select = "SELECT $fields";
662 $from = "FROM {user} u
663 JOIN {groups_members} gm ON gm.userid = u.id";
664 $where = "WHERE gm.groupid = :groupid";
665 $order = "ORDER BY $sort";
667 $params = ['groupid' => $groupid];
669 if (!\core_group\visibility::can_view_all_groups($courseid)) {
670 $from .= " JOIN {groups} g ON g.id = gm.groupid";
671 // Can view memberships of visibility is ALL, visibility is MEMBERS and current user is a member,
672 // or visibility is OWN and this is their membership.
673 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_member_visibility_where();
674 $params = array_merge($params, $visibilityparams);
675 $where .= $visibilitywhere;
678 $sql = implode(PHP_EOL, [$select, $from, $where, $order]);
680 return $DB->get_records_sql($sql, $params);
685 * Returns the users in the specified grouping.
687 * @category group
688 * @param int $groupingid The groupingid to get the users for
689 * @param string $fields The fields to return
690 * @param string $sort optional sorting of returned users
691 * @return array|bool Returns an array of the users for the specified
692 * group or false if no users or an error returned.
694 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
695 global $DB;
697 return $DB->get_records_sql("SELECT $fields
698 FROM {user} u
699 INNER JOIN {groups_members} gm ON u.id = gm.userid
700 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
701 WHERE gg.groupingid = ?
702 ORDER BY $sort", array($groupingid));
706 * Returns effective groupmode used in course
708 * @category group
709 * @param stdClass $course course object.
710 * @return int group mode
712 function groups_get_course_groupmode($course) {
713 return $course->groupmode;
717 * Returns effective groupmode used in activity, course setting
718 * overrides activity setting if groupmodeforce enabled.
720 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
722 * @category group
723 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
724 * @param stdClass $course object optional course object to improve perf
725 * @return int group mode
727 function groups_get_activity_groupmode($cm, $course=null) {
728 if ($cm instanceof cm_info) {
729 return $cm->effectivegroupmode;
731 if (isset($course->id) and $course->id == $cm->course) {
732 //ok
733 } else {
734 // Get course object (reuse $COURSE if possible).
735 $course = get_course($cm->course, false);
738 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
742 * Print group menu selector for course level.
744 * @category group
745 * @param stdClass $course course object
746 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
747 * @param bool $return return as string instead of printing
748 * @return mixed void or string depending on $return param
750 function groups_print_course_menu($course, $urlroot, $return=false) {
751 global $USER, $OUTPUT;
753 if (!$groupmode = $course->groupmode) {
754 if ($return) {
755 return '';
756 } else {
757 return;
761 $context = context_course::instance($course->id);
762 $aag = has_capability('moodle/site:accessallgroups', $context);
764 $usergroups = array();
765 if ($groupmode == VISIBLEGROUPS or $aag) {
766 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
767 // Get user's own groups and put to the top.
768 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
769 } else {
770 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
773 $activegroup = groups_get_course_group($course, true, $allowedgroups);
775 $groupsmenu = array();
776 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
777 $groupsmenu[0] = get_string('allparticipants');
780 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
782 if ($groupmode == VISIBLEGROUPS) {
783 $grouplabel = get_string('groupsvisible');
784 } else {
785 $grouplabel = get_string('groupsseparate');
788 if ($aag and $course->defaultgroupingid) {
789 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
790 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
794 if (count($groupsmenu) == 1) {
795 $groupname = reset($groupsmenu);
796 $output = $grouplabel.': '.$groupname;
797 } else {
798 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
799 $select->label = $grouplabel;
800 $output = $OUTPUT->render($select);
803 $output = '<div class="groupselector">'.$output.'</div>';
805 if ($return) {
806 return $output;
807 } else {
808 echo $output;
813 * Turn an array of groups into an array of menu options.
814 * @param array $groups of group objects.
815 * @return array groupid => formatted group name.
817 function groups_list_to_menu($groups) {
818 $groupsmenu = array();
819 foreach ($groups as $group) {
820 $groupsmenu[$group->id] = format_string($group->name);
822 return $groupsmenu;
826 * Takes user's allowed groups and own groups and formats for use in group selector menu
827 * If user has allowed groups + own groups will add to an optgroup
828 * Own groups are removed from allowed groups
829 * @param array $allowedgroups All groups user is allowed to see
830 * @param array $usergroups Groups user belongs to
831 * @return array
833 function groups_sort_menu_options($allowedgroups, $usergroups) {
834 $useroptions = array();
835 if ($usergroups) {
836 $useroptions = groups_list_to_menu($usergroups);
838 // Remove user groups from other groups list.
839 foreach ($usergroups as $group) {
840 unset($allowedgroups[$group->id]);
844 $allowedoptions = array();
845 if ($allowedgroups) {
846 $allowedoptions = groups_list_to_menu($allowedgroups);
849 if ($useroptions && $allowedoptions) {
850 return array(
851 1 => array(get_string('mygroups', 'group') => $useroptions),
852 2 => array(get_string('othergroups', 'group') => $allowedoptions)
854 } else if ($useroptions) {
855 return $useroptions;
856 } else {
857 return $allowedoptions;
862 * Generates html to print menu selector for course level, listing all groups.
863 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
865 * @param stdclass $course course object.
866 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
867 * @param bool $update set this to true to update current active group based on the group param.
868 * @param int $activegroup Change group active to this group if $update set to true.
870 * @return string html or void
872 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
873 global $SESSION, $OUTPUT, $USER;
875 $groupmode = groups_get_course_groupmode($course);
876 $context = context_course::instance($course->id);
877 $groupsmenu = array();
879 if (has_capability('moodle/site:accessallgroups', $context)) {
880 $groupsmenu[0] = get_string('allparticipants');
881 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
882 } else {
883 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
886 $groupsmenu += groups_list_to_menu($allowedgroups);
888 if ($update) {
889 // Init activegroup array if necessary.
890 if (!isset($SESSION->activegroup)) {
891 $SESSION->activegroup = array();
893 if (!isset($SESSION->activegroup[$course->id])) {
894 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
896 if (empty($groupsmenu[$activegroup])) {
897 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
899 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
902 $grouplabel = get_string('groups');
903 if (count($groupsmenu) == 0) {
904 return '';
905 } else if (count($groupsmenu) == 1) {
906 $groupname = reset($groupsmenu);
907 $output = $grouplabel.': '.$groupname;
908 } else {
909 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
910 $select->label = $grouplabel;
911 $output = $OUTPUT->render($select);
914 return $output;
919 * Print group menu selector for activity.
921 * @category group
922 * @param stdClass|cm_info $cm course module object
923 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
924 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
925 * @param bool $return return as string instead of printing
926 * @param bool $hideallparticipants If true, this prevents the 'All participants'
927 * option from appearing in cases where it normally would. This is intended for
928 * use only by activities that cannot display all groups together. (Note that
929 * selecting this option does not prevent groups_get_activity_group from
930 * returning 0; it will still do that if the user has chosen 'all participants'
931 * in another activity, or not chosen anything.)
932 * @return mixed void or string depending on $return param
934 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
935 global $USER, $OUTPUT;
937 if ($urlroot instanceof moodle_url) {
938 // no changes necessary
940 } else {
941 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
942 // Display error if urlroot is not absolute (this causes the non-JS version to break)
943 debugging('groups_print_activity_menu requires absolute URL for ' .
944 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
945 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
946 DEBUG_DEVELOPER);
948 $urlroot = new moodle_url($urlroot);
951 if (!$groupmode = groups_get_activity_groupmode($cm)) {
952 if ($return) {
953 return '';
954 } else {
955 return;
959 $context = context_module::instance($cm->id);
960 $aag = has_capability('moodle/site:accessallgroups', $context);
962 $usergroups = array();
963 if ($groupmode == VISIBLEGROUPS or $aag) {
964 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true); // Any group in grouping.
965 // Get user's own groups and put to the top.
966 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
967 } else {
968 // Only assigned groups.
969 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
972 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
974 $groupsmenu = array();
975 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
976 $groupsmenu[0] = get_string('allparticipants');
979 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
981 if ($groupmode == VISIBLEGROUPS) {
982 $grouplabel = get_string('groupsvisible');
983 } else {
984 $grouplabel = get_string('groupsseparate');
987 if ($aag and $cm->groupingid) {
988 if ($grouping = groups_get_grouping($cm->groupingid)) {
989 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
993 if (count($groupsmenu) == 1) {
994 $groupname = reset($groupsmenu);
995 $output = $grouplabel.': '.$groupname;
996 } else {
997 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
998 $select->label = $grouplabel;
999 $output = $OUTPUT->render($select);
1002 $output = '<div class="groupselector">'.$output.'</div>';
1004 if ($return) {
1005 return $output;
1006 } else {
1007 echo $output;
1012 * Returns group active in course, changes the group by default if 'group' page param present
1014 * @category group
1015 * @param stdClass $course course bject
1016 * @param bool $update change active group if group param submitted
1017 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
1018 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
1020 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
1021 global $USER, $SESSION;
1023 if (!$groupmode = $course->groupmode) {
1024 // NOGROUPS used
1025 return false;
1028 $context = context_course::instance($course->id);
1029 if (has_capability('moodle/site:accessallgroups', $context)) {
1030 $groupmode = 'aag';
1033 if (!is_array($allowedgroups)) {
1034 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1035 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
1036 } else {
1037 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
1041 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
1043 // set new active group if requested
1044 $changegroup = optional_param('group', -1, PARAM_INT);
1045 if ($update and $changegroup != -1) {
1047 if ($changegroup == 0) {
1048 // do not allow changing to all groups without accessallgroups capability
1049 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1050 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
1053 } else {
1054 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1055 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
1060 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
1064 * Returns group active in activity, changes the group by default if 'group' page param present
1066 * @category group
1067 * @param stdClass|cm_info $cm course module object
1068 * @param bool $update change active group if group param submitted
1069 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
1070 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
1072 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
1073 global $USER, $SESSION;
1075 if (!$groupmode = groups_get_activity_groupmode($cm)) {
1076 // NOGROUPS used
1077 return false;
1080 $context = context_module::instance($cm->id);
1081 if (has_capability('moodle/site:accessallgroups', $context)) {
1082 $groupmode = 'aag';
1085 if (!is_array($allowedgroups)) {
1086 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1087 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true);
1088 } else {
1089 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.*', false, true);
1093 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
1095 // set new active group if requested
1096 $changegroup = optional_param('group', -1, PARAM_INT);
1097 if ($update and $changegroup != -1) {
1099 if ($changegroup == 0) {
1100 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
1101 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1102 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
1105 } else {
1106 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1107 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
1112 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
1116 * Gets a list of groups that the user is allowed to access within the
1117 * specified activity.
1119 * @category group
1120 * @param stdClass|cm_info $cm Course-module
1121 * @param int $userid User ID (defaults to current user)
1122 * @return array An array of group objects, or false if none
1124 function groups_get_activity_allowed_groups($cm,$userid=0) {
1125 // Use current user by default
1126 global $USER;
1127 if(!$userid) {
1128 $userid=$USER->id;
1131 // Get groupmode for activity, taking into account course settings
1132 $groupmode=groups_get_activity_groupmode($cm);
1134 // If visible groups mode, or user has the accessallgroups capability,
1135 // then they can access all groups for the activity...
1136 $context = context_module::instance($cm->id);
1137 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
1138 return groups_get_all_groups($cm->course, 0, $cm->groupingid, 'g.*', false, true);
1139 } else {
1140 // ...otherwise they can only access groups they belong to
1141 return groups_get_all_groups($cm->course, $userid, $cm->groupingid, 'g.*', false, true);
1146 * Determine if a given group is visible to user or not in a given context.
1148 * @since Moodle 2.6
1149 * @param int $groupid Group id to test. 0 for all groups.
1150 * @param stdClass $course Course object.
1151 * @param stdClass $cm Course module object.
1152 * @param int $userid user id to test against. Defaults to $USER.
1153 * @return boolean true if visible, false otherwise
1155 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
1156 global $USER;
1158 if (empty($userid)) {
1159 $userid = $USER->id;
1162 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1163 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1164 // Groups are not used, or everything is visible, no need to go any further.
1165 return true;
1168 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1169 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
1170 // User can see everything. Groupid = 0 is handled here as well.
1171 return true;
1172 } else if ($groupid != 0) {
1173 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
1174 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
1175 if (array_key_exists($groupid, $groups)) {
1176 // User can see the group.
1177 return true;
1180 return false;
1184 * Get sql and parameters that will return user ids for a group or groups
1186 * @param int|array $groupids Where this is an array of multiple groups, it will match on members of any of the groups
1187 * @param context $context Course context or a context within a course. Mandatory when $groupid = USERSWITHOUTGROUP
1188 * @param int $groupsjointype Join type logic used. Defaults to 'Any' (logical OR).
1189 * @return array($sql, $params)
1190 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1192 function groups_get_members_ids_sql($groupids, context $context = null, $groupsjointype = GROUPS_JOIN_ANY) {
1193 if (!is_array($groupids)) {
1194 $groupids = [$groupids];
1197 $groupjoin = groups_get_members_join($groupids, 'u.id', $context, $groupsjointype);
1199 $sql = "SELECT DISTINCT u.id
1200 FROM {user} u
1201 $groupjoin->joins
1202 WHERE u.deleted = 0";
1203 if (!empty($groupjoin->wheres)) {
1204 $sql .= ' AND '. $groupjoin->wheres;
1207 return array($sql, $groupjoin->params);
1211 * Returns array with SQL and parameters returning userids and concatenated group names for given course
1213 * This function uses 'gn[0-9]+_' prefix for table names and parameters
1215 * @param int $courseid
1216 * @param string $separator
1217 * @return array [$sql, $params]
1219 function groups_get_names_concat_sql(int $courseid, string $separator = ', '): array {
1220 global $DB;
1222 // Use unique prefix just in case somebody makes some SQL magic with the result.
1223 static $i = 0;
1224 $i++;
1225 $prefix = "gn{$i}_";
1227 $groupalias = $prefix . 'g';
1228 $groupmemberalias = $prefix . 'gm';
1229 $groupcourseparam = $prefix . 'courseid';
1231 $sqlgroupconcat = $DB->sql_group_concat("{$groupalias}.name", $separator, "{$groupalias}.name");
1233 $sql = "SELECT {$groupmemberalias}.userid, {$sqlgroupconcat} AS groupnames
1234 FROM {groups} {$groupalias}
1235 JOIN {groups_members} {$groupmemberalias} ON {$groupmemberalias}.groupid = {$groupalias}.id
1236 WHERE {$groupalias}.courseid = :{$groupcourseparam}
1237 GROUP BY {$groupmemberalias}.userid";
1239 return [$sql, [$groupcourseparam => $courseid]];
1243 * Get sql join to return users in a group
1245 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1246 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1247 * @param context $context Course context or a context within a course. Mandatory when $groupids includes USERSWITHOUTGROUP
1248 * @param int $jointype Join type logic used. Defaults to 'Any' (logical OR).
1249 * @return \core\dml\sql_join Contains joins, wheres, params
1250 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1252 function groups_get_members_join($groupids, $useridcolumn, context $context = null, int $jointype = GROUPS_JOIN_ANY) {
1253 global $DB;
1255 // Use unique prefix just in case somebody makes some SQL magic with the result.
1256 static $i = 0;
1257 $i++;
1258 $prefix = 'gm' . $i . '_';
1260 if (!is_array($groupids)) {
1261 $groupids = $groupids ? [$groupids] : [];
1264 $join = '';
1265 $where = '';
1266 $param = [];
1268 $coursecontext = (!empty($context)) ? $context->get_course_context() : null;
1269 if (in_array(USERSWITHOUTGROUP, $groupids) && empty($coursecontext)) {
1270 // Throw an exception if $context is empty or invalid because it's needed to get the users without any group.
1271 throw new coding_exception('Missing or wrong $context parameter in an attempt to get members without any group');
1274 // Handle cases where we need to include/exclude users not in any groups.
1275 if (($nogroupskey = array_search(USERSWITHOUTGROUP, $groupids)) !== false) {
1276 // Get members without any group.
1277 $join .= "LEFT JOIN (
1278 SELECT g.courseid, m.groupid, m.userid
1279 FROM {groups_members} m
1280 JOIN {groups} g ON g.id = m.groupid
1281 ) {$prefix}gm ON ({$prefix}gm.userid = {$useridcolumn} AND {$prefix}gm.courseid = :{$prefix}gcourseid)";
1283 // Join type 'None' when filtering by 'no groups' means match users in at least one group.
1284 if ($jointype == GROUPS_JOIN_NONE) {
1285 $where = "{$prefix}gm.userid IS NOT NULL";
1286 } else {
1287 // All other cases need to match users not in any group.
1288 $where = "{$prefix}gm.userid IS NULL";
1291 $param = ["{$prefix}gcourseid" => $coursecontext->instanceid];
1292 unset($groupids[$nogroupskey]);
1295 // Handle any specified groups that need to be included.
1296 if (!empty($groupids)) {
1297 switch ($jointype) {
1298 case GROUPS_JOIN_ALL:
1299 // Handle matching all of the provided groups (logical AND).
1300 $joinallwheres = [];
1301 $aliaskey = 0;
1302 foreach ($groupids as $groupid) {
1303 $gmalias = "{$prefix}gm{$aliaskey}";
1304 $aliaskey++;
1305 $join .= "LEFT JOIN {groups_members} {$gmalias}
1306 ON ({$gmalias}.userid = {$useridcolumn} AND {$gmalias}.groupid = :{$gmalias}param)";
1307 $joinallwheres[] = "{$gmalias}.userid IS NOT NULL";
1308 $param["{$gmalias}param"] = $groupid;
1311 // Members of all of the specified groups only.
1312 if (empty($where)) {
1313 $where = '(' . implode(' AND ', $joinallwheres) . ')';
1314 } else {
1315 // Members of the specified groups and also no groups.
1316 // NOTE: This will always return no results, because you cannot be in specified groups and also be in no groups.
1317 $where = '(' . $where . ' AND ' . implode(' AND ', $joinallwheres) . ')';
1320 break;
1322 case GROUPS_JOIN_ANY:
1323 // Handle matching any of the provided groups (logical OR).
1324 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1326 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1327 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1328 $param = array_merge($param, $groupsparams);
1330 // Members of any of the specified groups only.
1331 if (empty($where)) {
1332 $where = "{$prefix}gm2.userid IS NOT NULL";
1333 } else {
1334 // Members of any of the specified groups or no groups.
1335 $where = "({$where} OR {$prefix}gm2.userid IS NOT NULL)";
1338 break;
1340 case GROUPS_JOIN_NONE:
1341 // Handle matching none of the provided groups (logical NOT).
1342 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1344 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1345 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1346 $param = array_merge($param, $groupsparams);
1348 // Members of none of the specified groups only.
1349 if (empty($where)) {
1350 $where = "{$prefix}gm2.userid IS NULL";
1351 } else {
1352 // Members of any unspecified groups (not a member of the specified groups, and not a member of no groups).
1353 $where = "({$where} AND {$prefix}gm2.userid IS NULL)";
1356 break;
1360 return new \core\dml\sql_join($join, $where, $param);
1364 * Internal method, sets up $SESSION->activegroup and verifies previous value
1366 * @param int $courseid
1367 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1368 * @param int $groupingid 0 means all groups
1369 * @param array $allowedgroups list of groups user can see
1371 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1372 global $SESSION, $USER;
1374 // init activegroup array if necessary
1375 if (!isset($SESSION->activegroup)) {
1376 $SESSION->activegroup = array();
1378 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1379 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1382 // make sure that the current group info is ok
1383 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1384 // active group does not exist anymore or is 0
1385 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1386 // do not do this if all groups selected and groupmode is not separate
1387 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1391 // set up defaults if necessary
1392 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1393 if ($groupmode == 'aag') {
1394 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1396 } else if ($allowedgroups) {
1397 if ($groupmode != SEPARATEGROUPS
1398 && $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid, 'g.*', false, true)) {
1399 $firstgroup = reset($mygroups);
1400 } else {
1401 $firstgroup = reset($allowedgroups);
1403 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1405 } else {
1406 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1407 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1408 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1414 * Caches group data for a particular course to speed up subsequent requests.
1416 * @param int $courseid The course id to cache data for.
1417 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1418 * @return stdClass A data object containing groups, groupings, and mappings.
1420 function groups_cache_groupdata($courseid, cache $cache = null) {
1421 global $DB;
1423 if ($cache === null) {
1424 // Initialise a cache if we wern't given one.
1425 $cache = cache::make('core', 'groupdata');
1428 // Get the groups that belong to the course.
1429 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1430 // Get the groupings that belong to the course.
1431 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1433 if (!is_array($groups)) {
1434 $groups = array();
1437 if (!is_array($groupings)) {
1438 $groupings = array();
1441 if (!empty($groupings)) {
1442 // Finally get the mappings between the two.
1443 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1444 $mappings = $DB->get_records_sql("
1445 SELECT gg.id, gg.groupingid, gg.groupid
1446 FROM {groupings_groups} gg
1447 JOIN {groups} g ON g.id = gg.groupid
1448 WHERE gg.groupingid $insql
1449 ORDER BY g.name ASC", $params);
1450 } else {
1451 $mappings = array();
1454 // Prepare the data array.
1455 $data = new stdClass;
1456 $data->groups = $groups;
1457 $data->groupings = $groupings;
1458 $data->mappings = $mappings;
1459 // Cache the data.
1460 $cache->set($courseid, $data);
1461 // Finally return it so it can be used if desired.
1462 return $data;
1466 * Gets group data for a course.
1468 * This returns an object with the following properties:
1469 * - groups : An array of all the groups in the course.
1470 * - groupings : An array of all the groupings within the course.
1471 * - mappings : An array of group to grouping mappings.
1473 * @param int $courseid The course id to get data for.
1474 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1475 * @return stdClass
1477 function groups_get_course_data($courseid, cache $cache = null) {
1478 if ($cache === null) {
1479 // Initialise a cache if we wern't given one.
1480 $cache = cache::make('core', 'groupdata');
1482 // Try to retrieve it from the cache.
1483 $data = $cache->get($courseid);
1484 if ($data === false) {
1485 $data = groups_cache_groupdata($courseid, $cache);
1487 return $data;
1491 * Determine if the current user can see at least one of the groups of the specified user.
1493 * @param stdClass $course Course object.
1494 * @param int $userid user id to check against.
1495 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1496 * @return boolean true if visible, false otherwise
1497 * @since Moodle 2.9
1499 function groups_user_groups_visible($course, $userid, $cm = null) {
1500 global $USER;
1502 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1503 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1504 // Groups are not used, or everything is visible, no need to go any further.
1505 return true;
1508 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1509 if (has_capability('moodle/site:accessallgroups', $context)) {
1510 // User can see everything.
1511 return true;
1512 } else {
1513 // Group mode is separate, and user doesn't have access all groups capability.
1514 if (empty($cm)) {
1515 $usergroups = groups_get_all_groups($course->id, $userid);
1516 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1517 } else {
1518 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1519 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1522 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1523 if (!empty($samegroups)) {
1524 // We share groups!
1525 return true;
1528 return false;
1532 * Returns the users in the specified groups.
1534 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1536 * @param array $groupsids The list of groups ids to check
1537 * @param array $extrafields extra fields to be included in result
1538 * @param int $sort optional sorting of returned users
1539 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1540 * @since Moodle 3.3
1542 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1543 global $DB;
1545 $userfieldsapi = \core_user\fields::for_userpic()->including(...($extrafields ?? []));
1546 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1547 list($insql, $params) = $DB->get_in_or_equal($groupsids, SQL_PARAMS_NAMED);
1549 $courseids = $DB->get_fieldset_sql("SELECT DISTINCT courseid FROM {groups} WHERE id $insql", $params);
1551 if (count($courseids) > 1) {
1552 // Groups from multiple courses. Have to check permission in system context.
1553 $context = context_system::instance();
1554 } else {
1555 $courseid = reset($courseids);
1556 $context = context_course::instance($courseid);
1559 $visibilitywhere = '';
1560 if (!has_capability('moodle/course:viewhiddengroups', $context)) {
1561 list($visibilitywhere, $visibilityparams) = \core_group\visibility::sql_member_visibility_where();
1562 $params = array_merge($params, $visibilityparams);
1565 return $DB->get_records_sql("SELECT $userfields
1566 FROM {user} u
1567 JOIN {groups_members} gm ON u.id = gm.userid
1568 JOIN {groups} g ON g.id = gm.groupid
1569 WHERE gm.groupid $insql $visibilitywhere
1570 GROUP BY $userfields
1571 ORDER BY $sort", $params);
1575 * Returns users who share group membership with the specified user in the given actiivty.
1577 * @param stdClass|cm_info $cm course module
1578 * @param int $userid user id (empty for current user)
1579 * @return array a list of user
1580 * @since Moodle 3.3
1582 function groups_get_activity_shared_group_members($cm, $userid = null) {
1583 global $USER;
1585 if (empty($userid)) {
1586 $userid = $USER->id;
1589 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1590 // No groups no users.
1591 if (empty($groupsids)) {
1592 return [];
1594 return groups_get_groups_members($groupsids);