MDL-58596 core_stats: unit test for stats_get_base_weekly
[moodle.git] / lib / grouplib.php
blob687eef1b54ffe1a0a6650c39db20a2aee3f5cf26
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.
198 * @category group
199 * @param int $courseid The id of the course.
200 * @param mixed $userid optional user id or array of ids, returns only groups of the user.
201 * @param int $groupingid optional returns only groups in the specified grouping.
202 * @param string $fields
203 * @param bool $withmembers If true - this will return an extra field which is the list of userids that
204 * are members of this group.
205 * @return array Returns an array of the group objects (userid field returned if array in $userid)
207 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false) {
208 global $DB;
210 // We need to check that we each field in the fields list belongs to the group table and that it has not being
211 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
212 $knownfields = true;
213 if ($fields !== 'g.*') {
214 // Quickly check if the first field is no longer g.id as using the
215 // cache will return an array indexed differently than when expect
216 if (strpos($fields, 'g.*') !== 0 && strpos($fields, 'g.id') !== 0) {
217 $knownfields = false;
218 } else {
219 $fieldbits = explode(',', $fields);
220 foreach ($fieldbits as $bit) {
221 $bit = trim($bit);
222 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
223 $knownfields = false;
224 break;
230 if (empty($userid) && $knownfields && !$withmembers) {
231 // We can use the cache.
232 $data = groups_get_course_data($courseid);
233 if (empty($groupingid)) {
234 // All groups.. Easy!
235 $groups = $data->groups;
236 } else {
237 $groups = array();
238 foreach ($data->mappings as $mapping) {
239 if ($mapping->groupingid != $groupingid) {
240 continue;
242 if (isset($data->groups[$mapping->groupid])) {
243 $groups[$mapping->groupid] = $data->groups[$mapping->groupid];
247 // Yay! We could use the cache. One more query saved.
248 return $groups;
250 $memberselect = '';
251 $memberjoin = '';
253 if (empty($userid)) {
254 $userfrom = "";
255 $userwhere = "";
256 $params = array();
257 } else {
258 list($usql, $params) = $DB->get_in_or_equal($userid);
259 $userfrom = ", {groups_members} gm";
260 $userwhere = "AND g.id = gm.groupid AND gm.userid $usql";
263 if (!empty($groupingid)) {
264 $groupingfrom = ", {groupings_groups} gg";
265 $groupingwhere = "AND g.id = gg.groupid AND gg.groupingid = ?";
266 $params[] = $groupingid;
267 } else {
268 $groupingfrom = "";
269 $groupingwhere = "";
272 if ($withmembers) {
273 $memberselect = $DB->sql_concat("COALESCE(ugm.userid, 0)", "':'", 'g.id') . ' AS ugmid, ugm.userid, ';
274 $memberjoin = ' LEFT JOIN {groups_members} ugm ON ugm.groupid = g.id ';
277 array_unshift($params, $courseid);
279 $results = $DB->get_records_sql("SELECT $memberselect $fields
280 FROM {groups} g $userfrom $groupingfrom $memberjoin
281 WHERE g.courseid = ? $userwhere $groupingwhere
282 ORDER BY name ASC", $params);
284 if ($withmembers) {
285 // We need to post-process the results back into standard format.
286 $groups = [];
287 foreach ($results as $row) {
288 if (!isset($groups[$row->id])) {
289 $row->members = [$row->userid => $row->userid];
290 unset($row->userid);
291 unset($row->ugmid);
292 $groups[$row->id] = $row;
293 } else {
294 $groups[$row->id]->members[$row->userid] = $row->userid;
297 $results = $groups;
300 return $results;
304 * Gets array of all groups in current user.
306 * @since Moodle 2.5
307 * @category group
308 * @return array Returns an array of the group objects.
310 function groups_get_my_groups() {
311 global $DB, $USER;
312 return $DB->get_records_sql("SELECT *
313 FROM {groups_members} gm
314 JOIN {groups} g
315 ON g.id = gm.groupid
316 WHERE gm.userid = ?
317 ORDER BY name ASC", array($USER->id));
321 * Returns info about user's groups in course.
323 * @category group
324 * @param int $courseid
325 * @param int $userid $USER if not specified
326 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
328 function groups_get_user_groups($courseid, $userid=0) {
329 global $USER, $DB;
331 if (empty($userid)) {
332 $userid = $USER->id;
335 $cache = cache::make('core', 'user_group_groupings');
337 // Try to retrieve group ids from the cache.
338 $usergroups = $cache->get($userid);
340 if ($usergroups === false) {
341 $sql = "SELECT g.id, g.courseid, gg.groupingid
342 FROM {groups} g
343 JOIN {groups_members} gm ON gm.groupid = g.id
344 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
345 WHERE gm.userid = ?";
347 $rs = $DB->get_recordset_sql($sql, array($userid));
349 $usergroups = array();
350 $allgroups = array();
352 foreach ($rs as $group) {
353 if (!array_key_exists($group->courseid, $allgroups)) {
354 $allgroups[$group->courseid] = array();
356 $allgroups[$group->courseid][$group->id] = $group->id;
357 if (!array_key_exists($group->courseid, $usergroups)) {
358 $usergroups[$group->courseid] = array();
360 if (is_null($group->groupingid)) {
361 continue;
363 if (!array_key_exists($group->groupingid, $usergroups[$group->courseid])) {
364 $usergroups[$group->courseid][$group->groupingid] = array();
366 $usergroups[$group->courseid][$group->groupingid][$group->id] = $group->id;
368 $rs->close();
370 foreach (array_keys($allgroups) as $cid) {
371 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
374 // Cache the data.
375 $cache->set($userid, $usergroups);
378 if (array_key_exists($courseid, $usergroups)) {
379 return $usergroups[$courseid];
380 } else {
381 return array('0' => array());
386 * Gets an array of all groupings in a specified course. This value is cached
387 * for a single course (so you can call it repeatedly for the same course
388 * without a performance penalty).
390 * @category group
391 * @param int $courseid return all groupings from course with this courseid
392 * @return array Returns an array of the grouping objects (empty if none)
394 function groups_get_all_groupings($courseid) {
395 $data = groups_get_course_data($courseid);
396 return $data->groupings;
400 * Determines if the user is a member of the given group.
402 * If $userid is null, use the global object.
404 * @category group
405 * @param int $groupid The group to check for membership.
406 * @param int $userid The user to check against the group.
407 * @return bool True if the user is a member, false otherwise.
409 function groups_is_member($groupid, $userid=null) {
410 global $USER, $DB;
412 if (!$userid) {
413 $userid = $USER->id;
416 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
420 * Determines if current or specified is member of any active group in activity
422 * @category group
423 * @staticvar array $cache
424 * @param stdClass|cm_info $cm course module object
425 * @param int $userid id of user, null means $USER->id
426 * @return bool true if user member of at least one group used in activity
428 function groups_has_membership($cm, $userid=null) {
429 global $CFG, $USER, $DB;
431 static $cache = array();
433 if (empty($userid)) {
434 $userid = $USER->id;
437 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
438 if (isset($cache[$cachekey])) {
439 return($cache[$cachekey]);
442 if ($cm->groupingid) {
443 // find out if member of any group in selected activity grouping
444 $sql = "SELECT 'x'
445 FROM {groups_members} gm, {groupings_groups} gg
446 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
447 $params = array($userid, $cm->groupingid);
449 } else {
450 // no grouping used - check all groups in course
451 $sql = "SELECT 'x'
452 FROM {groups_members} gm, {groups} g
453 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
454 $params = array($userid, $cm->course);
457 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
459 return $cache[$cachekey];
463 * Returns the users in the specified group.
465 * @category group
466 * @param int $groupid The groupid to get the users for
467 * @param int $fields The fields to return
468 * @param int $sort optional sorting of returned users
469 * @return array|bool Returns an array of the users for the specified
470 * group or false if no users or an error returned.
472 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
473 global $DB;
475 return $DB->get_records_sql("SELECT $fields
476 FROM {user} u, {groups_members} gm
477 WHERE u.id = gm.userid AND gm.groupid = ?
478 ORDER BY $sort", array($groupid));
483 * Returns the users in the specified grouping.
485 * @category group
486 * @param int $groupingid The groupingid to get the users for
487 * @param string $fields The fields to return
488 * @param string $sort optional sorting of returned users
489 * @return array|bool Returns an array of the users for the specified
490 * group or false if no users or an error returned.
492 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
493 global $DB;
495 return $DB->get_records_sql("SELECT $fields
496 FROM {user} u
497 INNER JOIN {groups_members} gm ON u.id = gm.userid
498 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
499 WHERE gg.groupingid = ?
500 ORDER BY $sort", array($groupingid));
504 * Returns effective groupmode used in course
506 * @category group
507 * @param stdClass $course course object.
508 * @return int group mode
510 function groups_get_course_groupmode($course) {
511 return $course->groupmode;
515 * Returns effective groupmode used in activity, course setting
516 * overrides activity setting if groupmodeforce enabled.
518 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
520 * @category group
521 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
522 * @param stdClass $course object optional course object to improve perf
523 * @return int group mode
525 function groups_get_activity_groupmode($cm, $course=null) {
526 if ($cm instanceof cm_info) {
527 return $cm->effectivegroupmode;
529 if (isset($course->id) and $course->id == $cm->course) {
530 //ok
531 } else {
532 // Get course object (reuse $COURSE if possible).
533 $course = get_course($cm->course, false);
536 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
540 * Print group menu selector for course level.
542 * @category group
543 * @param stdClass $course course object
544 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
545 * @param bool $return return as string instead of printing
546 * @return mixed void or string depending on $return param
548 function groups_print_course_menu($course, $urlroot, $return=false) {
549 global $USER, $OUTPUT;
551 if (!$groupmode = $course->groupmode) {
552 if ($return) {
553 return '';
554 } else {
555 return;
559 $context = context_course::instance($course->id);
560 $aag = has_capability('moodle/site:accessallgroups', $context);
562 $usergroups = array();
563 if ($groupmode == VISIBLEGROUPS or $aag) {
564 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
565 // Get user's own groups and put to the top.
566 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
567 } else {
568 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
571 $activegroup = groups_get_course_group($course, true, $allowedgroups);
573 $groupsmenu = array();
574 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
575 $groupsmenu[0] = get_string('allparticipants');
578 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
580 if ($groupmode == VISIBLEGROUPS) {
581 $grouplabel = get_string('groupsvisible');
582 } else {
583 $grouplabel = get_string('groupsseparate');
586 if ($aag and $course->defaultgroupingid) {
587 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
588 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
592 if (count($groupsmenu) == 1) {
593 $groupname = reset($groupsmenu);
594 $output = $grouplabel.': '.$groupname;
595 } else {
596 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
597 $select->label = $grouplabel;
598 $output = $OUTPUT->render($select);
601 $output = '<div class="groupselector">'.$output.'</div>';
603 if ($return) {
604 return $output;
605 } else {
606 echo $output;
611 * Turn an array of groups into an array of menu options.
612 * @param array $groups of group objects.
613 * @return array groupid => formatted group name.
615 function groups_list_to_menu($groups) {
616 $groupsmenu = array();
617 foreach ($groups as $group) {
618 $groupsmenu[$group->id] = format_string($group->name);
620 return $groupsmenu;
624 * Takes user's allowed groups and own groups and formats for use in group selector menu
625 * If user has allowed groups + own groups will add to an optgroup
626 * Own groups are removed from allowed groups
627 * @param array $allowedgroups All groups user is allowed to see
628 * @param array $usergroups Groups user belongs to
629 * @return array
631 function groups_sort_menu_options($allowedgroups, $usergroups) {
632 $useroptions = array();
633 if ($usergroups) {
634 $useroptions = groups_list_to_menu($usergroups);
636 // Remove user groups from other groups list.
637 foreach ($usergroups as $group) {
638 unset($allowedgroups[$group->id]);
642 $allowedoptions = array();
643 if ($allowedgroups) {
644 $allowedoptions = groups_list_to_menu($allowedgroups);
647 if ($useroptions && $allowedoptions) {
648 return array(
649 1 => array(get_string('mygroups', 'group') => $useroptions),
650 2 => array(get_string('othergroups', 'group') => $allowedoptions)
652 } else if ($useroptions) {
653 return $useroptions;
654 } else {
655 return $allowedoptions;
660 * Generates html to print menu selector for course level, listing all groups.
661 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
663 * @param stdclass $course course object.
664 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
665 * @param bool $update set this to true to update current active group based on the group param.
666 * @param int $activegroup Change group active to this group if $update set to true.
668 * @return string html or void
670 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
671 global $SESSION, $OUTPUT, $USER;
673 $groupmode = groups_get_course_groupmode($course);
674 $context = context_course::instance($course->id);
675 $groupsmenu = array();
677 if (has_capability('moodle/site:accessallgroups', $context)) {
678 $groupsmenu[0] = get_string('allparticipants');
679 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
680 } else {
681 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
684 $groupsmenu += groups_list_to_menu($allowedgroups);
686 if ($update) {
687 // Init activegroup array if necessary.
688 if (!isset($SESSION->activegroup)) {
689 $SESSION->activegroup = array();
691 if (!isset($SESSION->activegroup[$course->id])) {
692 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
694 if (empty($groupsmenu[$activegroup])) {
695 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
697 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
700 $grouplabel = get_string('groups');
701 if (count($groupsmenu) == 0) {
702 return '';
703 } else if (count($groupsmenu) == 1) {
704 $groupname = reset($groupsmenu);
705 $output = $grouplabel.': '.$groupname;
706 } else {
707 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
708 $select->label = $grouplabel;
709 $output = $OUTPUT->render($select);
712 return $output;
717 * Print group menu selector for activity.
719 * @category group
720 * @param stdClass|cm_info $cm course module object
721 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
722 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
723 * @param bool $return return as string instead of printing
724 * @param bool $hideallparticipants If true, this prevents the 'All participants'
725 * option from appearing in cases where it normally would. This is intended for
726 * use only by activities that cannot display all groups together. (Note that
727 * selecting this option does not prevent groups_get_activity_group from
728 * returning 0; it will still do that if the user has chosen 'all participants'
729 * in another activity, or not chosen anything.)
730 * @return mixed void or string depending on $return param
732 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
733 global $USER, $OUTPUT;
735 if ($urlroot instanceof moodle_url) {
736 // no changes necessary
738 } else {
739 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
740 // Display error if urlroot is not absolute (this causes the non-JS version to break)
741 debugging('groups_print_activity_menu requires absolute URL for ' .
742 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
743 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
744 DEBUG_DEVELOPER);
746 $urlroot = new moodle_url($urlroot);
749 if (!$groupmode = groups_get_activity_groupmode($cm)) {
750 if ($return) {
751 return '';
752 } else {
753 return;
757 $context = context_module::instance($cm->id);
758 $aag = has_capability('moodle/site:accessallgroups', $context);
760 $usergroups = array();
761 if ($groupmode == VISIBLEGROUPS or $aag) {
762 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid); // any group in grouping
763 // Get user's own groups and put to the top.
764 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
765 } else {
766 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); // only assigned groups
769 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
771 $groupsmenu = array();
772 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
773 $groupsmenu[0] = get_string('allparticipants');
776 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
778 if ($groupmode == VISIBLEGROUPS) {
779 $grouplabel = get_string('groupsvisible');
780 } else {
781 $grouplabel = get_string('groupsseparate');
784 if ($aag and $cm->groupingid) {
785 if ($grouping = groups_get_grouping($cm->groupingid)) {
786 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
790 if (count($groupsmenu) == 1) {
791 $groupname = reset($groupsmenu);
792 $output = $grouplabel.': '.$groupname;
793 } else {
794 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
795 $select->label = $grouplabel;
796 $output = $OUTPUT->render($select);
799 $output = '<div class="groupselector">'.$output.'</div>';
801 if ($return) {
802 return $output;
803 } else {
804 echo $output;
809 * Returns group active in course, changes the group by default if 'group' page param present
811 * @category group
812 * @param stdClass $course course bject
813 * @param bool $update change active group if group param submitted
814 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
815 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
817 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
818 global $USER, $SESSION;
820 if (!$groupmode = $course->groupmode) {
821 // NOGROUPS used
822 return false;
825 $context = context_course::instance($course->id);
826 if (has_capability('moodle/site:accessallgroups', $context)) {
827 $groupmode = 'aag';
830 if (!is_array($allowedgroups)) {
831 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
832 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
833 } else {
834 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
838 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
840 // set new active group if requested
841 $changegroup = optional_param('group', -1, PARAM_INT);
842 if ($update and $changegroup != -1) {
844 if ($changegroup == 0) {
845 // do not allow changing to all groups without accessallgroups capability
846 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
847 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
850 } else {
851 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
852 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
857 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
861 * Returns group active in activity, changes the group by default if 'group' page param present
863 * @category group
864 * @param stdClass|cm_info $cm course module object
865 * @param bool $update change active group if group param submitted
866 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
867 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
869 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
870 global $USER, $SESSION;
872 if (!$groupmode = groups_get_activity_groupmode($cm)) {
873 // NOGROUPS used
874 return false;
877 $context = context_module::instance($cm->id);
878 if (has_capability('moodle/site:accessallgroups', $context)) {
879 $groupmode = 'aag';
882 if (!is_array($allowedgroups)) {
883 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
884 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
885 } else {
886 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
890 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
892 // set new active group if requested
893 $changegroup = optional_param('group', -1, PARAM_INT);
894 if ($update and $changegroup != -1) {
896 if ($changegroup == 0) {
897 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
898 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
899 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
902 } else {
903 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
904 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
909 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
913 * Gets a list of groups that the user is allowed to access within the
914 * specified activity.
916 * @category group
917 * @param stdClass|cm_info $cm Course-module
918 * @param int $userid User ID (defaults to current user)
919 * @return array An array of group objects, or false if none
921 function groups_get_activity_allowed_groups($cm,$userid=0) {
922 // Use current user by default
923 global $USER;
924 if(!$userid) {
925 $userid=$USER->id;
928 // Get groupmode for activity, taking into account course settings
929 $groupmode=groups_get_activity_groupmode($cm);
931 // If visible groups mode, or user has the accessallgroups capability,
932 // then they can access all groups for the activity...
933 $context = context_module::instance($cm->id);
934 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
935 return groups_get_all_groups($cm->course, 0, $cm->groupingid);
936 } else {
937 // ...otherwise they can only access groups they belong to
938 return groups_get_all_groups($cm->course, $userid, $cm->groupingid);
943 * Determine if a given group is visible to user or not in a given context.
945 * @since Moodle 2.6
946 * @param int $groupid Group id to test. 0 for all groups.
947 * @param stdClass $course Course object.
948 * @param stdClass $cm Course module object.
949 * @param int $userid user id to test against. Defaults to $USER.
950 * @return boolean true if visible, false otherwise
952 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
953 global $USER;
955 if (empty($userid)) {
956 $userid = $USER->id;
959 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
960 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
961 // Groups are not used, or everything is visible, no need to go any further.
962 return true;
965 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
966 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
967 // User can see everything. Groupid = 0 is handled here as well.
968 return true;
969 } else if ($groupid != 0) {
970 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
971 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
972 if (array_key_exists($groupid, $groups)) {
973 // User can see the group.
974 return true;
977 return false;
981 * Get sql and parameters that will return user ids for a group
983 * @param int $groupid
984 * @param context $context Course context or a context within a course. Mandatory when $groupid = USERSWITHOUTGROUP
985 * @return array($sql, $params)
986 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
988 function groups_get_members_ids_sql($groupid, context $context = null) {
989 $groupjoin = groups_get_members_join($groupid, 'u.id', $context);
991 $sql = "SELECT DISTINCT u.id
992 FROM {user} u
993 $groupjoin->joins
994 WHERE u.deleted = 0";
995 if (!empty($groupjoin->wheres)) {
996 $sql .= ' AND '. $groupjoin->wheres;
999 return array($sql, $groupjoin->params);
1003 * Get sql join to return users in a group
1005 * @param int $groupid The groupid, 0 means all groups and USERSWITHOUTGROUP no group
1006 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1007 * @param context $context Course context or a context within a course. Mandatory when $groupid = USERSWITHOUTGROUP
1008 * @return \core\dml\sql_join Contains joins, wheres, params
1009 * @throws coding_exception if empty or invalid context submitted when $groupid = USERSWITHOUTGROUP
1011 function groups_get_members_join($groupid, $useridcolumn, context $context = null) {
1012 // Use unique prefix just in case somebody makes some SQL magic with the result.
1013 static $i = 0;
1014 $i++;
1015 $prefix = 'gm' . $i . '_';
1017 $coursecontext = (!empty($context)) ? $context->get_course_context() : null;
1018 if ($groupid == USERSWITHOUTGROUP && empty($coursecontext)) {
1019 // Throw an exception if $context is empty or invalid because it's needed to get the users without any group.
1020 throw new coding_exception('Missing or wrong $context parameter in an attempt to get members without any group');
1023 if ($groupid == USERSWITHOUTGROUP) {
1024 // Get members without any group.
1025 $join = "LEFT JOIN (
1026 SELECT g.courseid, m.groupid, m.userid
1027 FROM {groups_members} m
1028 JOIN {groups} g ON g.id = m.groupid
1029 ) {$prefix}gm ON ({$prefix}gm.userid = $useridcolumn AND {$prefix}gm.courseid = :{$prefix}gcourseid)";
1030 $where = "{$prefix}gm.userid IS NULL";
1031 $param = array("{$prefix}gcourseid" => $coursecontext->instanceid);
1032 } else {
1033 // Get members of defined groupid.
1034 $join = "JOIN {groups_members} {$prefix}gm
1035 ON ({$prefix}gm.userid = $useridcolumn AND {$prefix}gm.groupid = :{$prefix}gmid)";
1036 $where = '';
1037 $param = array("{$prefix}gmid" => $groupid);
1040 return new \core\dml\sql_join($join, $where, $param);
1044 * Internal method, sets up $SESSION->activegroup and verifies previous value
1046 * @param int $courseid
1047 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1048 * @param int $groupingid 0 means all groups
1049 * @param array $allowedgroups list of groups user can see
1051 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1052 global $SESSION, $USER;
1054 // init activegroup array if necessary
1055 if (!isset($SESSION->activegroup)) {
1056 $SESSION->activegroup = array();
1058 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1059 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1062 // make sure that the current group info is ok
1063 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1064 // active group does not exist anymore or is 0
1065 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1066 // do not do this if all groups selected and groupmode is not separate
1067 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1071 // set up defaults if necessary
1072 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1073 if ($groupmode == 'aag') {
1074 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1076 } else if ($allowedgroups) {
1077 if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
1078 $firstgroup = reset($mygroups);
1079 } else {
1080 $firstgroup = reset($allowedgroups);
1082 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1084 } else {
1085 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1086 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1087 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1093 * Caches group data for a particular course to speed up subsequent requests.
1095 * @param int $courseid The course id to cache data for.
1096 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1097 * @return stdClass A data object containing groups, groupings, and mappings.
1099 function groups_cache_groupdata($courseid, cache $cache = null) {
1100 global $DB;
1102 if ($cache === null) {
1103 // Initialise a cache if we wern't given one.
1104 $cache = cache::make('core', 'groupdata');
1107 // Get the groups that belong to the course.
1108 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1109 // Get the groupings that belong to the course.
1110 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1112 if (!is_array($groups)) {
1113 $groups = array();
1116 if (!is_array($groupings)) {
1117 $groupings = array();
1120 if (!empty($groupings)) {
1121 // Finally get the mappings between the two.
1122 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1123 $mappings = $DB->get_records_sql("
1124 SELECT gg.id, gg.groupingid, gg.groupid
1125 FROM {groupings_groups} gg
1126 JOIN {groups} g ON g.id = gg.groupid
1127 WHERE gg.groupingid $insql
1128 ORDER BY g.name ASC", $params);
1129 } else {
1130 $mappings = array();
1133 // Prepare the data array.
1134 $data = new stdClass;
1135 $data->groups = $groups;
1136 $data->groupings = $groupings;
1137 $data->mappings = $mappings;
1138 // Cache the data.
1139 $cache->set($courseid, $data);
1140 // Finally return it so it can be used if desired.
1141 return $data;
1145 * Gets group data for a course.
1147 * This returns an object with the following properties:
1148 * - groups : An array of all the groups in the course.
1149 * - groupings : An array of all the groupings within the course.
1150 * - mappings : An array of group to grouping mappings.
1152 * @param int $courseid The course id to get data for.
1153 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1154 * @return stdClass
1156 function groups_get_course_data($courseid, cache $cache = null) {
1157 if ($cache === null) {
1158 // Initialise a cache if we wern't given one.
1159 $cache = cache::make('core', 'groupdata');
1161 // Try to retrieve it from the cache.
1162 $data = $cache->get($courseid);
1163 if ($data === false) {
1164 $data = groups_cache_groupdata($courseid, $cache);
1166 return $data;
1170 * Determine if the current user can see at least one of the groups of the specified user.
1172 * @param stdClass $course Course object.
1173 * @param int $userid user id to check against.
1174 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1175 * @return boolean true if visible, false otherwise
1176 * @since Moodle 2.9
1178 function groups_user_groups_visible($course, $userid, $cm = null) {
1179 global $USER;
1181 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1182 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1183 // Groups are not used, or everything is visible, no need to go any further.
1184 return true;
1187 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1188 if (has_capability('moodle/site:accessallgroups', $context)) {
1189 // User can see everything.
1190 return true;
1191 } else {
1192 // Group mode is separate, and user doesn't have access all groups capability.
1193 if (empty($cm)) {
1194 $usergroups = groups_get_all_groups($course->id, $userid);
1195 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1196 } else {
1197 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1198 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1201 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1202 if (!empty($samegroups)) {
1203 // We share groups!
1204 return true;
1207 return false;
1211 * Returns the users in the specified groups.
1213 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1215 * @param array $groupsids The list of groups ids to check
1216 * @param array $extrafields extra fields to be included in result
1217 * @param int $sort optional sorting of returned users
1218 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1219 * @since Moodle 3.3
1221 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1222 global $DB;
1224 $userfields = user_picture::fields('u', $extrafields);
1225 list($insql, $params) = $DB->get_in_or_equal($groupsids);
1227 return $DB->get_records_sql("SELECT $userfields
1228 FROM {user} u, {groups_members} gm
1229 WHERE u.id = gm.userid AND gm.groupid $insql
1230 GROUP BY $userfields
1231 ORDER BY $sort", $params);
1235 * Returns users who share group membership with the specified user in the given actiivty.
1237 * @param stdClass|cm_info $cm course module
1238 * @param int $userid user id (empty for current user)
1239 * @return array a list of user
1240 * @since Moodle 3.3
1242 function groups_get_activity_shared_group_members($cm, $userid = null) {
1243 global $USER;
1245 if (empty($userid)) {
1246 $userid = $USER;
1249 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1250 // No groups no users.
1251 if (empty($groupsids)) {
1252 return [];
1254 return groups_get_groups_members($groupsids);