Merge branch 'MDL-66992-master' of https://github.com/tungthai/moodle
[moodle.git] / lib / grouplib.php
blob34b48690ff336eecd52666ed28631d1cd72915d8
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);
47 /**
48 * Determines if a group with a given groupid exists.
50 * @category group
51 * @param int $groupid The groupid to check for
52 * @return bool True if the group exists, false otherwise or if an error
53 * occurred.
55 function groups_group_exists($groupid) {
56 global $DB;
57 return $DB->record_exists('groups', array('id'=>$groupid));
60 /**
61 * Gets the name of a group with a specified id
63 * @category group
64 * @param int $groupid The id of the group
65 * @return string The name of the group
67 function groups_get_group_name($groupid) {
68 global $DB;
69 return $DB->get_field('groups', 'name', array('id'=>$groupid));
72 /**
73 * Gets the name of a grouping with a specified id
75 * @category group
76 * @param int $groupingid The id of the grouping
77 * @return string The name of the grouping
79 function groups_get_grouping_name($groupingid) {
80 global $DB;
81 return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
84 /**
85 * Returns the groupid of a group with the name specified for the course.
86 * Group names should be unique in course
88 * @category group
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) {
97 return $group->id;
100 return false;
104 * Returns the groupid of a group with the idnumber specified for the course.
105 * Group idnumbers should be unique within course
107 * @category group
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)) {
114 return false;
116 $data = groups_get_course_data($courseid);
117 foreach ($data->groups as $group) {
118 if ($group->idnumber == $idnumber) {
119 return $group;
122 return false;
126 * Returns the groupingid of a grouping with the name specified for the course.
127 * Grouping names should be unique in course
129 * @category group
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;
141 return false;
145 * Returns the groupingid of a grouping with the idnumber specified for the course.
146 * Grouping names should be unique within course
148 * @category group
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)) {
155 return false;
157 $data = groups_get_course_data($courseid);
158 foreach ($data->groupings as $grouping) {
159 if ($grouping->idnumber == $idnumber) {
160 return $grouping;
163 return false;
167 * Get the group object
169 * @category group
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) {
177 global $DB;
178 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
182 * Get the grouping object
184 * @category group
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) {
191 global $DB;
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).
198 * @category group
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) {
212 global $DB;
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.
216 $knownfields = true;
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;
222 } else {
223 $fieldbits = explode(',', $fields);
224 foreach ($fieldbits as $bit) {
225 $bit = trim($bit);
226 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
227 $knownfields = false;
228 break;
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;
240 } else {
241 $groups = array();
242 foreach ($data->mappings as $mapping) {
243 if ($mapping->groupingid != $groupingid) {
244 continue;
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.
252 return $groups;
255 $params = [];
256 $userfrom = '';
257 $userwhere = '';
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";
264 $groupingfrom = '';
265 $groupingwhere = '';
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("
275 SELECT $fields
276 FROM {groups} g
277 $userfrom
278 $groupingfrom
279 WHERE g.courseid = ?
280 $userwhere
281 $groupingwhere
282 ORDER BY g.name ASC", $params);
284 if (!$withmembers) {
285 return $results;
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.
292 $groups = [];
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;
301 return $groups;
305 * Gets array of all groups in current user.
307 * @since Moodle 2.5
308 * @category group
309 * @return array Returns an array of the group objects.
311 function groups_get_my_groups() {
312 global $DB, $USER;
313 return $DB->get_records_sql("SELECT *
314 FROM {groups_members} gm
315 JOIN {groups} g
316 ON g.id = gm.groupid
317 WHERE gm.userid = ?
318 ORDER BY name ASC", array($USER->id));
322 * Returns info about user's groups in course.
324 * @category group
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) {
330 global $USER, $DB;
332 if (empty($userid)) {
333 $userid = $USER->id;
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
343 FROM {groups} g
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)) {
362 continue;
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;
369 $rs->close();
371 foreach (array_keys($allgroups) as $cid) {
372 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
375 // Cache the data.
376 $cache->set($userid, $usergroups);
379 if (array_key_exists($courseid, $usergroups)) {
380 return $usergroups[$courseid];
381 } else {
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).
391 * @category group
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.
405 * @category group
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) {
411 global $USER, $DB;
413 if (!$userid) {
414 $userid = $USER->id;
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
423 * @category group
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)) {
435 $userid = $USER->id;
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
445 $sql = "SELECT 'x'
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);
450 } else {
451 // no grouping used - check all groups in course
452 $sql = "SELECT 'x'
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.
466 * @category 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') {
474 global $DB;
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.
486 * @category group
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') {
494 global $DB;
496 return $DB->get_records_sql("SELECT $fields
497 FROM {user} u
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
507 * @category group
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
521 * @category group
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) {
531 //ok
532 } else {
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.
543 * @category group
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) {
553 if ($return) {
554 return '';
555 } else {
556 return;
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);
568 } else {
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');
583 } else {
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;
596 } else {
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>';
604 if ($return) {
605 return $output;
606 } else {
607 echo $output;
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);
621 return $groupsmenu;
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
630 * @return array
632 function groups_sort_menu_options($allowedgroups, $usergroups) {
633 $useroptions = array();
634 if ($usergroups) {
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) {
649 return array(
650 1 => array(get_string('mygroups', 'group') => $useroptions),
651 2 => array(get_string('othergroups', 'group') => $allowedoptions)
653 } else if ($useroptions) {
654 return $useroptions;
655 } else {
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);
681 } else {
682 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
685 $groupsmenu += groups_list_to_menu($allowedgroups);
687 if ($update) {
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) {
703 return '';
704 } else if (count($groupsmenu) == 1) {
705 $groupname = reset($groupsmenu);
706 $output = $grouplabel.': '.$groupname;
707 } else {
708 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
709 $select->label = $grouplabel;
710 $output = $OUTPUT->render($select);
713 return $output;
718 * Print group menu selector for activity.
720 * @category group
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
739 } else {
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\');',
745 DEBUG_DEVELOPER);
747 $urlroot = new moodle_url($urlroot);
750 if (!$groupmode = groups_get_activity_groupmode($cm)) {
751 if ($return) {
752 return '';
753 } else {
754 return;
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);
766 } else {
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');
781 } else {
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;
794 } else {
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>';
802 if ($return) {
803 return $output;
804 } else {
805 echo $output;
810 * Returns group active in course, changes the group by default if 'group' page param present
812 * @category group
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) {
822 // NOGROUPS used
823 return false;
826 $context = context_course::instance($course->id);
827 if (has_capability('moodle/site:accessallgroups', $context)) {
828 $groupmode = 'aag';
831 if (!is_array($allowedgroups)) {
832 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
833 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
834 } else {
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;
851 } else {
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
864 * @category group
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)) {
874 // NOGROUPS used
875 return false;
878 $context = context_module::instance($cm->id);
879 if (has_capability('moodle/site:accessallgroups', $context)) {
880 $groupmode = 'aag';
883 if (!is_array($allowedgroups)) {
884 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
885 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
886 } else {
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;
903 } else {
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.
917 * @category group
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
924 global $USER;
925 if(!$userid) {
926 $userid=$USER->id;
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);
937 } else {
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.
946 * @since Moodle 2.6
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) {
954 global $USER;
956 if (empty($userid)) {
957 $userid = $USER->id;
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.
963 return true;
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.
969 return true;
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.
975 return true;
978 return false;
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
997 FROM {user} u
998 $groupjoin->joins
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) {
1017 global $DB;
1019 // Use unique prefix just in case somebody makes some SQL magic with the result.
1020 static $i = 0;
1021 $i++;
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);
1057 } else {
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})";
1064 $where = '';
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);
1106 } else {
1107 $firstgroup = reset($allowedgroups);
1109 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1111 } else {
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) {
1127 global $DB;
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)) {
1140 $groups = array();
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);
1156 } else {
1157 $mappings = array();
1160 // Prepare the data array.
1161 $data = new stdClass;
1162 $data->groups = $groups;
1163 $data->groupings = $groupings;
1164 $data->mappings = $mappings;
1165 // Cache the data.
1166 $cache->set($courseid, $data);
1167 // Finally return it so it can be used if desired.
1168 return $data;
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.
1181 * @return stdClass
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);
1193 return $data;
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
1203 * @since Moodle 2.9
1205 function groups_user_groups_visible($course, $userid, $cm = null) {
1206 global $USER;
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.
1211 return true;
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.
1217 return true;
1218 } else {
1219 // Group mode is separate, and user doesn't have access all groups capability.
1220 if (empty($cm)) {
1221 $usergroups = groups_get_all_groups($course->id, $userid);
1222 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1223 } else {
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)) {
1230 // We share groups!
1231 return true;
1234 return false;
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.
1246 * @since Moodle 3.3
1248 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1249 global $DB;
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
1267 * @since Moodle 3.3
1269 function groups_get_activity_shared_group_members($cm, $userid = null) {
1270 global $USER;
1272 if (empty($userid)) {
1273 $userid = $USER;
1276 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1277 // No groups no users.
1278 if (empty($groupsids)) {
1279 return [];
1281 return groups_get_groups_members($groupsids);