3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 defined('MOODLE_INTERNAL') ||
die();
27 * Groups not used in course or activity
29 define('NOGROUPS', 0);
32 * Groups used, users do not see other groups
34 define('SEPARATEGROUPS', 1);
37 * Groups used, students see other groups
39 define('VISIBLEGROUPS', 2);
42 * This is for filtering users without any group.
44 define('USERSWITHOUTGROUP', -1);
48 * Determines if a group with a given groupid exists.
51 * @param int $groupid The groupid to check for
52 * @return bool True if the group exists, false otherwise or if an error
55 function groups_group_exists($groupid) {
57 return $DB->record_exists('groups', array('id'=>$groupid));
61 * Gets the name of a group with a specified id
64 * @param int $groupid The id of the group
65 * @return string The name of the group
67 function groups_get_group_name($groupid) {
69 return $DB->get_field('groups', 'name', array('id'=>$groupid));
73 * Gets the name of a grouping with a specified id
76 * @param int $groupingid The id of the grouping
77 * @return string The name of the grouping
79 function groups_get_grouping_name($groupingid) {
81 return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
85 * Returns the groupid of a group with the name specified for the course.
86 * Group names should be unique in course
89 * @param int $courseid The id of the course
90 * @param string $name name of group (without magic quotes)
91 * @return int $groupid
93 function groups_get_group_by_name($courseid, $name) {
94 $data = groups_get_course_data($courseid);
95 foreach ($data->groups
as $group) {
96 if ($group->name
== $name) {
104 * Returns the groupid of a group with the idnumber specified for the course.
105 * Group idnumbers should be unique within course
108 * @param int $courseid The id of the course
109 * @param string $idnumber idnumber of group
110 * @return group object
112 function groups_get_group_by_idnumber($courseid, $idnumber) {
113 if (empty($idnumber)) {
116 $data = groups_get_course_data($courseid);
117 foreach ($data->groups
as $group) {
118 if ($group->idnumber
== $idnumber) {
126 * Returns the groupingid of a grouping with the name specified for the course.
127 * Grouping names should be unique in course
130 * @param int $courseid The id of the course
131 * @param string $name name of group (without magic quotes)
132 * @return int $groupid
134 function groups_get_grouping_by_name($courseid, $name) {
135 $data = groups_get_course_data($courseid);
136 foreach ($data->groupings
as $grouping) {
137 if ($grouping->name
== $name) {
138 return $grouping->id
;
145 * Returns the groupingid of a grouping with the idnumber specified for the course.
146 * Grouping names should be unique within course
149 * @param int $courseid The id of the course
150 * @param string $idnumber idnumber of the group
151 * @return grouping object
153 function groups_get_grouping_by_idnumber($courseid, $idnumber) {
154 if (empty($idnumber)) {
157 $data = groups_get_course_data($courseid);
158 foreach ($data->groupings
as $grouping) {
159 if ($grouping->idnumber
== $idnumber) {
167 * Get the group object
170 * @param int $groupid ID of the group.
171 * @param string $fields (default is all fields)
172 * @param int $strictness (IGNORE_MISSING - default)
173 * @return bool|stdClass group object or false if not found
174 * @throws dml_exception
176 function groups_get_group($groupid, $fields='*', $strictness=IGNORE_MISSING
) {
178 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
182 * Get the grouping object
185 * @param int $groupingid ID of the group.
186 * @param string $fields
187 * @param int $strictness (IGNORE_MISSING - default)
188 * @return stdClass group object
190 function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING
) {
192 return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
196 * Gets array of all groups in a specified course (subject to the conditions imposed by the other arguments).
199 * @param int $courseid The id of the course.
200 * @param int|int[] $userid optional user id or array of ids, returns only groups continaing one or more of those users.
201 * @param int $groupingid optional returns only groups in the specified grouping.
202 * @param string $fields defaults to g.*. This allows you to vary which fields are returned.
203 * If $groupingid is specified, the groupings_groups table will be available with alias gg.
204 * If $userid is specified, the groups_members table will be available as gm.
205 * @param bool $withmembers if true return an extra field members (int[]) which is the list of userids that
206 * are members of each group. For this to work, g.id (or g.*) must be included in $fields.
207 * In this case, the final results will always be an array indexed by group id.
208 * @return array returns an array of the group objects (unless you have done something very weird
209 * with the $fields option).
211 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false) {
214 // We need to check that we each field in the fields list belongs to the group table and that it has not being
215 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
217 if ($fields !== 'g.*') {
218 // Quickly check if the first field is no longer g.id as using the
219 // cache will return an array indexed differently than when expect
220 if (strpos($fields, 'g.*') !== 0 && strpos($fields, 'g.id') !== 0) {
221 $knownfields = false;
223 $fieldbits = explode(',', $fields);
224 foreach ($fieldbits as $bit) {
226 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
227 $knownfields = false;
234 if (empty($userid) && $knownfields && !$withmembers) {
235 // We can use the cache.
236 $data = groups_get_course_data($courseid);
237 if (empty($groupingid)) {
238 // All groups.. Easy!
239 $groups = $data->groups
;
242 foreach ($data->mappings
as $mapping) {
243 if ($mapping->groupingid
!= $groupingid) {
246 if (isset($data->groups
[$mapping->groupid
])) {
247 $groups[$mapping->groupid
] = $data->groups
[$mapping->groupid
];
251 // Yay! We could use the cache. One more query saved.
258 if (!empty($userid)) {
259 list($usql, $params) = $DB->get_in_or_equal($userid);
260 $userfrom = "JOIN {groups_members} gm ON gm.groupid = g.id";
261 $userwhere = "AND gm.userid $usql";
266 if (!empty($groupingid)) {
267 $groupingfrom = "JOIN {groupings_groups} gg ON gg.groupid = g.id";
268 $groupingwhere = "AND gg.groupingid = ?";
269 $params[] = $groupingid;
272 array_unshift($params, $courseid);
274 $results = $DB->get_records_sql("
282 ORDER BY g.name ASC", $params);
288 // We also want group members. We do this in a separate query, becuse the above
289 // query will return a lot of data (e.g. g.description) for each group, and
290 // some groups may contain hundreds of members. We don't want the results
291 // to contain hundreds of copies of long descriptions.
293 foreach ($results as $row) {
294 $groups[$row->id
] = $row;
295 $groups[$row->id
]->members
= [];
297 $groupmembers = $DB->get_records_list('groups_members', 'groupid', array_keys($groups));
298 foreach ($groupmembers as $gm) {
299 $groups[$gm->groupid
]->members
[$gm->userid
] = $gm->userid
;
305 * Gets array of all groups in current user.
309 * @return array Returns an array of the group objects.
311 function groups_get_my_groups() {
313 return $DB->get_records_sql("SELECT *
314 FROM {groups_members} gm
318 ORDER BY name ASC", array($USER->id
));
322 * Returns info about user's groups in course.
325 * @param int $courseid
326 * @param int $userid $USER if not specified
327 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
329 function groups_get_user_groups($courseid, $userid=0) {
332 if (empty($userid)) {
336 $cache = cache
::make('core', 'user_group_groupings');
338 // Try to retrieve group ids from the cache.
339 $usergroups = $cache->get($userid);
341 if ($usergroups === false) {
342 $sql = "SELECT g.id, g.courseid, gg.groupingid
344 JOIN {groups_members} gm ON gm.groupid = g.id
345 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
346 WHERE gm.userid = ?";
348 $rs = $DB->get_recordset_sql($sql, array($userid));
350 $usergroups = array();
351 $allgroups = array();
353 foreach ($rs as $group) {
354 if (!array_key_exists($group->courseid
, $allgroups)) {
355 $allgroups[$group->courseid
] = array();
357 $allgroups[$group->courseid
][$group->id
] = $group->id
;
358 if (!array_key_exists($group->courseid
, $usergroups)) {
359 $usergroups[$group->courseid
] = array();
361 if (is_null($group->groupingid
)) {
364 if (!array_key_exists($group->groupingid
, $usergroups[$group->courseid
])) {
365 $usergroups[$group->courseid
][$group->groupingid
] = array();
367 $usergroups[$group->courseid
][$group->groupingid
][$group->id
] = $group->id
;
371 foreach (array_keys($allgroups) as $cid) {
372 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
376 $cache->set($userid, $usergroups);
379 if (array_key_exists($courseid, $usergroups)) {
380 return $usergroups[$courseid];
382 return array('0' => array());
387 * Gets an array of all groupings in a specified course. This value is cached
388 * for a single course (so you can call it repeatedly for the same course
389 * without a performance penalty).
392 * @param int $courseid return all groupings from course with this courseid
393 * @return array Returns an array of the grouping objects (empty if none)
395 function groups_get_all_groupings($courseid) {
396 $data = groups_get_course_data($courseid);
397 return $data->groupings
;
401 * Determines if the user is a member of the given group.
403 * If $userid is null, use the global object.
406 * @param int $groupid The group to check for membership.
407 * @param int $userid The user to check against the group.
408 * @return bool True if the user is a member, false otherwise.
410 function groups_is_member($groupid, $userid=null) {
417 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
421 * Determines if current or specified is member of any active group in activity
424 * @staticvar array $cache
425 * @param stdClass|cm_info $cm course module object
426 * @param int $userid id of user, null means $USER->id
427 * @return bool true if user member of at least one group used in activity
429 function groups_has_membership($cm, $userid=null) {
430 global $CFG, $USER, $DB;
432 static $cache = array();
434 if (empty($userid)) {
438 $cachekey = $userid.'|'.$cm->course
.'|'.$cm->groupingid
;
439 if (isset($cache[$cachekey])) {
440 return($cache[$cachekey]);
443 if ($cm->groupingid
) {
444 // find out if member of any group in selected activity grouping
446 FROM {groups_members} gm, {groupings_groups} gg
447 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
448 $params = array($userid, $cm->groupingid
);
451 // no grouping used - check all groups in course
453 FROM {groups_members} gm, {groups} g
454 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
455 $params = array($userid, $cm->course
);
458 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
460 return $cache[$cachekey];
464 * Returns the users in the specified group.
467 * @param int $groupid The groupid to get the users for
468 * @param int $fields The fields to return
469 * @param int $sort optional sorting of returned users
470 * @return array|bool Returns an array of the users for the specified
471 * group or false if no users or an error returned.
473 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
476 return $DB->get_records_sql("SELECT $fields
477 FROM {user} u, {groups_members} gm
478 WHERE u.id = gm.userid AND gm.groupid = ?
479 ORDER BY $sort", array($groupid));
484 * Returns the users in the specified grouping.
487 * @param int $groupingid The groupingid to get the users for
488 * @param string $fields The fields to return
489 * @param string $sort optional sorting of returned users
490 * @return array|bool Returns an array of the users for the specified
491 * group or false if no users or an error returned.
493 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
496 return $DB->get_records_sql("SELECT $fields
498 INNER JOIN {groups_members} gm ON u.id = gm.userid
499 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
500 WHERE gg.groupingid = ?
501 ORDER BY $sort", array($groupingid));
505 * Returns effective groupmode used in course
508 * @param stdClass $course course object.
509 * @return int group mode
511 function groups_get_course_groupmode($course) {
512 return $course->groupmode
;
516 * Returns effective groupmode used in activity, course setting
517 * overrides activity setting if groupmodeforce enabled.
519 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
522 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
523 * @param stdClass $course object optional course object to improve perf
524 * @return int group mode
526 function groups_get_activity_groupmode($cm, $course=null) {
527 if ($cm instanceof cm_info
) {
528 return $cm->effectivegroupmode
;
530 if (isset($course->id
) and $course->id
== $cm->course
) {
533 // Get course object (reuse $COURSE if possible).
534 $course = get_course($cm->course
, false);
537 return empty($course->groupmodeforce
) ?
$cm->groupmode
: $course->groupmode
;
541 * Print group menu selector for course level.
544 * @param stdClass $course course object
545 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
546 * @param bool $return return as string instead of printing
547 * @return mixed void or string depending on $return param
549 function groups_print_course_menu($course, $urlroot, $return=false) {
550 global $USER, $OUTPUT;
552 if (!$groupmode = $course->groupmode
) {
560 $context = context_course
::instance($course->id
);
561 $aag = has_capability('moodle/site:accessallgroups', $context);
563 $usergroups = array();
564 if ($groupmode == VISIBLEGROUPS
or $aag) {
565 $allowedgroups = groups_get_all_groups($course->id
, 0, $course->defaultgroupingid
);
566 // Get user's own groups and put to the top.
567 $usergroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
569 $allowedgroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
572 $activegroup = groups_get_course_group($course, true, $allowedgroups);
574 $groupsmenu = array();
575 if (!$allowedgroups or $groupmode == VISIBLEGROUPS
or $aag) {
576 $groupsmenu[0] = get_string('allparticipants');
579 $groupsmenu +
= groups_sort_menu_options($allowedgroups, $usergroups);
581 if ($groupmode == VISIBLEGROUPS
) {
582 $grouplabel = get_string('groupsvisible');
584 $grouplabel = get_string('groupsseparate');
587 if ($aag and $course->defaultgroupingid
) {
588 if ($grouping = groups_get_grouping($course->defaultgroupingid
)) {
589 $grouplabel = $grouplabel . ' (' . format_string($grouping->name
) . ')';
593 if (count($groupsmenu) == 1) {
594 $groupname = reset($groupsmenu);
595 $output = $grouplabel.': '.$groupname;
597 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
598 $select->label
= $grouplabel;
599 $output = $OUTPUT->render($select);
602 $output = '<div class="groupselector">'.$output.'</div>';
612 * Turn an array of groups into an array of menu options.
613 * @param array $groups of group objects.
614 * @return array groupid => formatted group name.
616 function groups_list_to_menu($groups) {
617 $groupsmenu = array();
618 foreach ($groups as $group) {
619 $groupsmenu[$group->id
] = format_string($group->name
);
625 * Takes user's allowed groups and own groups and formats for use in group selector menu
626 * If user has allowed groups + own groups will add to an optgroup
627 * Own groups are removed from allowed groups
628 * @param array $allowedgroups All groups user is allowed to see
629 * @param array $usergroups Groups user belongs to
632 function groups_sort_menu_options($allowedgroups, $usergroups) {
633 $useroptions = array();
635 $useroptions = groups_list_to_menu($usergroups);
637 // Remove user groups from other groups list.
638 foreach ($usergroups as $group) {
639 unset($allowedgroups[$group->id
]);
643 $allowedoptions = array();
644 if ($allowedgroups) {
645 $allowedoptions = groups_list_to_menu($allowedgroups);
648 if ($useroptions && $allowedoptions) {
650 1 => array(get_string('mygroups', 'group') => $useroptions),
651 2 => array(get_string('othergroups', 'group') => $allowedoptions)
653 } else if ($useroptions) {
656 return $allowedoptions;
661 * Generates html to print menu selector for course level, listing all groups.
662 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
664 * @param stdclass $course course object.
665 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
666 * @param bool $update set this to true to update current active group based on the group param.
667 * @param int $activegroup Change group active to this group if $update set to true.
669 * @return string html or void
671 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
672 global $SESSION, $OUTPUT, $USER;
674 $groupmode = groups_get_course_groupmode($course);
675 $context = context_course
::instance($course->id
);
676 $groupsmenu = array();
678 if (has_capability('moodle/site:accessallgroups', $context)) {
679 $groupsmenu[0] = get_string('allparticipants');
680 $allowedgroups = groups_get_all_groups($course->id
, 0, $course->defaultgroupingid
);
682 $allowedgroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
685 $groupsmenu +
= groups_list_to_menu($allowedgroups);
688 // Init activegroup array if necessary.
689 if (!isset($SESSION->activegroup
)) {
690 $SESSION->activegroup
= array();
692 if (!isset($SESSION->activegroup
[$course->id
])) {
693 $SESSION->activegroup
[$course->id
] = array(SEPARATEGROUPS
=> array(), VISIBLEGROUPS
=> array(), 'aag' => array());
695 if (empty($groupsmenu[$activegroup])) {
696 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
698 $SESSION->activegroup
[$course->id
][$groupmode][$course->defaultgroupingid
] = $activegroup;
701 $grouplabel = get_string('groups');
702 if (count($groupsmenu) == 0) {
704 } else if (count($groupsmenu) == 1) {
705 $groupname = reset($groupsmenu);
706 $output = $grouplabel.': '.$groupname;
708 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
709 $select->label
= $grouplabel;
710 $output = $OUTPUT->render($select);
718 * Print group menu selector for activity.
721 * @param stdClass|cm_info $cm course module object
722 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
723 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
724 * @param bool $return return as string instead of printing
725 * @param bool $hideallparticipants If true, this prevents the 'All participants'
726 * option from appearing in cases where it normally would. This is intended for
727 * use only by activities that cannot display all groups together. (Note that
728 * selecting this option does not prevent groups_get_activity_group from
729 * returning 0; it will still do that if the user has chosen 'all participants'
730 * in another activity, or not chosen anything.)
731 * @return mixed void or string depending on $return param
733 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
734 global $USER, $OUTPUT;
736 if ($urlroot instanceof moodle_url
) {
737 // no changes necessary
740 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
741 // Display error if urlroot is not absolute (this causes the non-JS version to break)
742 debugging('groups_print_activity_menu requires absolute URL for ' .
743 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
744 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
747 $urlroot = new moodle_url($urlroot);
750 if (!$groupmode = groups_get_activity_groupmode($cm)) {
758 $context = context_module
::instance($cm->id
);
759 $aag = has_capability('moodle/site:accessallgroups', $context);
761 $usergroups = array();
762 if ($groupmode == VISIBLEGROUPS
or $aag) {
763 $allowedgroups = groups_get_all_groups($cm->course
, 0, $cm->groupingid
); // any group in grouping
764 // Get user's own groups and put to the top.
765 $usergroups = groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
);
767 $allowedgroups = groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
); // only assigned groups
770 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
772 $groupsmenu = array();
773 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS
or $aag) and !$hideallparticipants) {
774 $groupsmenu[0] = get_string('allparticipants');
777 $groupsmenu +
= groups_sort_menu_options($allowedgroups, $usergroups);
779 if ($groupmode == VISIBLEGROUPS
) {
780 $grouplabel = get_string('groupsvisible');
782 $grouplabel = get_string('groupsseparate');
785 if ($aag and $cm->groupingid
) {
786 if ($grouping = groups_get_grouping($cm->groupingid
)) {
787 $grouplabel = $grouplabel . ' (' . format_string($grouping->name
) . ')';
791 if (count($groupsmenu) == 1) {
792 $groupname = reset($groupsmenu);
793 $output = $grouplabel.': '.$groupname;
795 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
796 $select->label
= $grouplabel;
797 $output = $OUTPUT->render($select);
800 $output = '<div class="groupselector">'.$output.'</div>';
810 * Returns group active in course, changes the group by default if 'group' page param present
813 * @param stdClass $course course bject
814 * @param bool $update change active group if group param submitted
815 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
816 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
818 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
819 global $USER, $SESSION;
821 if (!$groupmode = $course->groupmode
) {
826 $context = context_course
::instance($course->id
);
827 if (has_capability('moodle/site:accessallgroups', $context)) {
831 if (!is_array($allowedgroups)) {
832 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
833 $allowedgroups = groups_get_all_groups($course->id
, 0, $course->defaultgroupingid
);
835 $allowedgroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
839 _group_verify_activegroup($course->id
, $groupmode, $course->defaultgroupingid
, $allowedgroups);
841 // set new active group if requested
842 $changegroup = optional_param('group', -1, PARAM_INT
);
843 if ($update and $changegroup != -1) {
845 if ($changegroup == 0) {
846 // do not allow changing to all groups without accessallgroups capability
847 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
848 $SESSION->activegroup
[$course->id
][$groupmode][$course->defaultgroupingid
] = 0;
852 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
853 $SESSION->activegroup
[$course->id
][$groupmode][$course->defaultgroupingid
] = $changegroup;
858 return $SESSION->activegroup
[$course->id
][$groupmode][$course->defaultgroupingid
];
862 * Returns group active in activity, changes the group by default if 'group' page param present
865 * @param stdClass|cm_info $cm course module object
866 * @param bool $update change active group if group param submitted
867 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
868 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
870 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
871 global $USER, $SESSION;
873 if (!$groupmode = groups_get_activity_groupmode($cm)) {
878 $context = context_module
::instance($cm->id
);
879 if (has_capability('moodle/site:accessallgroups', $context)) {
883 if (!is_array($allowedgroups)) {
884 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
885 $allowedgroups = groups_get_all_groups($cm->course
, 0, $cm->groupingid
);
887 $allowedgroups = groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
);
891 _group_verify_activegroup($cm->course
, $groupmode, $cm->groupingid
, $allowedgroups);
893 // set new active group if requested
894 $changegroup = optional_param('group', -1, PARAM_INT
);
895 if ($update and $changegroup != -1) {
897 if ($changegroup == 0) {
898 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
899 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
900 $SESSION->activegroup
[$cm->course
][$groupmode][$cm->groupingid
] = 0;
904 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
905 $SESSION->activegroup
[$cm->course
][$groupmode][$cm->groupingid
] = $changegroup;
910 return $SESSION->activegroup
[$cm->course
][$groupmode][$cm->groupingid
];
914 * Gets a list of groups that the user is allowed to access within the
915 * specified activity.
918 * @param stdClass|cm_info $cm Course-module
919 * @param int $userid User ID (defaults to current user)
920 * @return array An array of group objects, or false if none
922 function groups_get_activity_allowed_groups($cm,$userid=0) {
923 // Use current user by default
929 // Get groupmode for activity, taking into account course settings
930 $groupmode=groups_get_activity_groupmode($cm);
932 // If visible groups mode, or user has the accessallgroups capability,
933 // then they can access all groups for the activity...
934 $context = context_module
::instance($cm->id
);
935 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $context, $userid)) {
936 return groups_get_all_groups($cm->course
, 0, $cm->groupingid
);
938 // ...otherwise they can only access groups they belong to
939 return groups_get_all_groups($cm->course
, $userid, $cm->groupingid
);
944 * Determine if a given group is visible to user or not in a given context.
947 * @param int $groupid Group id to test. 0 for all groups.
948 * @param stdClass $course Course object.
949 * @param stdClass $cm Course module object.
950 * @param int $userid user id to test against. Defaults to $USER.
951 * @return boolean true if visible, false otherwise
953 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
956 if (empty($userid)) {
960 $groupmode = empty($cm) ?
groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
961 if ($groupmode == NOGROUPS ||
$groupmode == VISIBLEGROUPS
) {
962 // Groups are not used, or everything is visible, no need to go any further.
966 $context = empty($cm) ? context_course
::instance($course->id
) : context_module
::instance($cm->id
);
967 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
968 // User can see everything. Groupid = 0 is handled here as well.
970 } else if ($groupid != 0) {
971 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
972 $groups = empty($cm) ?
groups_get_all_groups($course->id
, $userid) : groups_get_activity_allowed_groups($cm, $userid);
973 if (array_key_exists($groupid, $groups)) {
974 // User can see the group.
982 * Get sql and parameters that will return user ids for a group or groups
984 * @param int|array $groupids Where this is an array of multiple groups, it will match on members of any of the groups
985 * @param context $context Course context or a context within a course. Mandatory when $groupid = USERSWITHOUTGROUP
986 * @return array($sql, $params)
987 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
989 function groups_get_members_ids_sql($groupids, context
$context = null) {
990 if (!is_array($groupids)) {
991 $groupids = [$groupids];
994 $groupjoin = groups_get_members_join($groupids, 'u.id', $context);
996 $sql = "SELECT DISTINCT u.id
999 WHERE u.deleted = 0";
1000 if (!empty($groupjoin->wheres
)) {
1001 $sql .= ' AND '. $groupjoin->wheres
;
1004 return array($sql, $groupjoin->params
);
1008 * Get sql join to return users in a group
1010 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1011 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1012 * @param context $context Course context or a context within a course. Mandatory when $groupids includes USERSWITHOUTGROUP
1013 * @return \core\dml\sql_join Contains joins, wheres, params
1014 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1016 function groups_get_members_join($groupids, $useridcolumn, context
$context = null) {
1019 // Use unique prefix just in case somebody makes some SQL magic with the result.
1022 $prefix = 'gm' . $i . '_';
1024 if (!is_array($groupids)) {
1025 $groupids = $groupids ?
[$groupids] : [];
1028 $coursecontext = (!empty($context)) ?
$context->get_course_context() : null;
1029 if (in_array(USERSWITHOUTGROUP
, $groupids) && empty($coursecontext)) {
1030 // Throw an exception if $context is empty or invalid because it's needed to get the users without any group.
1031 throw new coding_exception('Missing or wrong $context parameter in an attempt to get members without any group');
1034 // Handle cases where we need to include users not in any groups.
1035 if (($nogroupskey = array_search(USERSWITHOUTGROUP
, $groupids)) !== false) {
1036 // Get members without any group.
1037 $join = "LEFT JOIN (
1038 SELECT g.courseid, m.groupid, m.userid
1039 FROM {groups_members} m
1040 JOIN {groups} g ON g.id = m.groupid
1041 ) {$prefix}gm ON ({$prefix}gm.userid = {$useridcolumn} AND {$prefix}gm.courseid = :{$prefix}gcourseid)";
1042 $where = "{$prefix}gm.userid IS NULL";
1043 $param = ["{$prefix}gcourseid" => $coursecontext->instanceid
];
1044 unset($groupids[$nogroupskey]);
1046 // Handle any groups that also need to be included (eg searching for users in no groups OR within specified groups).
1047 if (!empty($groupids)) {
1048 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED
, $prefix);
1050 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1051 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1052 // TODO: This only handles 'Any' (logical OR) of the provided groups. MDL-68348 will add 'All' and 'None' support.
1053 $where = "({$where} OR {$prefix}gm2.userid IS NOT NULL)";
1054 $param = array_merge($param, $groupsparams);
1058 // Get members of defined group IDs only.
1059 list($groupssql, $param) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED
, $prefix);
1061 // TODO: This only handles 'Any' (logical OR) of the provided groups. MDL-68348 will add 'All' and 'None' support.
1062 $join = "JOIN {groups_members} {$prefix}gm
1063 ON ({$prefix}gm.userid = {$useridcolumn} AND {$prefix}gm.groupid {$groupssql})";
1067 return new \core\dml\
sql_join($join, $where, $param);
1071 * Internal method, sets up $SESSION->activegroup and verifies previous value
1073 * @param int $courseid
1074 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1075 * @param int $groupingid 0 means all groups
1076 * @param array $allowedgroups list of groups user can see
1078 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1079 global $SESSION, $USER;
1081 // init activegroup array if necessary
1082 if (!isset($SESSION->activegroup
)) {
1083 $SESSION->activegroup
= array();
1085 if (!array_key_exists($courseid, $SESSION->activegroup
)) {
1086 $SESSION->activegroup
[$courseid] = array(SEPARATEGROUPS
=>array(), VISIBLEGROUPS
=>array(), 'aag'=>array());
1089 // make sure that the current group info is ok
1090 if (array_key_exists($groupingid, $SESSION->activegroup
[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup
[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1091 // active group does not exist anymore or is 0
1092 if ($SESSION->activegroup
[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS
) {
1093 // do not do this if all groups selected and groupmode is not separate
1094 unset($SESSION->activegroup
[$courseid][$groupmode][$groupingid]);
1098 // set up defaults if necessary
1099 if (!array_key_exists($groupingid, $SESSION->activegroup
[$courseid][$groupmode])) {
1100 if ($groupmode == 'aag') {
1101 $SESSION->activegroup
[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1103 } else if ($allowedgroups) {
1104 if ($groupmode != SEPARATEGROUPS
and $mygroups = groups_get_all_groups($courseid, $USER->id
, $groupingid)) {
1105 $firstgroup = reset($mygroups);
1107 $firstgroup = reset($allowedgroups);
1109 $SESSION->activegroup
[$courseid][$groupmode][$groupingid] = $firstgroup->id
;
1112 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1113 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1114 $SESSION->activegroup
[$courseid][$groupmode][$groupingid] = 0;
1120 * Caches group data for a particular course to speed up subsequent requests.
1122 * @param int $courseid The course id to cache data for.
1123 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1124 * @return stdClass A data object containing groups, groupings, and mappings.
1126 function groups_cache_groupdata($courseid, cache
$cache = null) {
1129 if ($cache === null) {
1130 // Initialise a cache if we wern't given one.
1131 $cache = cache
::make('core', 'groupdata');
1134 // Get the groups that belong to the course.
1135 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1136 // Get the groupings that belong to the course.
1137 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1139 if (!is_array($groups)) {
1143 if (!is_array($groupings)) {
1144 $groupings = array();
1147 if (!empty($groupings)) {
1148 // Finally get the mappings between the two.
1149 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1150 $mappings = $DB->get_records_sql("
1151 SELECT gg.id, gg.groupingid, gg.groupid
1152 FROM {groupings_groups} gg
1153 JOIN {groups} g ON g.id = gg.groupid
1154 WHERE gg.groupingid $insql
1155 ORDER BY g.name ASC", $params);
1157 $mappings = array();
1160 // Prepare the data array.
1161 $data = new stdClass
;
1162 $data->groups
= $groups;
1163 $data->groupings
= $groupings;
1164 $data->mappings
= $mappings;
1166 $cache->set($courseid, $data);
1167 // Finally return it so it can be used if desired.
1172 * Gets group data for a course.
1174 * This returns an object with the following properties:
1175 * - groups : An array of all the groups in the course.
1176 * - groupings : An array of all the groupings within the course.
1177 * - mappings : An array of group to grouping mappings.
1179 * @param int $courseid The course id to get data for.
1180 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1183 function groups_get_course_data($courseid, cache
$cache = null) {
1184 if ($cache === null) {
1185 // Initialise a cache if we wern't given one.
1186 $cache = cache
::make('core', 'groupdata');
1188 // Try to retrieve it from the cache.
1189 $data = $cache->get($courseid);
1190 if ($data === false) {
1191 $data = groups_cache_groupdata($courseid, $cache);
1197 * Determine if the current user can see at least one of the groups of the specified user.
1199 * @param stdClass $course Course object.
1200 * @param int $userid user id to check against.
1201 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1202 * @return boolean true if visible, false otherwise
1205 function groups_user_groups_visible($course, $userid, $cm = null) {
1208 $groupmode = empty($cm) ?
groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1209 if ($groupmode == NOGROUPS ||
$groupmode == VISIBLEGROUPS
) {
1210 // Groups are not used, or everything is visible, no need to go any further.
1214 $context = empty($cm) ? context_course
::instance($course->id
) : context_module
::instance($cm->id
);
1215 if (has_capability('moodle/site:accessallgroups', $context)) {
1216 // User can see everything.
1219 // Group mode is separate, and user doesn't have access all groups capability.
1221 $usergroups = groups_get_all_groups($course->id
, $userid);
1222 $currentusergroups = groups_get_all_groups($course->id
, $USER->id
);
1224 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1225 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id
);
1228 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1229 if (!empty($samegroups)) {
1238 * Returns the users in the specified groups.
1240 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1242 * @param array $groupsids The list of groups ids to check
1243 * @param array $extrafields extra fields to be included in result
1244 * @param int $sort optional sorting of returned users
1245 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1248 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1251 $userfields = user_picture
::fields('u', $extrafields);
1252 list($insql, $params) = $DB->get_in_or_equal($groupsids);
1254 return $DB->get_records_sql("SELECT $userfields
1255 FROM {user} u, {groups_members} gm
1256 WHERE u.id = gm.userid AND gm.groupid $insql
1257 GROUP BY $userfields
1258 ORDER BY $sort", $params);
1262 * Returns users who share group membership with the specified user in the given actiivty.
1264 * @param stdClass|cm_info $cm course module
1265 * @param int $userid user id (empty for current user)
1266 * @return array a list of user
1269 function groups_get_activity_shared_group_members($cm, $userid = null) {
1272 if (empty($userid)) {
1276 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1277 // No groups no users.
1278 if (empty($groupsids)) {
1281 return groups_get_groups_members($groupsids);