Merge branch 'MDL-70075-39-2' of git://github.com/andrewnicols/moodle into MOODLE_39_...
[moodle.git] / lib / grouplib.php
blob6aa89065f46a91a4ee4b0fcc9a2d0a74bffd742d
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 * Determines if a group with a given groupid exists.
64 * @category group
65 * @param int $groupid The groupid to check for
66 * @return bool True if the group exists, false otherwise or if an error
67 * occurred.
69 function groups_group_exists($groupid) {
70 global $DB;
71 return $DB->record_exists('groups', array('id'=>$groupid));
74 /**
75 * Gets the name of a group with a specified id
77 * @category group
78 * @param int $groupid The id of the group
79 * @return string The name of the group
81 function groups_get_group_name($groupid) {
82 global $DB;
83 return $DB->get_field('groups', 'name', array('id'=>$groupid));
86 /**
87 * Gets the name of a grouping with a specified id
89 * @category group
90 * @param int $groupingid The id of the grouping
91 * @return string The name of the grouping
93 function groups_get_grouping_name($groupingid) {
94 global $DB;
95 return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
98 /**
99 * Returns the groupid of a group with the name specified for the course.
100 * Group names should be unique in course
102 * @category group
103 * @param int $courseid The id of the course
104 * @param string $name name of group (without magic quotes)
105 * @return int $groupid
107 function groups_get_group_by_name($courseid, $name) {
108 $data = groups_get_course_data($courseid);
109 foreach ($data->groups as $group) {
110 if ($group->name == $name) {
111 return $group->id;
114 return false;
118 * Returns the groupid of a group with the idnumber specified for the course.
119 * Group idnumbers should be unique within course
121 * @category group
122 * @param int $courseid The id of the course
123 * @param string $idnumber idnumber of group
124 * @return group object
126 function groups_get_group_by_idnumber($courseid, $idnumber) {
127 if (empty($idnumber)) {
128 return false;
130 $data = groups_get_course_data($courseid);
131 foreach ($data->groups as $group) {
132 if ($group->idnumber == $idnumber) {
133 return $group;
136 return false;
140 * Returns the groupingid of a grouping with the name specified for the course.
141 * Grouping names should be unique in course
143 * @category group
144 * @param int $courseid The id of the course
145 * @param string $name name of group (without magic quotes)
146 * @return int $groupid
148 function groups_get_grouping_by_name($courseid, $name) {
149 $data = groups_get_course_data($courseid);
150 foreach ($data->groupings as $grouping) {
151 if ($grouping->name == $name) {
152 return $grouping->id;
155 return false;
159 * Returns the groupingid of a grouping with the idnumber specified for the course.
160 * Grouping names should be unique within course
162 * @category group
163 * @param int $courseid The id of the course
164 * @param string $idnumber idnumber of the group
165 * @return grouping object
167 function groups_get_grouping_by_idnumber($courseid, $idnumber) {
168 if (empty($idnumber)) {
169 return false;
171 $data = groups_get_course_data($courseid);
172 foreach ($data->groupings as $grouping) {
173 if ($grouping->idnumber == $idnumber) {
174 return $grouping;
177 return false;
181 * Get the group object
183 * @category group
184 * @param int $groupid ID of the group.
185 * @param string $fields (default is all fields)
186 * @param int $strictness (IGNORE_MISSING - default)
187 * @return bool|stdClass group object or false if not found
188 * @throws dml_exception
190 function groups_get_group($groupid, $fields='*', $strictness=IGNORE_MISSING) {
191 global $DB;
192 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
196 * Get the grouping object
198 * @category group
199 * @param int $groupingid ID of the group.
200 * @param string $fields
201 * @param int $strictness (IGNORE_MISSING - default)
202 * @return stdClass group object
204 function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING) {
205 global $DB;
206 return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
210 * Gets array of all groups in a specified course (subject to the conditions imposed by the other arguments).
212 * @category group
213 * @param int $courseid The id of the course.
214 * @param int|int[] $userid optional user id or array of ids, returns only groups continaing one or more of those users.
215 * @param int $groupingid optional returns only groups in the specified grouping.
216 * @param string $fields defaults to g.*. This allows you to vary which fields are returned.
217 * If $groupingid is specified, the groupings_groups table will be available with alias gg.
218 * If $userid is specified, the groups_members table will be available as gm.
219 * @param bool $withmembers if true return an extra field members (int[]) which is the list of userids that
220 * are members of each group. For this to work, g.id (or g.*) must be included in $fields.
221 * In this case, the final results will always be an array indexed by group id.
222 * @return array returns an array of the group objects (unless you have done something very weird
223 * with the $fields option).
225 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false) {
226 global $DB;
228 // We need to check that we each field in the fields list belongs to the group table and that it has not being
229 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
230 $knownfields = true;
231 if ($fields !== 'g.*') {
232 // Quickly check if the first field is no longer g.id as using the
233 // cache will return an array indexed differently than when expect
234 if (strpos($fields, 'g.*') !== 0 && strpos($fields, 'g.id') !== 0) {
235 $knownfields = false;
236 } else {
237 $fieldbits = explode(',', $fields);
238 foreach ($fieldbits as $bit) {
239 $bit = trim($bit);
240 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
241 $knownfields = false;
242 break;
248 if (empty($userid) && $knownfields && !$withmembers) {
249 // We can use the cache.
250 $data = groups_get_course_data($courseid);
251 if (empty($groupingid)) {
252 // All groups.. Easy!
253 $groups = $data->groups;
254 } else {
255 $groups = array();
256 foreach ($data->mappings as $mapping) {
257 if ($mapping->groupingid != $groupingid) {
258 continue;
260 if (isset($data->groups[$mapping->groupid])) {
261 $groups[$mapping->groupid] = $data->groups[$mapping->groupid];
265 // Yay! We could use the cache. One more query saved.
266 return $groups;
269 $params = [];
270 $userfrom = '';
271 $userwhere = '';
272 if (!empty($userid)) {
273 list($usql, $params) = $DB->get_in_or_equal($userid);
274 $userfrom = "JOIN {groups_members} gm ON gm.groupid = g.id";
275 $userwhere = "AND gm.userid $usql";
278 $groupingfrom = '';
279 $groupingwhere = '';
280 if (!empty($groupingid)) {
281 $groupingfrom = "JOIN {groupings_groups} gg ON gg.groupid = g.id";
282 $groupingwhere = "AND gg.groupingid = ?";
283 $params[] = $groupingid;
286 array_unshift($params, $courseid);
288 $results = $DB->get_records_sql("
289 SELECT $fields
290 FROM {groups} g
291 $userfrom
292 $groupingfrom
293 WHERE g.courseid = ?
294 $userwhere
295 $groupingwhere
296 ORDER BY g.name ASC", $params);
298 if (!$withmembers) {
299 return $results;
302 // We also want group members. We do this in a separate query, becuse the above
303 // query will return a lot of data (e.g. g.description) for each group, and
304 // some groups may contain hundreds of members. We don't want the results
305 // to contain hundreds of copies of long descriptions.
306 $groups = [];
307 foreach ($results as $row) {
308 $groups[$row->id] = $row;
309 $groups[$row->id]->members = [];
311 $groupmembers = $DB->get_records_list('groups_members', 'groupid', array_keys($groups));
312 foreach ($groupmembers as $gm) {
313 $groups[$gm->groupid]->members[$gm->userid] = $gm->userid;
315 return $groups;
319 * Gets array of all groups in current user.
321 * @since Moodle 2.5
322 * @category group
323 * @return array Returns an array of the group objects.
325 function groups_get_my_groups() {
326 global $DB, $USER;
327 return $DB->get_records_sql("SELECT *
328 FROM {groups_members} gm
329 JOIN {groups} g
330 ON g.id = gm.groupid
331 WHERE gm.userid = ?
332 ORDER BY name ASC", array($USER->id));
336 * Returns info about user's groups in course.
338 * @category group
339 * @param int $courseid
340 * @param int $userid $USER if not specified
341 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
343 function groups_get_user_groups($courseid, $userid=0) {
344 global $USER, $DB;
346 if (empty($userid)) {
347 $userid = $USER->id;
350 $cache = cache::make('core', 'user_group_groupings');
352 // Try to retrieve group ids from the cache.
353 $usergroups = $cache->get($userid);
355 if ($usergroups === false) {
356 $sql = "SELECT g.id, g.courseid, gg.groupingid
357 FROM {groups} g
358 JOIN {groups_members} gm ON gm.groupid = g.id
359 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
360 WHERE gm.userid = ?";
362 $rs = $DB->get_recordset_sql($sql, array($userid));
364 $usergroups = array();
365 $allgroups = array();
367 foreach ($rs as $group) {
368 if (!array_key_exists($group->courseid, $allgroups)) {
369 $allgroups[$group->courseid] = array();
371 $allgroups[$group->courseid][$group->id] = $group->id;
372 if (!array_key_exists($group->courseid, $usergroups)) {
373 $usergroups[$group->courseid] = array();
375 if (is_null($group->groupingid)) {
376 continue;
378 if (!array_key_exists($group->groupingid, $usergroups[$group->courseid])) {
379 $usergroups[$group->courseid][$group->groupingid] = array();
381 $usergroups[$group->courseid][$group->groupingid][$group->id] = $group->id;
383 $rs->close();
385 foreach (array_keys($allgroups) as $cid) {
386 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
389 // Cache the data.
390 $cache->set($userid, $usergroups);
393 if (array_key_exists($courseid, $usergroups)) {
394 return $usergroups[$courseid];
395 } else {
396 return array('0' => array());
401 * Gets an array of all groupings in a specified course. This value is cached
402 * for a single course (so you can call it repeatedly for the same course
403 * without a performance penalty).
405 * @category group
406 * @param int $courseid return all groupings from course with this courseid
407 * @return array Returns an array of the grouping objects (empty if none)
409 function groups_get_all_groupings($courseid) {
410 $data = groups_get_course_data($courseid);
411 return $data->groupings;
415 * Determines if the user is a member of the given group.
417 * If $userid is null, use the global object.
419 * @category group
420 * @param int $groupid The group to check for membership.
421 * @param int $userid The user to check against the group.
422 * @return bool True if the user is a member, false otherwise.
424 function groups_is_member($groupid, $userid=null) {
425 global $USER, $DB;
427 if (!$userid) {
428 $userid = $USER->id;
431 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
435 * Determines if current or specified is member of any active group in activity
437 * @category group
438 * @staticvar array $cache
439 * @param stdClass|cm_info $cm course module object
440 * @param int $userid id of user, null means $USER->id
441 * @return bool true if user member of at least one group used in activity
443 function groups_has_membership($cm, $userid=null) {
444 global $CFG, $USER, $DB;
446 static $cache = array();
448 if (empty($userid)) {
449 $userid = $USER->id;
452 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
453 if (isset($cache[$cachekey])) {
454 return($cache[$cachekey]);
457 if ($cm->groupingid) {
458 // find out if member of any group in selected activity grouping
459 $sql = "SELECT 'x'
460 FROM {groups_members} gm, {groupings_groups} gg
461 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
462 $params = array($userid, $cm->groupingid);
464 } else {
465 // no grouping used - check all groups in course
466 $sql = "SELECT 'x'
467 FROM {groups_members} gm, {groups} g
468 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
469 $params = array($userid, $cm->course);
472 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
474 return $cache[$cachekey];
478 * Returns the users in the specified group.
480 * @category group
481 * @param int $groupid The groupid to get the users for
482 * @param int $fields The fields to return
483 * @param int $sort optional sorting of returned users
484 * @return array|bool Returns an array of the users for the specified
485 * group or false if no users or an error returned.
487 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
488 global $DB;
490 return $DB->get_records_sql("SELECT $fields
491 FROM {user} u, {groups_members} gm
492 WHERE u.id = gm.userid AND gm.groupid = ?
493 ORDER BY $sort", array($groupid));
498 * Returns the users in the specified grouping.
500 * @category group
501 * @param int $groupingid The groupingid to get the users for
502 * @param string $fields The fields to return
503 * @param string $sort optional sorting of returned users
504 * @return array|bool Returns an array of the users for the specified
505 * group or false if no users or an error returned.
507 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
508 global $DB;
510 return $DB->get_records_sql("SELECT $fields
511 FROM {user} u
512 INNER JOIN {groups_members} gm ON u.id = gm.userid
513 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
514 WHERE gg.groupingid = ?
515 ORDER BY $sort", array($groupingid));
519 * Returns effective groupmode used in course
521 * @category group
522 * @param stdClass $course course object.
523 * @return int group mode
525 function groups_get_course_groupmode($course) {
526 return $course->groupmode;
530 * Returns effective groupmode used in activity, course setting
531 * overrides activity setting if groupmodeforce enabled.
533 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
535 * @category group
536 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
537 * @param stdClass $course object optional course object to improve perf
538 * @return int group mode
540 function groups_get_activity_groupmode($cm, $course=null) {
541 if ($cm instanceof cm_info) {
542 return $cm->effectivegroupmode;
544 if (isset($course->id) and $course->id == $cm->course) {
545 //ok
546 } else {
547 // Get course object (reuse $COURSE if possible).
548 $course = get_course($cm->course, false);
551 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
555 * Print group menu selector for course level.
557 * @category group
558 * @param stdClass $course course object
559 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
560 * @param bool $return return as string instead of printing
561 * @return mixed void or string depending on $return param
563 function groups_print_course_menu($course, $urlroot, $return=false) {
564 global $USER, $OUTPUT;
566 if (!$groupmode = $course->groupmode) {
567 if ($return) {
568 return '';
569 } else {
570 return;
574 $context = context_course::instance($course->id);
575 $aag = has_capability('moodle/site:accessallgroups', $context);
577 $usergroups = array();
578 if ($groupmode == VISIBLEGROUPS or $aag) {
579 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
580 // Get user's own groups and put to the top.
581 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
582 } else {
583 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
586 $activegroup = groups_get_course_group($course, true, $allowedgroups);
588 $groupsmenu = array();
589 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
590 $groupsmenu[0] = get_string('allparticipants');
593 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
595 if ($groupmode == VISIBLEGROUPS) {
596 $grouplabel = get_string('groupsvisible');
597 } else {
598 $grouplabel = get_string('groupsseparate');
601 if ($aag and $course->defaultgroupingid) {
602 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
603 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
607 if (count($groupsmenu) == 1) {
608 $groupname = reset($groupsmenu);
609 $output = $grouplabel.': '.$groupname;
610 } else {
611 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
612 $select->label = $grouplabel;
613 $output = $OUTPUT->render($select);
616 $output = '<div class="groupselector">'.$output.'</div>';
618 if ($return) {
619 return $output;
620 } else {
621 echo $output;
626 * Turn an array of groups into an array of menu options.
627 * @param array $groups of group objects.
628 * @return array groupid => formatted group name.
630 function groups_list_to_menu($groups) {
631 $groupsmenu = array();
632 foreach ($groups as $group) {
633 $groupsmenu[$group->id] = format_string($group->name);
635 return $groupsmenu;
639 * Takes user's allowed groups and own groups and formats for use in group selector menu
640 * If user has allowed groups + own groups will add to an optgroup
641 * Own groups are removed from allowed groups
642 * @param array $allowedgroups All groups user is allowed to see
643 * @param array $usergroups Groups user belongs to
644 * @return array
646 function groups_sort_menu_options($allowedgroups, $usergroups) {
647 $useroptions = array();
648 if ($usergroups) {
649 $useroptions = groups_list_to_menu($usergroups);
651 // Remove user groups from other groups list.
652 foreach ($usergroups as $group) {
653 unset($allowedgroups[$group->id]);
657 $allowedoptions = array();
658 if ($allowedgroups) {
659 $allowedoptions = groups_list_to_menu($allowedgroups);
662 if ($useroptions && $allowedoptions) {
663 return array(
664 1 => array(get_string('mygroups', 'group') => $useroptions),
665 2 => array(get_string('othergroups', 'group') => $allowedoptions)
667 } else if ($useroptions) {
668 return $useroptions;
669 } else {
670 return $allowedoptions;
675 * Generates html to print menu selector for course level, listing all groups.
676 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
678 * @param stdclass $course course object.
679 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
680 * @param bool $update set this to true to update current active group based on the group param.
681 * @param int $activegroup Change group active to this group if $update set to true.
683 * @return string html or void
685 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
686 global $SESSION, $OUTPUT, $USER;
688 $groupmode = groups_get_course_groupmode($course);
689 $context = context_course::instance($course->id);
690 $groupsmenu = array();
692 if (has_capability('moodle/site:accessallgroups', $context)) {
693 $groupsmenu[0] = get_string('allparticipants');
694 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
695 } else {
696 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
699 $groupsmenu += groups_list_to_menu($allowedgroups);
701 if ($update) {
702 // Init activegroup array if necessary.
703 if (!isset($SESSION->activegroup)) {
704 $SESSION->activegroup = array();
706 if (!isset($SESSION->activegroup[$course->id])) {
707 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
709 if (empty($groupsmenu[$activegroup])) {
710 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
712 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
715 $grouplabel = get_string('groups');
716 if (count($groupsmenu) == 0) {
717 return '';
718 } else if (count($groupsmenu) == 1) {
719 $groupname = reset($groupsmenu);
720 $output = $grouplabel.': '.$groupname;
721 } else {
722 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
723 $select->label = $grouplabel;
724 $output = $OUTPUT->render($select);
727 return $output;
732 * Print group menu selector for activity.
734 * @category group
735 * @param stdClass|cm_info $cm course module object
736 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
737 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
738 * @param bool $return return as string instead of printing
739 * @param bool $hideallparticipants If true, this prevents the 'All participants'
740 * option from appearing in cases where it normally would. This is intended for
741 * use only by activities that cannot display all groups together. (Note that
742 * selecting this option does not prevent groups_get_activity_group from
743 * returning 0; it will still do that if the user has chosen 'all participants'
744 * in another activity, or not chosen anything.)
745 * @return mixed void or string depending on $return param
747 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
748 global $USER, $OUTPUT;
750 if ($urlroot instanceof moodle_url) {
751 // no changes necessary
753 } else {
754 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
755 // Display error if urlroot is not absolute (this causes the non-JS version to break)
756 debugging('groups_print_activity_menu requires absolute URL for ' .
757 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
758 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
759 DEBUG_DEVELOPER);
761 $urlroot = new moodle_url($urlroot);
764 if (!$groupmode = groups_get_activity_groupmode($cm)) {
765 if ($return) {
766 return '';
767 } else {
768 return;
772 $context = context_module::instance($cm->id);
773 $aag = has_capability('moodle/site:accessallgroups', $context);
775 $usergroups = array();
776 if ($groupmode == VISIBLEGROUPS or $aag) {
777 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid); // any group in grouping
778 // Get user's own groups and put to the top.
779 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
780 } else {
781 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); // only assigned groups
784 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
786 $groupsmenu = array();
787 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
788 $groupsmenu[0] = get_string('allparticipants');
791 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
793 if ($groupmode == VISIBLEGROUPS) {
794 $grouplabel = get_string('groupsvisible');
795 } else {
796 $grouplabel = get_string('groupsseparate');
799 if ($aag and $cm->groupingid) {
800 if ($grouping = groups_get_grouping($cm->groupingid)) {
801 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
805 if (count($groupsmenu) == 1) {
806 $groupname = reset($groupsmenu);
807 $output = $grouplabel.': '.$groupname;
808 } else {
809 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
810 $select->label = $grouplabel;
811 $output = $OUTPUT->render($select);
814 $output = '<div class="groupselector">'.$output.'</div>';
816 if ($return) {
817 return $output;
818 } else {
819 echo $output;
824 * Returns group active in course, changes the group by default if 'group' page param present
826 * @category group
827 * @param stdClass $course course bject
828 * @param bool $update change active group if group param submitted
829 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
830 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
832 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
833 global $USER, $SESSION;
835 if (!$groupmode = $course->groupmode) {
836 // NOGROUPS used
837 return false;
840 $context = context_course::instance($course->id);
841 if (has_capability('moodle/site:accessallgroups', $context)) {
842 $groupmode = 'aag';
845 if (!is_array($allowedgroups)) {
846 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
847 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
848 } else {
849 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
853 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
855 // set new active group if requested
856 $changegroup = optional_param('group', -1, PARAM_INT);
857 if ($update and $changegroup != -1) {
859 if ($changegroup == 0) {
860 // do not allow changing to all groups without accessallgroups capability
861 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
862 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
865 } else {
866 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
867 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
872 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
876 * Returns group active in activity, changes the group by default if 'group' page param present
878 * @category group
879 * @param stdClass|cm_info $cm course module object
880 * @param bool $update change active group if group param submitted
881 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
882 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
884 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
885 global $USER, $SESSION;
887 if (!$groupmode = groups_get_activity_groupmode($cm)) {
888 // NOGROUPS used
889 return false;
892 $context = context_module::instance($cm->id);
893 if (has_capability('moodle/site:accessallgroups', $context)) {
894 $groupmode = 'aag';
897 if (!is_array($allowedgroups)) {
898 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
899 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
900 } else {
901 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
905 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
907 // set new active group if requested
908 $changegroup = optional_param('group', -1, PARAM_INT);
909 if ($update and $changegroup != -1) {
911 if ($changegroup == 0) {
912 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
913 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
914 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
917 } else {
918 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
919 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
924 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
928 * Gets a list of groups that the user is allowed to access within the
929 * specified activity.
931 * @category group
932 * @param stdClass|cm_info $cm Course-module
933 * @param int $userid User ID (defaults to current user)
934 * @return array An array of group objects, or false if none
936 function groups_get_activity_allowed_groups($cm,$userid=0) {
937 // Use current user by default
938 global $USER;
939 if(!$userid) {
940 $userid=$USER->id;
943 // Get groupmode for activity, taking into account course settings
944 $groupmode=groups_get_activity_groupmode($cm);
946 // If visible groups mode, or user has the accessallgroups capability,
947 // then they can access all groups for the activity...
948 $context = context_module::instance($cm->id);
949 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
950 return groups_get_all_groups($cm->course, 0, $cm->groupingid);
951 } else {
952 // ...otherwise they can only access groups they belong to
953 return groups_get_all_groups($cm->course, $userid, $cm->groupingid);
958 * Determine if a given group is visible to user or not in a given context.
960 * @since Moodle 2.6
961 * @param int $groupid Group id to test. 0 for all groups.
962 * @param stdClass $course Course object.
963 * @param stdClass $cm Course module object.
964 * @param int $userid user id to test against. Defaults to $USER.
965 * @return boolean true if visible, false otherwise
967 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
968 global $USER;
970 if (empty($userid)) {
971 $userid = $USER->id;
974 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
975 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
976 // Groups are not used, or everything is visible, no need to go any further.
977 return true;
980 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
981 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
982 // User can see everything. Groupid = 0 is handled here as well.
983 return true;
984 } else if ($groupid != 0) {
985 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
986 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
987 if (array_key_exists($groupid, $groups)) {
988 // User can see the group.
989 return true;
992 return false;
996 * Get sql and parameters that will return user ids for a group or groups
998 * @param int|array $groupids Where this is an array of multiple groups, it will match on members of any of the groups
999 * @param context $context Course context or a context within a course. Mandatory when $groupid = USERSWITHOUTGROUP
1000 * @param int $groupsjointype Join type logic used. Defaults to 'Any' (logical OR).
1001 * @return array($sql, $params)
1002 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1004 function groups_get_members_ids_sql($groupids, context $context = null, $groupsjointype = GROUPS_JOIN_ANY) {
1005 if (!is_array($groupids)) {
1006 $groupids = [$groupids];
1009 $groupjoin = groups_get_members_join($groupids, 'u.id', $context, $groupsjointype);
1011 $sql = "SELECT DISTINCT u.id
1012 FROM {user} u
1013 $groupjoin->joins
1014 WHERE u.deleted = 0";
1015 if (!empty($groupjoin->wheres)) {
1016 $sql .= ' AND '. $groupjoin->wheres;
1019 return array($sql, $groupjoin->params);
1023 * Get sql join to return users in a group
1025 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1026 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1027 * @param context $context Course context or a context within a course. Mandatory when $groupids includes USERSWITHOUTGROUP
1028 * @param int $jointype Join type logic used. Defaults to 'Any' (logical OR).
1029 * @return \core\dml\sql_join Contains joins, wheres, params
1030 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1032 function groups_get_members_join($groupids, $useridcolumn, context $context = null, int $jointype = GROUPS_JOIN_ANY) {
1033 global $DB;
1035 // Use unique prefix just in case somebody makes some SQL magic with the result.
1036 static $i = 0;
1037 $i++;
1038 $prefix = 'gm' . $i . '_';
1040 if (!is_array($groupids)) {
1041 $groupids = $groupids ? [$groupids] : [];
1044 $join = '';
1045 $where = '';
1046 $param = [];
1048 $coursecontext = (!empty($context)) ? $context->get_course_context() : null;
1049 if (in_array(USERSWITHOUTGROUP, $groupids) && empty($coursecontext)) {
1050 // Throw an exception if $context is empty or invalid because it's needed to get the users without any group.
1051 throw new coding_exception('Missing or wrong $context parameter in an attempt to get members without any group');
1054 // Handle cases where we need to include/exclude users not in any groups.
1055 if (($nogroupskey = array_search(USERSWITHOUTGROUP, $groupids)) !== false) {
1056 // Get members without any group.
1057 $join .= "LEFT JOIN (
1058 SELECT g.courseid, m.groupid, m.userid
1059 FROM {groups_members} m
1060 JOIN {groups} g ON g.id = m.groupid
1061 ) {$prefix}gm ON ({$prefix}gm.userid = {$useridcolumn} AND {$prefix}gm.courseid = :{$prefix}gcourseid)";
1063 // Join type 'None' when filtering by 'no groups' means match users in at least one group.
1064 if ($jointype == GROUPS_JOIN_NONE) {
1065 $where = "{$prefix}gm.userid IS NOT NULL";
1066 } else {
1067 // All other cases need to match users not in any group.
1068 $where = "{$prefix}gm.userid IS NULL";
1071 $param = ["{$prefix}gcourseid" => $coursecontext->instanceid];
1072 unset($groupids[$nogroupskey]);
1075 // Handle any specified groups that need to be included.
1076 if (!empty($groupids)) {
1077 switch ($jointype) {
1078 case GROUPS_JOIN_ALL:
1079 // Handle matching all of the provided groups (logical AND).
1080 $joinallwheres = [];
1081 $aliaskey = 0;
1082 foreach ($groupids as $groupid) {
1083 $gmalias = "{$prefix}gm{$aliaskey}";
1084 $aliaskey++;
1085 $join .= "LEFT JOIN {groups_members} {$gmalias}
1086 ON ({$gmalias}.userid = {$useridcolumn} AND {$gmalias}.groupid = :{$gmalias}param)";
1087 $joinallwheres[] = "{$gmalias}.userid IS NOT NULL";
1088 $param["{$gmalias}param"] = $groupid;
1091 // Members of all of the specified groups only.
1092 if (empty($where)) {
1093 $where = '(' . implode(' AND ', $joinallwheres) . ')';
1094 } else {
1095 // Members of the specified groups and also no groups.
1096 // NOTE: This will always return no results, because you cannot be in specified groups and also be in no groups.
1097 $where = '(' . $where . ' AND ' . implode(' AND ', $joinallwheres) . ')';
1100 break;
1102 case GROUPS_JOIN_ANY:
1103 // Handle matching any of the provided groups (logical OR).
1104 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1106 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1107 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1108 $param = array_merge($param, $groupsparams);
1110 // Members of any of the specified groups only.
1111 if (empty($where)) {
1112 $where = "{$prefix}gm2.userid IS NOT NULL";
1113 } else {
1114 // Members of any of the specified groups or no groups.
1115 $where = "({$where} OR {$prefix}gm2.userid IS NOT NULL)";
1118 break;
1120 case GROUPS_JOIN_NONE:
1121 // Handle matching none of the provided groups (logical NOT).
1122 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1124 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1125 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1126 $param = array_merge($param, $groupsparams);
1128 // Members of none of the specified groups only.
1129 if (empty($where)) {
1130 $where = "{$prefix}gm2.userid IS NULL";
1131 } else {
1132 // Members of any unspecified groups (not a member of the specified groups, and not a member of no groups).
1133 $where = "({$where} AND {$prefix}gm2.userid IS NULL)";
1136 break;
1140 return new \core\dml\sql_join($join, $where, $param);
1144 * Internal method, sets up $SESSION->activegroup and verifies previous value
1146 * @param int $courseid
1147 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1148 * @param int $groupingid 0 means all groups
1149 * @param array $allowedgroups list of groups user can see
1151 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1152 global $SESSION, $USER;
1154 // init activegroup array if necessary
1155 if (!isset($SESSION->activegroup)) {
1156 $SESSION->activegroup = array();
1158 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1159 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1162 // make sure that the current group info is ok
1163 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1164 // active group does not exist anymore or is 0
1165 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1166 // do not do this if all groups selected and groupmode is not separate
1167 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1171 // set up defaults if necessary
1172 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1173 if ($groupmode == 'aag') {
1174 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1176 } else if ($allowedgroups) {
1177 if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
1178 $firstgroup = reset($mygroups);
1179 } else {
1180 $firstgroup = reset($allowedgroups);
1182 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1184 } else {
1185 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1186 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1187 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1193 * Caches group data for a particular course to speed up subsequent requests.
1195 * @param int $courseid The course id to cache data for.
1196 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1197 * @return stdClass A data object containing groups, groupings, and mappings.
1199 function groups_cache_groupdata($courseid, cache $cache = null) {
1200 global $DB;
1202 if ($cache === null) {
1203 // Initialise a cache if we wern't given one.
1204 $cache = cache::make('core', 'groupdata');
1207 // Get the groups that belong to the course.
1208 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1209 // Get the groupings that belong to the course.
1210 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1212 if (!is_array($groups)) {
1213 $groups = array();
1216 if (!is_array($groupings)) {
1217 $groupings = array();
1220 if (!empty($groupings)) {
1221 // Finally get the mappings between the two.
1222 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1223 $mappings = $DB->get_records_sql("
1224 SELECT gg.id, gg.groupingid, gg.groupid
1225 FROM {groupings_groups} gg
1226 JOIN {groups} g ON g.id = gg.groupid
1227 WHERE gg.groupingid $insql
1228 ORDER BY g.name ASC", $params);
1229 } else {
1230 $mappings = array();
1233 // Prepare the data array.
1234 $data = new stdClass;
1235 $data->groups = $groups;
1236 $data->groupings = $groupings;
1237 $data->mappings = $mappings;
1238 // Cache the data.
1239 $cache->set($courseid, $data);
1240 // Finally return it so it can be used if desired.
1241 return $data;
1245 * Gets group data for a course.
1247 * This returns an object with the following properties:
1248 * - groups : An array of all the groups in the course.
1249 * - groupings : An array of all the groupings within the course.
1250 * - mappings : An array of group to grouping mappings.
1252 * @param int $courseid The course id to get data for.
1253 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1254 * @return stdClass
1256 function groups_get_course_data($courseid, cache $cache = null) {
1257 if ($cache === null) {
1258 // Initialise a cache if we wern't given one.
1259 $cache = cache::make('core', 'groupdata');
1261 // Try to retrieve it from the cache.
1262 $data = $cache->get($courseid);
1263 if ($data === false) {
1264 $data = groups_cache_groupdata($courseid, $cache);
1266 return $data;
1270 * Determine if the current user can see at least one of the groups of the specified user.
1272 * @param stdClass $course Course object.
1273 * @param int $userid user id to check against.
1274 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1275 * @return boolean true if visible, false otherwise
1276 * @since Moodle 2.9
1278 function groups_user_groups_visible($course, $userid, $cm = null) {
1279 global $USER;
1281 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1282 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1283 // Groups are not used, or everything is visible, no need to go any further.
1284 return true;
1287 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1288 if (has_capability('moodle/site:accessallgroups', $context)) {
1289 // User can see everything.
1290 return true;
1291 } else {
1292 // Group mode is separate, and user doesn't have access all groups capability.
1293 if (empty($cm)) {
1294 $usergroups = groups_get_all_groups($course->id, $userid);
1295 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1296 } else {
1297 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1298 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1301 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1302 if (!empty($samegroups)) {
1303 // We share groups!
1304 return true;
1307 return false;
1311 * Returns the users in the specified groups.
1313 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1315 * @param array $groupsids The list of groups ids to check
1316 * @param array $extrafields extra fields to be included in result
1317 * @param int $sort optional sorting of returned users
1318 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1319 * @since Moodle 3.3
1321 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1322 global $DB;
1324 $userfields = user_picture::fields('u', $extrafields);
1325 list($insql, $params) = $DB->get_in_or_equal($groupsids);
1327 return $DB->get_records_sql("SELECT $userfields
1328 FROM {user} u, {groups_members} gm
1329 WHERE u.id = gm.userid AND gm.groupid $insql
1330 GROUP BY $userfields
1331 ORDER BY $sort", $params);
1335 * Returns users who share group membership with the specified user in the given actiivty.
1337 * @param stdClass|cm_info $cm course module
1338 * @param int $userid user id (empty for current user)
1339 * @return array a list of user
1340 * @since Moodle 3.3
1342 function groups_get_activity_shared_group_members($cm, $userid = null) {
1343 global $USER;
1345 if (empty($userid)) {
1346 $userid = $USER;
1349 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1350 // No groups no users.
1351 if (empty($groupsids)) {
1352 return [];
1354 return groups_get_groups_members($groupsids);