3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 defined('MOODLE_INTERNAL') ||
die();
27 * Groups not used in course or activity
29 define('NOGROUPS', 0);
32 * Groups used, users do not see other groups
34 define('SEPARATEGROUPS', 1);
37 * Groups used, students see other groups
39 define('VISIBLEGROUPS', 2);
42 * This is for filtering users without any group.
44 define('USERSWITHOUTGROUP', -1);
47 * 'None' join type, used when filtering by groups (logical NOT)
49 define('GROUPS_JOIN_NONE', 0);
52 * 'Any' join type, used when filtering by groups (logical OR)
54 define('GROUPS_JOIN_ANY', 1);
57 * 'All' join type, used when filtering by groups (logical AND)
59 define('GROUPS_JOIN_ALL', 2);
62 * Determines if a group with a given groupid exists.
65 * @param int $groupid The groupid to check for
66 * @return bool True if the group exists, false otherwise or if an error
69 function groups_group_exists($groupid) {
71 return $DB->record_exists('groups', array('id'=>$groupid));
75 * Gets the name of a group with a specified id
77 * Before output, you should call {@see format_string} on the result
80 * @param int $groupid The id of the group
81 * @return string The name of the group
83 function groups_get_group_name($groupid) {
85 return $DB->get_field('groups', 'name', array('id'=>$groupid));
89 * Gets the name of a grouping with a specified id
91 * Before output, you should call {@see format_string} on the result
94 * @param int $groupingid The id of the grouping
95 * @return string The name of the grouping
97 function groups_get_grouping_name($groupingid) {
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
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) {
122 * Returns the groupid of a group with the idnumber specified for the course.
123 * Group idnumbers should be unique within course
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)) {
134 $data = groups_get_course_data($courseid);
135 foreach ($data->groups
as $group) {
136 if ($group->idnumber
== $idnumber) {
144 * Returns the groupingid of a grouping with the name specified for the course.
145 * Grouping names should be unique in course
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
;
163 * Returns the groupingid of a grouping with the idnumber specified for the course.
164 * Grouping names should be unique within course
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)) {
175 $data = groups_get_course_data($courseid);
176 foreach ($data->groupings
as $grouping) {
177 if ($grouping->idnumber
== $idnumber) {
185 * Get the group object
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
) {
196 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
200 * Get the grouping object
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
) {
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).
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) {
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.
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;
241 $fieldbits = explode(',', $fields);
242 foreach ($fieldbits as $bit) {
244 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
245 $knownfields = false;
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
;
260 foreach ($data->mappings
as $mapping) {
261 if ($mapping->groupingid
!= $groupingid) {
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.
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";
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("
300 ORDER BY g.name ASC", $params);
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.
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
;
323 * Gets array of all groups in current user.
327 * @return array Returns an array of the group objects.
329 function groups_get_my_groups() {
331 return $DB->get_records_sql("SELECT *
332 FROM {groups_members} gm
336 ORDER BY name ASC", array($USER->id
));
340 * Returns info about user's groups in course.
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) {
350 if (empty($userid)) {
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
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
)) {
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
;
389 foreach (array_keys($allgroups) as $cid) {
390 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
394 $cache->set($userid, $usergroups);
397 if (array_key_exists($courseid, $usergroups)) {
398 return $usergroups[$courseid];
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).
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.
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) {
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
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)) {
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
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
);
469 // no grouping used - check all groups in course
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.
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') {
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.
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') {
514 return $DB->get_records_sql("SELECT $fields
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
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
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
) {
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.
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
) {
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
);
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');
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;
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>';
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
);
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
650 function groups_sort_menu_options($allowedgroups, $usergroups) {
651 $useroptions = array();
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) {
668 1 => array(get_string('mygroups', 'group') => $useroptions),
669 2 => array(get_string('othergroups', 'group') => $allowedoptions)
671 } else if ($useroptions) {
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
);
700 $allowedgroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
703 $groupsmenu +
= groups_list_to_menu($allowedgroups);
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) {
722 } else if (count($groupsmenu) == 1) {
723 $groupname = reset($groupsmenu);
724 $output = $grouplabel.': '.$groupname;
726 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
727 $select->label
= $grouplabel;
728 $output = $OUTPUT->render($select);
736 * Print group menu selector for activity.
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
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\');',
765 $urlroot = new moodle_url($urlroot);
768 if (!$groupmode = groups_get_activity_groupmode($cm)) {
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
);
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');
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;
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>';
828 * Returns group active in course, changes the group by default if 'group' page param present
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
) {
844 $context = context_course
::instance($course->id
);
845 if (has_capability('moodle/site:accessallgroups', $context)) {
849 if (!is_array($allowedgroups)) {
850 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
851 $allowedgroups = groups_get_all_groups($course->id
, 0, $course->defaultgroupingid
);
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;
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
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)) {
896 $context = context_module
::instance($cm->id
);
897 if (has_capability('moodle/site:accessallgroups', $context)) {
901 if (!is_array($allowedgroups)) {
902 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
903 $allowedgroups = groups_get_all_groups($cm->course
, 0, $cm->groupingid
);
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;
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.
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
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
);
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.
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) {
974 if (empty($userid)) {
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.
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.
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.
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
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 {
1038 // Use unique prefix just in case somebody makes some SQL magic with the result.
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
) {
1071 // Use unique prefix just in case somebody makes some SQL magic with the result.
1074 $prefix = 'gm' . $i . '_';
1076 if (!is_array($groupids)) {
1077 $groupids = $groupids ?
[$groupids] : [];
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";
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 = [];
1118 foreach ($groupids as $groupid) {
1119 $gmalias = "{$prefix}gm{$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) . ')';
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) . ')';
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";
1150 // Members of any of the specified groups or no groups.
1151 $where = "({$where} OR {$prefix}gm2.userid IS NOT NULL)";
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";
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)";
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);
1216 $firstgroup = reset($allowedgroups);
1218 $SESSION->activegroup
[$courseid][$groupmode][$groupingid] = $firstgroup->id
;
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) {
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)) {
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);
1266 $mappings = array();
1269 // Prepare the data array.
1270 $data = new stdClass
;
1271 $data->groups
= $groups;
1272 $data->groupings
= $groupings;
1273 $data->mappings
= $mappings;
1275 $cache->set($courseid, $data);
1276 // Finally return it so it can be used if desired.
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.
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);
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
1314 function groups_user_groups_visible($course, $userid, $cm = null) {
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.
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.
1328 // Group mode is separate, and user doesn't have access all groups capability.
1330 $usergroups = groups_get_all_groups($course->id
, $userid);
1331 $currentusergroups = groups_get_all_groups($course->id
, $USER->id
);
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)) {
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.
1357 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
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
1379 function groups_get_activity_shared_group_members($cm, $userid = null) {
1382 if (empty($userid)) {
1386 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1387 // No groups no users.
1388 if (empty($groupsids)) {
1391 return groups_get_groups_members($groupsids);