MDL-76843 quiz: add test to verify random essay stats now work
[moodle.git] / lib / grouplib.php
blobbee8583d979a6a2e00dfc9b8c8207a26850e0acb
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 * Before output, you should call {@see format_string} on the result
79 * @category group
80 * @param int $groupid The id of the group
81 * @return string The name of the group
83 function groups_get_group_name($groupid) {
84 global $DB;
85 return $DB->get_field('groups', 'name', array('id'=>$groupid));
88 /**
89 * Gets the name of a grouping with a specified id
91 * Before output, you should call {@see format_string} on the result
93 * @category group
94 * @param int $groupingid The id of the grouping
95 * @return string The name of the grouping
97 function groups_get_grouping_name($groupingid) {
98 global $DB;
99 return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
103 * Returns the groupid of a group with the name specified for the course.
104 * Group names should be unique in course
106 * @category group
107 * @param int $courseid The id of the course
108 * @param string $name name of group (without magic quotes)
109 * @return int $groupid
111 function groups_get_group_by_name($courseid, $name) {
112 $data = groups_get_course_data($courseid);
113 foreach ($data->groups as $group) {
114 if ($group->name == $name) {
115 return $group->id;
118 return false;
122 * Returns the groupid of a group with the idnumber specified for the course.
123 * Group idnumbers should be unique within course
125 * @category group
126 * @param int $courseid The id of the course
127 * @param string $idnumber idnumber of group
128 * @return group object
130 function groups_get_group_by_idnumber($courseid, $idnumber) {
131 if (empty($idnumber)) {
132 return false;
134 $data = groups_get_course_data($courseid);
135 foreach ($data->groups as $group) {
136 if ($group->idnumber == $idnumber) {
137 return $group;
140 return false;
144 * Returns the groupingid of a grouping with the name specified for the course.
145 * Grouping names should be unique in course
147 * @category group
148 * @param int $courseid The id of the course
149 * @param string $name name of group (without magic quotes)
150 * @return int $groupid
152 function groups_get_grouping_by_name($courseid, $name) {
153 $data = groups_get_course_data($courseid);
154 foreach ($data->groupings as $grouping) {
155 if ($grouping->name == $name) {
156 return $grouping->id;
159 return false;
163 * Returns the groupingid of a grouping with the idnumber specified for the course.
164 * Grouping names should be unique within course
166 * @category group
167 * @param int $courseid The id of the course
168 * @param string $idnumber idnumber of the group
169 * @return grouping object
171 function groups_get_grouping_by_idnumber($courseid, $idnumber) {
172 if (empty($idnumber)) {
173 return false;
175 $data = groups_get_course_data($courseid);
176 foreach ($data->groupings as $grouping) {
177 if ($grouping->idnumber == $idnumber) {
178 return $grouping;
181 return false;
185 * Get the group object
187 * @category group
188 * @param int $groupid ID of the group.
189 * @param string $fields (default is all fields)
190 * @param int $strictness (IGNORE_MISSING - default)
191 * @return bool|stdClass group object or false if not found
192 * @throws dml_exception
194 function groups_get_group($groupid, $fields='*', $strictness=IGNORE_MISSING) {
195 global $DB;
196 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
200 * Get the grouping object
202 * @category group
203 * @param int $groupingid ID of the group.
204 * @param string $fields
205 * @param int $strictness (IGNORE_MISSING - default)
206 * @return stdClass group object
208 function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING) {
209 global $DB;
210 return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
214 * Gets array of all groups in a specified course (subject to the conditions imposed by the other arguments).
216 * @category group
217 * @param int $courseid The id of the course.
218 * @param int|int[] $userid optional user id or array of ids, returns only groups continaing one or more of those users.
219 * @param int $groupingid optional returns only groups in the specified grouping.
220 * @param string $fields defaults to g.*. This allows you to vary which fields are returned.
221 * If $groupingid is specified, the groupings_groups table will be available with alias gg.
222 * If $userid is specified, the groups_members table will be available as gm.
223 * @param bool $withmembers if true return an extra field members (int[]) which is the list of userids that
224 * are members of each group. For this to work, g.id (or g.*) must be included in $fields.
225 * In this case, the final results will always be an array indexed by group id.
226 * @return array returns an array of the group objects (unless you have done something very weird
227 * with the $fields option).
229 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false) {
230 global $DB;
232 // We need to check that we each field in the fields list belongs to the group table and that it has not being
233 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
234 $knownfields = true;
235 if ($fields !== 'g.*') {
236 // Quickly check if the first field is no longer g.id as using the
237 // cache will return an array indexed differently than when expect
238 if (strpos($fields, 'g.*') !== 0 && strpos($fields, 'g.id') !== 0) {
239 $knownfields = false;
240 } else {
241 $fieldbits = explode(',', $fields);
242 foreach ($fieldbits as $bit) {
243 $bit = trim($bit);
244 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
245 $knownfields = false;
246 break;
252 if (empty($userid) && $knownfields && !$withmembers) {
253 // We can use the cache.
254 $data = groups_get_course_data($courseid);
255 if (empty($groupingid)) {
256 // All groups.. Easy!
257 $groups = $data->groups;
258 } else {
259 $groups = array();
260 foreach ($data->mappings as $mapping) {
261 if ($mapping->groupingid != $groupingid) {
262 continue;
264 if (isset($data->groups[$mapping->groupid])) {
265 $groups[$mapping->groupid] = $data->groups[$mapping->groupid];
269 // Yay! We could use the cache. One more query saved.
270 return $groups;
273 $params = [];
274 $userfrom = '';
275 $userwhere = '';
276 if (!empty($userid)) {
277 list($usql, $params) = $DB->get_in_or_equal($userid);
278 $userfrom = "JOIN {groups_members} gm ON gm.groupid = g.id";
279 $userwhere = "AND gm.userid $usql";
282 $groupingfrom = '';
283 $groupingwhere = '';
284 if (!empty($groupingid)) {
285 $groupingfrom = "JOIN {groupings_groups} gg ON gg.groupid = g.id";
286 $groupingwhere = "AND gg.groupingid = ?";
287 $params[] = $groupingid;
290 array_unshift($params, $courseid);
292 $results = $DB->get_records_sql("
293 SELECT $fields
294 FROM {groups} g
295 $userfrom
296 $groupingfrom
297 WHERE g.courseid = ?
298 $userwhere
299 $groupingwhere
300 ORDER BY g.name ASC", $params);
302 if (!$withmembers) {
303 return $results;
306 // We also want group members. We do this in a separate query, becuse the above
307 // query will return a lot of data (e.g. g.description) for each group, and
308 // some groups may contain hundreds of members. We don't want the results
309 // to contain hundreds of copies of long descriptions.
310 $groups = [];
311 foreach ($results as $row) {
312 $groups[$row->id] = $row;
313 $groups[$row->id]->members = [];
315 $groupmembers = $DB->get_records_list('groups_members', 'groupid', array_keys($groups));
316 foreach ($groupmembers as $gm) {
317 $groups[$gm->groupid]->members[$gm->userid] = $gm->userid;
319 return $groups;
323 * Gets array of all groups in current user.
325 * @since Moodle 2.5
326 * @category group
327 * @return array Returns an array of the group objects.
329 function groups_get_my_groups() {
330 global $DB, $USER;
331 return $DB->get_records_sql("SELECT *
332 FROM {groups_members} gm
333 JOIN {groups} g
334 ON g.id = gm.groupid
335 WHERE gm.userid = ?
336 ORDER BY name ASC", array($USER->id));
340 * Returns info about user's groups in course.
342 * @category group
343 * @param int $courseid
344 * @param int $userid $USER if not specified
345 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
347 function groups_get_user_groups($courseid, $userid=0) {
348 global $USER, $DB;
350 if (empty($userid)) {
351 $userid = $USER->id;
354 $cache = cache::make('core', 'user_group_groupings');
356 // Try to retrieve group ids from the cache.
357 $usergroups = $cache->get($userid);
359 if ($usergroups === false) {
360 $sql = "SELECT g.id, g.courseid, gg.groupingid
361 FROM {groups} g
362 JOIN {groups_members} gm ON gm.groupid = g.id
363 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
364 WHERE gm.userid = ?";
366 $rs = $DB->get_recordset_sql($sql, array($userid));
368 $usergroups = array();
369 $allgroups = array();
371 foreach ($rs as $group) {
372 if (!array_key_exists($group->courseid, $allgroups)) {
373 $allgroups[$group->courseid] = array();
375 $allgroups[$group->courseid][$group->id] = $group->id;
376 if (!array_key_exists($group->courseid, $usergroups)) {
377 $usergroups[$group->courseid] = array();
379 if (is_null($group->groupingid)) {
380 continue;
382 if (!array_key_exists($group->groupingid, $usergroups[$group->courseid])) {
383 $usergroups[$group->courseid][$group->groupingid] = array();
385 $usergroups[$group->courseid][$group->groupingid][$group->id] = $group->id;
387 $rs->close();
389 foreach (array_keys($allgroups) as $cid) {
390 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
393 // Cache the data.
394 $cache->set($userid, $usergroups);
397 if (array_key_exists($courseid, $usergroups)) {
398 return $usergroups[$courseid];
399 } else {
400 return array('0' => array());
405 * Gets an array of all groupings in a specified course. This value is cached
406 * for a single course (so you can call it repeatedly for the same course
407 * without a performance penalty).
409 * @category group
410 * @param int $courseid return all groupings from course with this courseid
411 * @return array Returns an array of the grouping objects (empty if none)
413 function groups_get_all_groupings($courseid) {
414 $data = groups_get_course_data($courseid);
415 return $data->groupings;
419 * Determines if the user is a member of the given group.
421 * If $userid is null, use the global object.
423 * @category group
424 * @param int $groupid The group to check for membership.
425 * @param int $userid The user to check against the group.
426 * @return bool True if the user is a member, false otherwise.
428 function groups_is_member($groupid, $userid=null) {
429 global $USER, $DB;
431 if (!$userid) {
432 $userid = $USER->id;
435 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
439 * Determines if current or specified is member of any active group in activity
441 * @category group
442 * @staticvar array $cache
443 * @param stdClass|cm_info $cm course module object
444 * @param int $userid id of user, null means $USER->id
445 * @return bool true if user member of at least one group used in activity
447 function groups_has_membership($cm, $userid=null) {
448 global $CFG, $USER, $DB;
450 static $cache = array();
452 if (empty($userid)) {
453 $userid = $USER->id;
456 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
457 if (isset($cache[$cachekey])) {
458 return($cache[$cachekey]);
461 if ($cm->groupingid) {
462 // find out if member of any group in selected activity grouping
463 $sql = "SELECT 'x'
464 FROM {groups_members} gm, {groupings_groups} gg
465 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
466 $params = array($userid, $cm->groupingid);
468 } else {
469 // no grouping used - check all groups in course
470 $sql = "SELECT 'x'
471 FROM {groups_members} gm, {groups} g
472 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
473 $params = array($userid, $cm->course);
476 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
478 return $cache[$cachekey];
482 * Returns the users in the specified group.
484 * @category group
485 * @param int $groupid The groupid to get the users for
486 * @param int $fields The fields to return
487 * @param int $sort optional sorting of returned users
488 * @return array|bool Returns an array of the users for the specified
489 * group or false if no users or an error returned.
491 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
492 global $DB;
494 return $DB->get_records_sql("SELECT $fields
495 FROM {user} u, {groups_members} gm
496 WHERE u.id = gm.userid AND gm.groupid = ?
497 ORDER BY $sort", array($groupid));
502 * Returns the users in the specified grouping.
504 * @category group
505 * @param int $groupingid The groupingid to get the users for
506 * @param string $fields The fields to return
507 * @param string $sort optional sorting of returned users
508 * @return array|bool Returns an array of the users for the specified
509 * group or false if no users or an error returned.
511 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
512 global $DB;
514 return $DB->get_records_sql("SELECT $fields
515 FROM {user} u
516 INNER JOIN {groups_members} gm ON u.id = gm.userid
517 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
518 WHERE gg.groupingid = ?
519 ORDER BY $sort", array($groupingid));
523 * Returns effective groupmode used in course
525 * @category group
526 * @param stdClass $course course object.
527 * @return int group mode
529 function groups_get_course_groupmode($course) {
530 return $course->groupmode;
534 * Returns effective groupmode used in activity, course setting
535 * overrides activity setting if groupmodeforce enabled.
537 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
539 * @category group
540 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
541 * @param stdClass $course object optional course object to improve perf
542 * @return int group mode
544 function groups_get_activity_groupmode($cm, $course=null) {
545 if ($cm instanceof cm_info) {
546 return $cm->effectivegroupmode;
548 if (isset($course->id) and $course->id == $cm->course) {
549 //ok
550 } else {
551 // Get course object (reuse $COURSE if possible).
552 $course = get_course($cm->course, false);
555 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
559 * Print group menu selector for course level.
561 * @category group
562 * @param stdClass $course course object
563 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
564 * @param bool $return return as string instead of printing
565 * @return mixed void or string depending on $return param
567 function groups_print_course_menu($course, $urlroot, $return=false) {
568 global $USER, $OUTPUT;
570 if (!$groupmode = $course->groupmode) {
571 if ($return) {
572 return '';
573 } else {
574 return;
578 $context = context_course::instance($course->id);
579 $aag = has_capability('moodle/site:accessallgroups', $context);
581 $usergroups = array();
582 if ($groupmode == VISIBLEGROUPS or $aag) {
583 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
584 // Get user's own groups and put to the top.
585 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
586 } else {
587 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
590 $activegroup = groups_get_course_group($course, true, $allowedgroups);
592 $groupsmenu = array();
593 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
594 $groupsmenu[0] = get_string('allparticipants');
597 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
599 if ($groupmode == VISIBLEGROUPS) {
600 $grouplabel = get_string('groupsvisible');
601 } else {
602 $grouplabel = get_string('groupsseparate');
605 if ($aag and $course->defaultgroupingid) {
606 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
607 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
611 if (count($groupsmenu) == 1) {
612 $groupname = reset($groupsmenu);
613 $output = $grouplabel.': '.$groupname;
614 } else {
615 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
616 $select->label = $grouplabel;
617 $output = $OUTPUT->render($select);
620 $output = '<div class="groupselector">'.$output.'</div>';
622 if ($return) {
623 return $output;
624 } else {
625 echo $output;
630 * Turn an array of groups into an array of menu options.
631 * @param array $groups of group objects.
632 * @return array groupid => formatted group name.
634 function groups_list_to_menu($groups) {
635 $groupsmenu = array();
636 foreach ($groups as $group) {
637 $groupsmenu[$group->id] = format_string($group->name);
639 return $groupsmenu;
643 * Takes user's allowed groups and own groups and formats for use in group selector menu
644 * If user has allowed groups + own groups will add to an optgroup
645 * Own groups are removed from allowed groups
646 * @param array $allowedgroups All groups user is allowed to see
647 * @param array $usergroups Groups user belongs to
648 * @return array
650 function groups_sort_menu_options($allowedgroups, $usergroups) {
651 $useroptions = array();
652 if ($usergroups) {
653 $useroptions = groups_list_to_menu($usergroups);
655 // Remove user groups from other groups list.
656 foreach ($usergroups as $group) {
657 unset($allowedgroups[$group->id]);
661 $allowedoptions = array();
662 if ($allowedgroups) {
663 $allowedoptions = groups_list_to_menu($allowedgroups);
666 if ($useroptions && $allowedoptions) {
667 return array(
668 1 => array(get_string('mygroups', 'group') => $useroptions),
669 2 => array(get_string('othergroups', 'group') => $allowedoptions)
671 } else if ($useroptions) {
672 return $useroptions;
673 } else {
674 return $allowedoptions;
679 * Generates html to print menu selector for course level, listing all groups.
680 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
682 * @param stdclass $course course object.
683 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
684 * @param bool $update set this to true to update current active group based on the group param.
685 * @param int $activegroup Change group active to this group if $update set to true.
687 * @return string html or void
689 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
690 global $SESSION, $OUTPUT, $USER;
692 $groupmode = groups_get_course_groupmode($course);
693 $context = context_course::instance($course->id);
694 $groupsmenu = array();
696 if (has_capability('moodle/site:accessallgroups', $context)) {
697 $groupsmenu[0] = get_string('allparticipants');
698 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
699 } else {
700 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
703 $groupsmenu += groups_list_to_menu($allowedgroups);
705 if ($update) {
706 // Init activegroup array if necessary.
707 if (!isset($SESSION->activegroup)) {
708 $SESSION->activegroup = array();
710 if (!isset($SESSION->activegroup[$course->id])) {
711 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
713 if (empty($groupsmenu[$activegroup])) {
714 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
716 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
719 $grouplabel = get_string('groups');
720 if (count($groupsmenu) == 0) {
721 return '';
722 } else if (count($groupsmenu) == 1) {
723 $groupname = reset($groupsmenu);
724 $output = $grouplabel.': '.$groupname;
725 } else {
726 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
727 $select->label = $grouplabel;
728 $output = $OUTPUT->render($select);
731 return $output;
736 * Print group menu selector for activity.
738 * @category group
739 * @param stdClass|cm_info $cm course module object
740 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
741 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
742 * @param bool $return return as string instead of printing
743 * @param bool $hideallparticipants If true, this prevents the 'All participants'
744 * option from appearing in cases where it normally would. This is intended for
745 * use only by activities that cannot display all groups together. (Note that
746 * selecting this option does not prevent groups_get_activity_group from
747 * returning 0; it will still do that if the user has chosen 'all participants'
748 * in another activity, or not chosen anything.)
749 * @return mixed void or string depending on $return param
751 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
752 global $USER, $OUTPUT;
754 if ($urlroot instanceof moodle_url) {
755 // no changes necessary
757 } else {
758 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
759 // Display error if urlroot is not absolute (this causes the non-JS version to break)
760 debugging('groups_print_activity_menu requires absolute URL for ' .
761 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
762 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
763 DEBUG_DEVELOPER);
765 $urlroot = new moodle_url($urlroot);
768 if (!$groupmode = groups_get_activity_groupmode($cm)) {
769 if ($return) {
770 return '';
771 } else {
772 return;
776 $context = context_module::instance($cm->id);
777 $aag = has_capability('moodle/site:accessallgroups', $context);
779 $usergroups = array();
780 if ($groupmode == VISIBLEGROUPS or $aag) {
781 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid); // any group in grouping
782 // Get user's own groups and put to the top.
783 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
784 } else {
785 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); // only assigned groups
788 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
790 $groupsmenu = array();
791 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
792 $groupsmenu[0] = get_string('allparticipants');
795 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
797 if ($groupmode == VISIBLEGROUPS) {
798 $grouplabel = get_string('groupsvisible');
799 } else {
800 $grouplabel = get_string('groupsseparate');
803 if ($aag and $cm->groupingid) {
804 if ($grouping = groups_get_grouping($cm->groupingid)) {
805 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
809 if (count($groupsmenu) == 1) {
810 $groupname = reset($groupsmenu);
811 $output = $grouplabel.': '.$groupname;
812 } else {
813 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
814 $select->label = $grouplabel;
815 $output = $OUTPUT->render($select);
818 $output = '<div class="groupselector">'.$output.'</div>';
820 if ($return) {
821 return $output;
822 } else {
823 echo $output;
828 * Returns group active in course, changes the group by default if 'group' page param present
830 * @category group
831 * @param stdClass $course course bject
832 * @param bool $update change active group if group param submitted
833 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
834 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
836 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
837 global $USER, $SESSION;
839 if (!$groupmode = $course->groupmode) {
840 // NOGROUPS used
841 return false;
844 $context = context_course::instance($course->id);
845 if (has_capability('moodle/site:accessallgroups', $context)) {
846 $groupmode = 'aag';
849 if (!is_array($allowedgroups)) {
850 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
851 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
852 } else {
853 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
857 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
859 // set new active group if requested
860 $changegroup = optional_param('group', -1, PARAM_INT);
861 if ($update and $changegroup != -1) {
863 if ($changegroup == 0) {
864 // do not allow changing to all groups without accessallgroups capability
865 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
866 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
869 } else {
870 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
871 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
876 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
880 * Returns group active in activity, changes the group by default if 'group' page param present
882 * @category group
883 * @param stdClass|cm_info $cm course module object
884 * @param bool $update change active group if group param submitted
885 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
886 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
888 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
889 global $USER, $SESSION;
891 if (!$groupmode = groups_get_activity_groupmode($cm)) {
892 // NOGROUPS used
893 return false;
896 $context = context_module::instance($cm->id);
897 if (has_capability('moodle/site:accessallgroups', $context)) {
898 $groupmode = 'aag';
901 if (!is_array($allowedgroups)) {
902 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
903 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
904 } else {
905 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
909 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
911 // set new active group if requested
912 $changegroup = optional_param('group', -1, PARAM_INT);
913 if ($update and $changegroup != -1) {
915 if ($changegroup == 0) {
916 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
917 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
918 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
921 } else {
922 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
923 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
928 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
932 * Gets a list of groups that the user is allowed to access within the
933 * specified activity.
935 * @category group
936 * @param stdClass|cm_info $cm Course-module
937 * @param int $userid User ID (defaults to current user)
938 * @return array An array of group objects, or false if none
940 function groups_get_activity_allowed_groups($cm,$userid=0) {
941 // Use current user by default
942 global $USER;
943 if(!$userid) {
944 $userid=$USER->id;
947 // Get groupmode for activity, taking into account course settings
948 $groupmode=groups_get_activity_groupmode($cm);
950 // If visible groups mode, or user has the accessallgroups capability,
951 // then they can access all groups for the activity...
952 $context = context_module::instance($cm->id);
953 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
954 return groups_get_all_groups($cm->course, 0, $cm->groupingid);
955 } else {
956 // ...otherwise they can only access groups they belong to
957 return groups_get_all_groups($cm->course, $userid, $cm->groupingid);
962 * Determine if a given group is visible to user or not in a given context.
964 * @since Moodle 2.6
965 * @param int $groupid Group id to test. 0 for all groups.
966 * @param stdClass $course Course object.
967 * @param stdClass $cm Course module object.
968 * @param int $userid user id to test against. Defaults to $USER.
969 * @return boolean true if visible, false otherwise
971 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
972 global $USER;
974 if (empty($userid)) {
975 $userid = $USER->id;
978 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
979 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
980 // Groups are not used, or everything is visible, no need to go any further.
981 return true;
984 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
985 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
986 // User can see everything. Groupid = 0 is handled here as well.
987 return true;
988 } else if ($groupid != 0) {
989 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
990 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
991 if (array_key_exists($groupid, $groups)) {
992 // User can see the group.
993 return true;
996 return false;
1000 * Get sql and parameters that will return user ids for a group or groups
1002 * @param int|array $groupids Where this is an array of multiple groups, it will match on members of any of the groups
1003 * @param context $context Course context or a context within a course. Mandatory when $groupid = USERSWITHOUTGROUP
1004 * @param int $groupsjointype Join type logic used. Defaults to 'Any' (logical OR).
1005 * @return array($sql, $params)
1006 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1008 function groups_get_members_ids_sql($groupids, context $context = null, $groupsjointype = GROUPS_JOIN_ANY) {
1009 if (!is_array($groupids)) {
1010 $groupids = [$groupids];
1013 $groupjoin = groups_get_members_join($groupids, 'u.id', $context, $groupsjointype);
1015 $sql = "SELECT DISTINCT u.id
1016 FROM {user} u
1017 $groupjoin->joins
1018 WHERE u.deleted = 0";
1019 if (!empty($groupjoin->wheres)) {
1020 $sql .= ' AND '. $groupjoin->wheres;
1023 return array($sql, $groupjoin->params);
1027 * Returns array with SQL and parameters returning userids and concatenated group names for given course
1029 * This function uses 'gn[0-9]+_' prefix for table names and parameters
1031 * @param int $courseid
1032 * @param string $separator
1033 * @return array [$sql, $params]
1035 function groups_get_names_concat_sql(int $courseid, string $separator = ', '): array {
1036 global $DB;
1038 // Use unique prefix just in case somebody makes some SQL magic with the result.
1039 static $i = 0;
1040 $i++;
1041 $prefix = "gn{$i}_";
1043 $groupalias = $prefix . 'g';
1044 $groupmemberalias = $prefix . 'gm';
1045 $groupcourseparam = $prefix . 'courseid';
1047 $sqlgroupconcat = $DB->sql_group_concat("{$groupalias}.name", $separator, "{$groupalias}.name");
1049 $sql = "SELECT {$groupmemberalias}.userid, {$sqlgroupconcat} AS groupnames
1050 FROM {groups} {$groupalias}
1051 JOIN {groups_members} {$groupmemberalias} ON {$groupmemberalias}.groupid = {$groupalias}.id
1052 WHERE {$groupalias}.courseid = :{$groupcourseparam}
1053 GROUP BY {$groupmemberalias}.userid";
1055 return [$sql, [$groupcourseparam => $courseid]];
1059 * Get sql join to return users in a group
1061 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1062 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1063 * @param context $context Course context or a context within a course. Mandatory when $groupids includes USERSWITHOUTGROUP
1064 * @param int $jointype Join type logic used. Defaults to 'Any' (logical OR).
1065 * @return \core\dml\sql_join Contains joins, wheres, params
1066 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1068 function groups_get_members_join($groupids, $useridcolumn, context $context = null, int $jointype = GROUPS_JOIN_ANY) {
1069 global $DB;
1071 // Use unique prefix just in case somebody makes some SQL magic with the result.
1072 static $i = 0;
1073 $i++;
1074 $prefix = 'gm' . $i . '_';
1076 if (!is_array($groupids)) {
1077 $groupids = $groupids ? [$groupids] : [];
1080 $join = '';
1081 $where = '';
1082 $param = [];
1084 $coursecontext = (!empty($context)) ? $context->get_course_context() : null;
1085 if (in_array(USERSWITHOUTGROUP, $groupids) && empty($coursecontext)) {
1086 // Throw an exception if $context is empty or invalid because it's needed to get the users without any group.
1087 throw new coding_exception('Missing or wrong $context parameter in an attempt to get members without any group');
1090 // Handle cases where we need to include/exclude users not in any groups.
1091 if (($nogroupskey = array_search(USERSWITHOUTGROUP, $groupids)) !== false) {
1092 // Get members without any group.
1093 $join .= "LEFT JOIN (
1094 SELECT g.courseid, m.groupid, m.userid
1095 FROM {groups_members} m
1096 JOIN {groups} g ON g.id = m.groupid
1097 ) {$prefix}gm ON ({$prefix}gm.userid = {$useridcolumn} AND {$prefix}gm.courseid = :{$prefix}gcourseid)";
1099 // Join type 'None' when filtering by 'no groups' means match users in at least one group.
1100 if ($jointype == GROUPS_JOIN_NONE) {
1101 $where = "{$prefix}gm.userid IS NOT NULL";
1102 } else {
1103 // All other cases need to match users not in any group.
1104 $where = "{$prefix}gm.userid IS NULL";
1107 $param = ["{$prefix}gcourseid" => $coursecontext->instanceid];
1108 unset($groupids[$nogroupskey]);
1111 // Handle any specified groups that need to be included.
1112 if (!empty($groupids)) {
1113 switch ($jointype) {
1114 case GROUPS_JOIN_ALL:
1115 // Handle matching all of the provided groups (logical AND).
1116 $joinallwheres = [];
1117 $aliaskey = 0;
1118 foreach ($groupids as $groupid) {
1119 $gmalias = "{$prefix}gm{$aliaskey}";
1120 $aliaskey++;
1121 $join .= "LEFT JOIN {groups_members} {$gmalias}
1122 ON ({$gmalias}.userid = {$useridcolumn} AND {$gmalias}.groupid = :{$gmalias}param)";
1123 $joinallwheres[] = "{$gmalias}.userid IS NOT NULL";
1124 $param["{$gmalias}param"] = $groupid;
1127 // Members of all of the specified groups only.
1128 if (empty($where)) {
1129 $where = '(' . implode(' AND ', $joinallwheres) . ')';
1130 } else {
1131 // Members of the specified groups and also no groups.
1132 // NOTE: This will always return no results, because you cannot be in specified groups and also be in no groups.
1133 $where = '(' . $where . ' AND ' . implode(' AND ', $joinallwheres) . ')';
1136 break;
1138 case GROUPS_JOIN_ANY:
1139 // Handle matching any of the provided groups (logical OR).
1140 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1142 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1143 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1144 $param = array_merge($param, $groupsparams);
1146 // Members of any of the specified groups only.
1147 if (empty($where)) {
1148 $where = "{$prefix}gm2.userid IS NOT NULL";
1149 } else {
1150 // Members of any of the specified groups or no groups.
1151 $where = "({$where} OR {$prefix}gm2.userid IS NOT NULL)";
1154 break;
1156 case GROUPS_JOIN_NONE:
1157 // Handle matching none of the provided groups (logical NOT).
1158 list($groupssql, $groupsparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, $prefix);
1160 $join .= "LEFT JOIN {groups_members} {$prefix}gm2
1161 ON ({$prefix}gm2.userid = {$useridcolumn} AND {$prefix}gm2.groupid {$groupssql})";
1162 $param = array_merge($param, $groupsparams);
1164 // Members of none of the specified groups only.
1165 if (empty($where)) {
1166 $where = "{$prefix}gm2.userid IS NULL";
1167 } else {
1168 // Members of any unspecified groups (not a member of the specified groups, and not a member of no groups).
1169 $where = "({$where} AND {$prefix}gm2.userid IS NULL)";
1172 break;
1176 return new \core\dml\sql_join($join, $where, $param);
1180 * Internal method, sets up $SESSION->activegroup and verifies previous value
1182 * @param int $courseid
1183 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1184 * @param int $groupingid 0 means all groups
1185 * @param array $allowedgroups list of groups user can see
1187 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1188 global $SESSION, $USER;
1190 // init activegroup array if necessary
1191 if (!isset($SESSION->activegroup)) {
1192 $SESSION->activegroup = array();
1194 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1195 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1198 // make sure that the current group info is ok
1199 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1200 // active group does not exist anymore or is 0
1201 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1202 // do not do this if all groups selected and groupmode is not separate
1203 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1207 // set up defaults if necessary
1208 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1209 if ($groupmode == 'aag') {
1210 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1212 } else if ($allowedgroups) {
1213 if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
1214 $firstgroup = reset($mygroups);
1215 } else {
1216 $firstgroup = reset($allowedgroups);
1218 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1220 } else {
1221 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1222 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1223 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1229 * Caches group data for a particular course to speed up subsequent requests.
1231 * @param int $courseid The course id to cache data for.
1232 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1233 * @return stdClass A data object containing groups, groupings, and mappings.
1235 function groups_cache_groupdata($courseid, cache $cache = null) {
1236 global $DB;
1238 if ($cache === null) {
1239 // Initialise a cache if we wern't given one.
1240 $cache = cache::make('core', 'groupdata');
1243 // Get the groups that belong to the course.
1244 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1245 // Get the groupings that belong to the course.
1246 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1248 if (!is_array($groups)) {
1249 $groups = array();
1252 if (!is_array($groupings)) {
1253 $groupings = array();
1256 if (!empty($groupings)) {
1257 // Finally get the mappings between the two.
1258 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1259 $mappings = $DB->get_records_sql("
1260 SELECT gg.id, gg.groupingid, gg.groupid
1261 FROM {groupings_groups} gg
1262 JOIN {groups} g ON g.id = gg.groupid
1263 WHERE gg.groupingid $insql
1264 ORDER BY g.name ASC", $params);
1265 } else {
1266 $mappings = array();
1269 // Prepare the data array.
1270 $data = new stdClass;
1271 $data->groups = $groups;
1272 $data->groupings = $groupings;
1273 $data->mappings = $mappings;
1274 // Cache the data.
1275 $cache->set($courseid, $data);
1276 // Finally return it so it can be used if desired.
1277 return $data;
1281 * Gets group data for a course.
1283 * This returns an object with the following properties:
1284 * - groups : An array of all the groups in the course.
1285 * - groupings : An array of all the groupings within the course.
1286 * - mappings : An array of group to grouping mappings.
1288 * @param int $courseid The course id to get data for.
1289 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1290 * @return stdClass
1292 function groups_get_course_data($courseid, cache $cache = null) {
1293 if ($cache === null) {
1294 // Initialise a cache if we wern't given one.
1295 $cache = cache::make('core', 'groupdata');
1297 // Try to retrieve it from the cache.
1298 $data = $cache->get($courseid);
1299 if ($data === false) {
1300 $data = groups_cache_groupdata($courseid, $cache);
1302 return $data;
1306 * Determine if the current user can see at least one of the groups of the specified user.
1308 * @param stdClass $course Course object.
1309 * @param int $userid user id to check against.
1310 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1311 * @return boolean true if visible, false otherwise
1312 * @since Moodle 2.9
1314 function groups_user_groups_visible($course, $userid, $cm = null) {
1315 global $USER;
1317 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1318 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1319 // Groups are not used, or everything is visible, no need to go any further.
1320 return true;
1323 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1324 if (has_capability('moodle/site:accessallgroups', $context)) {
1325 // User can see everything.
1326 return true;
1327 } else {
1328 // Group mode is separate, and user doesn't have access all groups capability.
1329 if (empty($cm)) {
1330 $usergroups = groups_get_all_groups($course->id, $userid);
1331 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1332 } else {
1333 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1334 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1337 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1338 if (!empty($samegroups)) {
1339 // We share groups!
1340 return true;
1343 return false;
1347 * Returns the users in the specified groups.
1349 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1351 * @param array $groupsids The list of groups ids to check
1352 * @param array $extrafields extra fields to be included in result
1353 * @param int $sort optional sorting of returned users
1354 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1355 * @since Moodle 3.3
1357 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1358 global $DB;
1360 $userfieldsapi = \core_user\fields::for_userpic()->including(...($extrafields ?? []));
1361 $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1362 list($insql, $params) = $DB->get_in_or_equal($groupsids);
1364 return $DB->get_records_sql("SELECT $userfields
1365 FROM {user} u, {groups_members} gm
1366 WHERE u.id = gm.userid AND gm.groupid $insql
1367 GROUP BY $userfields
1368 ORDER BY $sort", $params);
1372 * Returns users who share group membership with the specified user in the given actiivty.
1374 * @param stdClass|cm_info $cm course module
1375 * @param int $userid user id (empty for current user)
1376 * @return array a list of user
1377 * @since Moodle 3.3
1379 function groups_get_activity_shared_group_members($cm, $userid = null) {
1380 global $USER;
1382 if (empty($userid)) {
1383 $userid = $USER;
1386 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1387 // No groups no users.
1388 if (empty($groupsids)) {
1389 return [];
1391 return groups_get_groups_members($groupsids);