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);
43 * Determines if a group with a given groupid exists.
46 * @param int $groupid The groupid to check for
47 * @return bool True if the group exists, false otherwise or if an error
50 function groups_group_exists($groupid) {
52 return $DB->record_exists('groups', array('id'=>$groupid));
56 * Gets the name of a group with a specified id
59 * @param int $groupid The id of the group
60 * @return string The name of the group
62 function groups_get_group_name($groupid) {
64 return $DB->get_field('groups', 'name', array('id'=>$groupid));
68 * Gets the name of a grouping with a specified id
71 * @param int $groupingid The id of the grouping
72 * @return string The name of the grouping
74 function groups_get_grouping_name($groupingid) {
76 return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
80 * Returns the groupid of a group with the name specified for the course.
81 * Group names should be unique in course
84 * @param int $courseid The id of the course
85 * @param string $name name of group (without magic quotes)
86 * @return int $groupid
88 function groups_get_group_by_name($courseid, $name) {
89 $data = groups_get_course_data($courseid);
90 foreach ($data->groups
as $group) {
91 if ($group->name
== $name) {
99 * Returns the groupid of a group with the idnumber specified for the course.
100 * Group idnumbers should be unique within course
103 * @param int $courseid The id of the course
104 * @param string $idnumber idnumber of group
105 * @return group object
107 function groups_get_group_by_idnumber($courseid, $idnumber) {
108 if (empty($idnumber)) {
111 $data = groups_get_course_data($courseid);
112 foreach ($data->groups
as $group) {
113 if ($group->idnumber
== $idnumber) {
121 * Returns the groupingid of a grouping with the name specified for the course.
122 * Grouping names should be unique in course
125 * @param int $courseid The id of the course
126 * @param string $name name of group (without magic quotes)
127 * @return int $groupid
129 function groups_get_grouping_by_name($courseid, $name) {
130 $data = groups_get_course_data($courseid);
131 foreach ($data->groupings
as $grouping) {
132 if ($grouping->name
== $name) {
133 return $grouping->id
;
140 * Returns the groupingid of a grouping with the idnumber specified for the course.
141 * Grouping names should be unique within course
144 * @param int $courseid The id of the course
145 * @param string $idnumber idnumber of the group
146 * @return grouping object
148 function groups_get_grouping_by_idnumber($courseid, $idnumber) {
149 if (empty($idnumber)) {
152 $data = groups_get_course_data($courseid);
153 foreach ($data->groupings
as $grouping) {
154 if ($grouping->idnumber
== $idnumber) {
162 * Get the group object
165 * @param int $groupid ID of the group.
166 * @param string $fields (default is all fields)
167 * @param int $strictness (IGNORE_MISSING - default)
168 * @return stdGlass group object
170 function groups_get_group($groupid, $fields='*', $strictness=IGNORE_MISSING
) {
172 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
176 * Get the grouping object
179 * @param int $groupingid ID of the group.
180 * @param string $fields
181 * @param int $strictness (IGNORE_MISSING - default)
182 * @return stdClass group object
184 function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING
) {
186 return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
190 * Gets array of all groups in a specified course.
193 * @param int $courseid The id of the course.
194 * @param mixed $userid optional user id or array of ids, returns only groups of the user.
195 * @param int $groupingid optional returns only groups in the specified grouping.
196 * @param string $fields
197 * @param bool $withmembers If true - this will return an extra field which is the list of userids that
198 * are members of this group.
199 * @return array Returns an array of the group objects (userid field returned if array in $userid)
201 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false) {
204 // We need to check that we each field in the fields list belongs to the group table and that it has not being
205 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
207 if ($fields !== 'g.*') {
208 // Quickly check if the first field is no longer g.id as using the
209 // cache will return an array indexed differently than when expect
210 if (strpos($fields, 'g.*') !== 0 && strpos($fields, 'g.id') !== 0) {
211 $knownfields = false;
213 $fieldbits = explode(',', $fields);
214 foreach ($fieldbits as $bit) {
216 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
217 $knownfields = false;
224 if (empty($userid) && $knownfields && !$withmembers) {
225 // We can use the cache.
226 $data = groups_get_course_data($courseid);
227 if (empty($groupingid)) {
228 // All groups.. Easy!
229 $groups = $data->groups
;
232 foreach ($data->mappings
as $mapping) {
233 if ($mapping->groupingid
!= $groupingid) {
236 if (isset($data->groups
[$mapping->groupid
])) {
237 $groups[$mapping->groupid
] = $data->groups
[$mapping->groupid
];
241 // Yay! We could use the cache. One more query saved.
247 if (empty($userid)) {
252 list($usql, $params) = $DB->get_in_or_equal($userid);
253 $userfrom = ", {groups_members} gm";
254 $userwhere = "AND g.id = gm.groupid AND gm.userid $usql";
257 if (!empty($groupingid)) {
258 $groupingfrom = ", {groupings_groups} gg";
259 $groupingwhere = "AND g.id = gg.groupid AND gg.groupingid = ?";
260 $params[] = $groupingid;
267 $memberselect = $DB->sql_concat("COALESCE(ugm.userid, 0)", "':'", 'g.id') . ' AS ugmid, ugm.userid, ';
268 $memberjoin = ' LEFT JOIN {groups_members} ugm ON ugm.groupid = g.id ';
271 array_unshift($params, $courseid);
273 $results = $DB->get_records_sql("SELECT $memberselect $fields
274 FROM {groups} g $userfrom $groupingfrom $memberjoin
275 WHERE g.courseid = ? $userwhere $groupingwhere
276 ORDER BY name ASC", $params);
279 // We need to post-process the results back into standard format.
281 foreach ($results as $row) {
282 if (!isset($groups[$row->id
])) {
283 $row->members
= [$row->userid
=> $row->userid
];
286 $groups[$row->id
] = $row;
288 $groups[$row->id
]->members
[$row->userid
] = $row->userid
;
298 * Gets array of all groups in a set of course.
301 * @param array $courses Array of course objects or course ids.
302 * @return array Array of groups indexed by course id.
304 function groups_get_all_groups_for_courses($courses) {
307 if (empty($courses)) {
314 foreach ($courses as $course) {
315 $courseid = is_object($course) ?
$course->id
: $course;
316 $groups[$courseid] = [];
317 $courseids[] = $courseid;
326 'g.descriptionformat',
334 $groupsmembersfields = [
343 $concatidsql = $DB->sql_concat_join("'-'", ['g.id', 'COALESCE(gm.id, 0)']) . ' AS uniqid';
344 list($courseidsql, $params) = $DB->get_in_or_equal($courseids);
345 $groupfieldssql = implode(',', $groupfields);
346 $groupmembersfieldssql = implode(',', $groupsmembersfields);
347 $sql = "SELECT {$concatidsql}, {$groupfieldssql}, {$groupmembersfieldssql}
349 LEFT JOIN {groups_members} gm
351 WHERE g.courseid {$courseidsql}";
353 $results = $DB->get_records_sql($sql, $params);
355 // The results will come back as a flat dataset thanks to the left
356 // join so we will need to do some post processing to blow it out
357 // into a more usable data structure.
359 // This loop will extract the distinct groups from the result set
360 // and add it's list of members to the object as a property called
361 // 'members'. Then each group will be added to the result set indexed
362 // by it's course id.
364 // The resulting data structure for $groups should be:
369 // <rest of group properties>
372 // <group member properties>
375 // <group member properties>
381 // <rest of group properties>
384 // <group member properties>
387 // <group member properties>
394 foreach ($results as $key => $result) {
395 $groupid = $result->gid
;
396 $courseid = $result->courseid
;
397 $coursegroups = $groups[$courseid];
398 $groupsmembersid = $result->gmid
;
399 $reducefunc = function($carry, $field) use ($result) {
400 // Iterate over the groups properties and pull
401 // them out into a separate object.
402 list($prefix, $field) = explode('.', $field);
404 if (property_exists($result, $field)) {
405 $carry[$field] = $result->{$field};
411 if (isset($coursegroups[$groupid])) {
412 $group = $coursegroups[$groupid];
418 $group = (object) array_reduce(
425 if (!empty($groupsmembersid)) {
426 $initial = ['id' => $groupsmembersid];
427 $groupsmembers = (object) array_reduce(
428 $groupsmembersfields,
433 $group->members
[$groupsmembers->userid
] = $groupsmembers;
436 $coursegroups[$groupid] = $group;
437 $groups[$courseid] = $coursegroups;
444 * Gets array of all groups in current user.
448 * @return array Returns an array of the group objects.
450 function groups_get_my_groups() {
452 return $DB->get_records_sql("SELECT *
453 FROM {groups_members} gm
457 ORDER BY name ASC", array($USER->id
));
461 * Returns info about user's groups in course.
464 * @param int $courseid
465 * @param int $userid $USER if not specified
466 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
468 function groups_get_user_groups($courseid, $userid=0) {
471 if (empty($userid)) {
475 $cache = cache
::make('core', 'user_group_groupings');
477 // Try to retrieve group ids from the cache.
478 $usergroups = $cache->get($userid);
480 if ($usergroups === false) {
481 $sql = "SELECT g.id, g.courseid, gg.groupingid
483 JOIN {groups_members} gm ON gm.groupid = g.id
484 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
485 WHERE gm.userid = ?";
487 $rs = $DB->get_recordset_sql($sql, array($userid));
489 $usergroups = array();
490 $allgroups = array();
492 foreach ($rs as $group) {
493 if (!array_key_exists($group->courseid
, $allgroups)) {
494 $allgroups[$group->courseid
] = array();
496 $allgroups[$group->courseid
][$group->id
] = $group->id
;
497 if (!array_key_exists($group->courseid
, $usergroups)) {
498 $usergroups[$group->courseid
] = array();
500 if (is_null($group->groupingid
)) {
503 if (!array_key_exists($group->groupingid
, $usergroups[$group->courseid
])) {
504 $usergroups[$group->courseid
][$group->groupingid
] = array();
506 $usergroups[$group->courseid
][$group->groupingid
][$group->id
] = $group->id
;
510 foreach (array_keys($allgroups) as $cid) {
511 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
515 $cache->set($userid, $usergroups);
518 if (array_key_exists($courseid, $usergroups)) {
519 return $usergroups[$courseid];
521 return array('0' => array());
526 * Gets an array of all groupings in a specified course. This value is cached
527 * for a single course (so you can call it repeatedly for the same course
528 * without a performance penalty).
531 * @param int $courseid return all groupings from course with this courseid
532 * @return array Returns an array of the grouping objects (empty if none)
534 function groups_get_all_groupings($courseid) {
535 $data = groups_get_course_data($courseid);
536 return $data->groupings
;
540 * Determines if the user is a member of the given group.
542 * If $userid is null, use the global object.
545 * @param int $groupid The group to check for membership.
546 * @param int $userid The user to check against the group.
547 * @return bool True if the user is a member, false otherwise.
549 function groups_is_member($groupid, $userid=null) {
556 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
560 * Determines if current or specified is member of any active group in activity
563 * @staticvar array $cache
564 * @param stdClass|cm_info $cm course module object
565 * @param int $userid id of user, null means $USER->id
566 * @return bool true if user member of at least one group used in activity
568 function groups_has_membership($cm, $userid=null) {
569 global $CFG, $USER, $DB;
571 static $cache = array();
573 if (empty($userid)) {
577 $cachekey = $userid.'|'.$cm->course
.'|'.$cm->groupingid
;
578 if (isset($cache[$cachekey])) {
579 return($cache[$cachekey]);
582 if ($cm->groupingid
) {
583 // find out if member of any group in selected activity grouping
585 FROM {groups_members} gm, {groupings_groups} gg
586 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
587 $params = array($userid, $cm->groupingid
);
590 // no grouping used - check all groups in course
592 FROM {groups_members} gm, {groups} g
593 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
594 $params = array($userid, $cm->course
);
597 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
599 return $cache[$cachekey];
603 * Returns the users in the specified group.
606 * @param int $groupid The groupid to get the users for
607 * @param int $fields The fields to return
608 * @param int $sort optional sorting of returned users
609 * @return array|bool Returns an array of the users for the specified
610 * group or false if no users or an error returned.
612 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
615 return $DB->get_records_sql("SELECT $fields
616 FROM {user} u, {groups_members} gm
617 WHERE u.id = gm.userid AND gm.groupid = ?
618 ORDER BY $sort", array($groupid));
623 * Returns the users in the specified grouping.
626 * @param int $groupingid The groupingid to get the users for
627 * @param string $fields The fields to return
628 * @param string $sort optional sorting of returned users
629 * @return array|bool Returns an array of the users for the specified
630 * group or false if no users or an error returned.
632 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
635 return $DB->get_records_sql("SELECT $fields
637 INNER JOIN {groups_members} gm ON u.id = gm.userid
638 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
639 WHERE gg.groupingid = ?
640 ORDER BY $sort", array($groupingid));
644 * Returns effective groupmode used in course
647 * @param stdClass $course course object.
648 * @return int group mode
650 function groups_get_course_groupmode($course) {
651 return $course->groupmode
;
655 * Returns effective groupmode used in activity, course setting
656 * overrides activity setting if groupmodeforce enabled.
658 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
661 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
662 * @param stdClass $course object optional course object to improve perf
663 * @return int group mode
665 function groups_get_activity_groupmode($cm, $course=null) {
666 if ($cm instanceof cm_info
) {
667 return $cm->effectivegroupmode
;
669 if (isset($course->id
) and $course->id
== $cm->course
) {
672 // Get course object (reuse $COURSE if possible).
673 $course = get_course($cm->course
, false);
676 return empty($course->groupmodeforce
) ?
$cm->groupmode
: $course->groupmode
;
680 * Print group menu selector for course level.
683 * @param stdClass $course course object
684 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
685 * @param bool $return return as string instead of printing
686 * @return mixed void or string depending on $return param
688 function groups_print_course_menu($course, $urlroot, $return=false) {
689 global $USER, $OUTPUT;
691 if (!$groupmode = $course->groupmode
) {
699 $context = context_course
::instance($course->id
);
700 $aag = has_capability('moodle/site:accessallgroups', $context);
702 $usergroups = array();
703 if ($groupmode == VISIBLEGROUPS
or $aag) {
704 $allowedgroups = groups_get_all_groups($course->id
, 0, $course->defaultgroupingid
);
705 // Get user's own groups and put to the top.
706 $usergroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
708 $allowedgroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
711 $activegroup = groups_get_course_group($course, true, $allowedgroups);
713 $groupsmenu = array();
714 if (!$allowedgroups or $groupmode == VISIBLEGROUPS
or $aag) {
715 $groupsmenu[0] = get_string('allparticipants');
718 $groupsmenu +
= groups_sort_menu_options($allowedgroups, $usergroups);
720 if ($groupmode == VISIBLEGROUPS
) {
721 $grouplabel = get_string('groupsvisible');
723 $grouplabel = get_string('groupsseparate');
726 if ($aag and $course->defaultgroupingid
) {
727 if ($grouping = groups_get_grouping($course->defaultgroupingid
)) {
728 $grouplabel = $grouplabel . ' (' . format_string($grouping->name
) . ')';
732 if (count($groupsmenu) == 1) {
733 $groupname = reset($groupsmenu);
734 $output = $grouplabel.': '.$groupname;
736 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
737 $select->label
= $grouplabel;
738 $output = $OUTPUT->render($select);
741 $output = '<div class="groupselector">'.$output.'</div>';
751 * Turn an array of groups into an array of menu options.
752 * @param array $groups of group objects.
753 * @return array groupid => formatted group name.
755 function groups_list_to_menu($groups) {
756 $groupsmenu = array();
757 foreach ($groups as $group) {
758 $groupsmenu[$group->id
] = format_string($group->name
);
764 * Takes user's allowed groups and own groups and formats for use in group selector menu
765 * If user has allowed groups + own groups will add to an optgroup
766 * Own groups are removed from allowed groups
767 * @param array $allowedgroups All groups user is allowed to see
768 * @param array $usergroups Groups user belongs to
771 function groups_sort_menu_options($allowedgroups, $usergroups) {
772 $useroptions = array();
774 $useroptions = groups_list_to_menu($usergroups);
776 // Remove user groups from other groups list.
777 foreach ($usergroups as $group) {
778 unset($allowedgroups[$group->id
]);
782 $allowedoptions = array();
783 if ($allowedgroups) {
784 $allowedoptions = groups_list_to_menu($allowedgroups);
787 if ($useroptions && $allowedoptions) {
789 1 => array(get_string('mygroups', 'group') => $useroptions),
790 2 => array(get_string('othergroups', 'group') => $allowedoptions)
792 } else if ($useroptions) {
795 return $allowedoptions;
800 * Generates html to print menu selector for course level, listing all groups.
801 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
803 * @param stdclass $course course object.
804 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
805 * @param bool $update set this to true to update current active group based on the group param.
806 * @param int $activegroup Change group active to this group if $update set to true.
808 * @return string html or void
810 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
811 global $SESSION, $OUTPUT, $USER;
813 $groupmode = groups_get_course_groupmode($course);
814 $context = context_course
::instance($course->id
);
815 $groupsmenu = array();
817 if (has_capability('moodle/site:accessallgroups', $context)) {
818 $groupsmenu[0] = get_string('allparticipants');
819 $allowedgroups = groups_get_all_groups($course->id
, 0, $course->defaultgroupingid
);
821 $allowedgroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
824 $groupsmenu +
= groups_list_to_menu($allowedgroups);
827 // Init activegroup array if necessary.
828 if (!isset($SESSION->activegroup
)) {
829 $SESSION->activegroup
= array();
831 if (!isset($SESSION->activegroup
[$course->id
])) {
832 $SESSION->activegroup
[$course->id
] = array(SEPARATEGROUPS
=> array(), VISIBLEGROUPS
=> array(), 'aag' => array());
834 if (empty($groupsmenu[$activegroup])) {
835 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
837 $SESSION->activegroup
[$course->id
][$groupmode][$course->defaultgroupingid
] = $activegroup;
840 $grouplabel = get_string('groups');
841 if (count($groupsmenu) == 0) {
843 } else if (count($groupsmenu) == 1) {
844 $groupname = reset($groupsmenu);
845 $output = $grouplabel.': '.$groupname;
847 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
848 $select->label
= $grouplabel;
849 $output = $OUTPUT->render($select);
857 * Print group menu selector for activity.
860 * @param stdClass|cm_info $cm course module object
861 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
862 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
863 * @param bool $return return as string instead of printing
864 * @param bool $hideallparticipants If true, this prevents the 'All participants'
865 * option from appearing in cases where it normally would. This is intended for
866 * use only by activities that cannot display all groups together. (Note that
867 * selecting this option does not prevent groups_get_activity_group from
868 * returning 0; it will still do that if the user has chosen 'all participants'
869 * in another activity, or not chosen anything.)
870 * @return mixed void or string depending on $return param
872 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
873 global $USER, $OUTPUT;
875 if ($urlroot instanceof moodle_url
) {
876 // no changes necessary
879 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
880 // Display error if urlroot is not absolute (this causes the non-JS version to break)
881 debugging('groups_print_activity_menu requires absolute URL for ' .
882 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
883 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
886 $urlroot = new moodle_url($urlroot);
889 if (!$groupmode = groups_get_activity_groupmode($cm)) {
897 $context = context_module
::instance($cm->id
);
898 $aag = has_capability('moodle/site:accessallgroups', $context);
900 $usergroups = array();
901 if ($groupmode == VISIBLEGROUPS
or $aag) {
902 $allowedgroups = groups_get_all_groups($cm->course
, 0, $cm->groupingid
); // any group in grouping
903 // Get user's own groups and put to the top.
904 $usergroups = groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
);
906 $allowedgroups = groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
); // only assigned groups
909 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
911 $groupsmenu = array();
912 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS
or $aag) and !$hideallparticipants) {
913 $groupsmenu[0] = get_string('allparticipants');
916 $groupsmenu +
= groups_sort_menu_options($allowedgroups, $usergroups);
918 if ($groupmode == VISIBLEGROUPS
) {
919 $grouplabel = get_string('groupsvisible');
921 $grouplabel = get_string('groupsseparate');
924 if ($aag and $cm->groupingid
) {
925 if ($grouping = groups_get_grouping($cm->groupingid
)) {
926 $grouplabel = $grouplabel . ' (' . format_string($grouping->name
) . ')';
930 if (count($groupsmenu) == 1) {
931 $groupname = reset($groupsmenu);
932 $output = $grouplabel.': '.$groupname;
934 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
935 $select->label
= $grouplabel;
936 $output = $OUTPUT->render($select);
939 $output = '<div class="groupselector">'.$output.'</div>';
949 * Returns group active in course, changes the group by default if 'group' page param present
952 * @param stdClass $course course bject
953 * @param bool $update change active group if group param submitted
954 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
955 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
957 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
958 global $USER, $SESSION;
960 if (!$groupmode = $course->groupmode
) {
965 $context = context_course
::instance($course->id
);
966 if (has_capability('moodle/site:accessallgroups', $context)) {
970 if (!is_array($allowedgroups)) {
971 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
972 $allowedgroups = groups_get_all_groups($course->id
, 0, $course->defaultgroupingid
);
974 $allowedgroups = groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
);
978 _group_verify_activegroup($course->id
, $groupmode, $course->defaultgroupingid
, $allowedgroups);
980 // set new active group if requested
981 $changegroup = optional_param('group', -1, PARAM_INT
);
982 if ($update and $changegroup != -1) {
984 if ($changegroup == 0) {
985 // do not allow changing to all groups without accessallgroups capability
986 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
987 $SESSION->activegroup
[$course->id
][$groupmode][$course->defaultgroupingid
] = 0;
991 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
992 $SESSION->activegroup
[$course->id
][$groupmode][$course->defaultgroupingid
] = $changegroup;
997 return $SESSION->activegroup
[$course->id
][$groupmode][$course->defaultgroupingid
];
1001 * Returns group active in activity, changes the group by default if 'group' page param present
1004 * @param stdClass|cm_info $cm course module object
1005 * @param bool $update change active group if group param submitted
1006 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
1007 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
1009 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
1010 global $USER, $SESSION;
1012 if (!$groupmode = groups_get_activity_groupmode($cm)) {
1017 $context = context_module
::instance($cm->id
);
1018 if (has_capability('moodle/site:accessallgroups', $context)) {
1022 if (!is_array($allowedgroups)) {
1023 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
1024 $allowedgroups = groups_get_all_groups($cm->course
, 0, $cm->groupingid
);
1026 $allowedgroups = groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
);
1030 _group_verify_activegroup($cm->course
, $groupmode, $cm->groupingid
, $allowedgroups);
1032 // set new active group if requested
1033 $changegroup = optional_param('group', -1, PARAM_INT
);
1034 if ($update and $changegroup != -1) {
1036 if ($changegroup == 0) {
1037 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
1038 if ($groupmode == VISIBLEGROUPS
or $groupmode === 'aag') {
1039 $SESSION->activegroup
[$cm->course
][$groupmode][$cm->groupingid
] = 0;
1043 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1044 $SESSION->activegroup
[$cm->course
][$groupmode][$cm->groupingid
] = $changegroup;
1049 return $SESSION->activegroup
[$cm->course
][$groupmode][$cm->groupingid
];
1053 * Gets a list of groups that the user is allowed to access within the
1054 * specified activity.
1057 * @param stdClass|cm_info $cm Course-module
1058 * @param int $userid User ID (defaults to current user)
1059 * @return array An array of group objects, or false if none
1061 function groups_get_activity_allowed_groups($cm,$userid=0) {
1062 // Use current user by default
1068 // Get groupmode for activity, taking into account course settings
1069 $groupmode=groups_get_activity_groupmode($cm);
1071 // If visible groups mode, or user has the accessallgroups capability,
1072 // then they can access all groups for the activity...
1073 $context = context_module
::instance($cm->id
);
1074 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $context, $userid)) {
1075 return groups_get_all_groups($cm->course
, 0, $cm->groupingid
);
1077 // ...otherwise they can only access groups they belong to
1078 return groups_get_all_groups($cm->course
, $userid, $cm->groupingid
);
1083 * Determine if a given group is visible to user or not in a given context.
1086 * @param int $groupid Group id to test. 0 for all groups.
1087 * @param stdClass $course Course object.
1088 * @param stdClass $cm Course module object.
1089 * @param int $userid user id to test against. Defaults to $USER.
1090 * @return boolean true if visible, false otherwise
1092 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
1095 if (empty($userid)) {
1096 $userid = $USER->id
;
1099 $groupmode = empty($cm) ?
groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1100 if ($groupmode == NOGROUPS ||
$groupmode == VISIBLEGROUPS
) {
1101 // Groups are not used, or everything is visible, no need to go any further.
1105 $context = empty($cm) ? context_course
::instance($course->id
) : context_module
::instance($cm->id
);
1106 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
1107 // User can see everything. Groupid = 0 is handled here as well.
1109 } else if ($groupid != 0) {
1110 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
1111 $groups = empty($cm) ?
groups_get_all_groups($course->id
, $userid) : groups_get_activity_allowed_groups($cm, $userid);
1112 if (array_key_exists($groupid, $groups)) {
1113 // User can see the group.
1121 * Get sql and parameters that will return user ids for a group
1123 * @param int $groupid
1124 * @return array($sql, $params)
1126 function groups_get_members_ids_sql($groupid) {
1127 $groupjoin = groups_get_members_join($groupid, 'u.id');
1129 $sql = "SELECT DISTINCT u.id
1132 WHERE u.deleted = 0";
1134 return array($sql, $groupjoin->params
);
1138 * Get sql join to return users in a group
1140 * @param int $groupid
1141 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1142 * @return \core\dml\sql_join Contains joins, wheres, params
1144 function groups_get_members_join($groupid, $useridcolumn) {
1145 // Use unique prefix just in case somebody makes some SQL magic with the result.
1148 $prefix = 'gm' . $i . '_';
1150 $join = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = $useridcolumn AND {$prefix}gm.groupid = :{$prefix}gmid)";
1151 $param = array("{$prefix}gmid" => $groupid);
1153 return new \core\dml\
sql_join($join, '', $param);
1157 * Internal method, sets up $SESSION->activegroup and verifies previous value
1159 * @param int $courseid
1160 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1161 * @param int $groupingid 0 means all groups
1162 * @param array $allowedgroups list of groups user can see
1164 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1165 global $SESSION, $USER;
1167 // init activegroup array if necessary
1168 if (!isset($SESSION->activegroup
)) {
1169 $SESSION->activegroup
= array();
1171 if (!array_key_exists($courseid, $SESSION->activegroup
)) {
1172 $SESSION->activegroup
[$courseid] = array(SEPARATEGROUPS
=>array(), VISIBLEGROUPS
=>array(), 'aag'=>array());
1175 // make sure that the current group info is ok
1176 if (array_key_exists($groupingid, $SESSION->activegroup
[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup
[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1177 // active group does not exist anymore or is 0
1178 if ($SESSION->activegroup
[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS
) {
1179 // do not do this if all groups selected and groupmode is not separate
1180 unset($SESSION->activegroup
[$courseid][$groupmode][$groupingid]);
1184 // set up defaults if necessary
1185 if (!array_key_exists($groupingid, $SESSION->activegroup
[$courseid][$groupmode])) {
1186 if ($groupmode == 'aag') {
1187 $SESSION->activegroup
[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1189 } else if ($allowedgroups) {
1190 if ($groupmode != SEPARATEGROUPS
and $mygroups = groups_get_all_groups($courseid, $USER->id
, $groupingid)) {
1191 $firstgroup = reset($mygroups);
1193 $firstgroup = reset($allowedgroups);
1195 $SESSION->activegroup
[$courseid][$groupmode][$groupingid] = $firstgroup->id
;
1198 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1199 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1200 $SESSION->activegroup
[$courseid][$groupmode][$groupingid] = 0;
1206 * Caches group data for a particular course to speed up subsequent requests.
1208 * @param int $courseid The course id to cache data for.
1209 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1210 * @return stdClass A data object containing groups, groupings, and mappings.
1212 function groups_cache_groupdata($courseid, cache
$cache = null) {
1215 if ($cache === null) {
1216 // Initialise a cache if we wern't given one.
1217 $cache = cache
::make('core', 'groupdata');
1220 // Get the groups that belong to the course.
1221 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1222 // Get the groupings that belong to the course.
1223 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1225 if (!is_array($groups)) {
1229 if (!is_array($groupings)) {
1230 $groupings = array();
1233 if (!empty($groupings)) {
1234 // Finally get the mappings between the two.
1235 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1236 $mappings = $DB->get_records_sql("
1237 SELECT gg.id, gg.groupingid, gg.groupid
1238 FROM {groupings_groups} gg
1239 JOIN {groups} g ON g.id = gg.groupid
1240 WHERE gg.groupingid $insql
1241 ORDER BY g.name ASC", $params);
1243 $mappings = array();
1246 // Prepare the data array.
1247 $data = new stdClass
;
1248 $data->groups
= $groups;
1249 $data->groupings
= $groupings;
1250 $data->mappings
= $mappings;
1252 $cache->set($courseid, $data);
1253 // Finally return it so it can be used if desired.
1258 * Gets group data for a course.
1260 * This returns an object with the following properties:
1261 * - groups : An array of all the groups in the course.
1262 * - groupings : An array of all the groupings within the course.
1263 * - mappings : An array of group to grouping mappings.
1265 * @param int $courseid The course id to get data for.
1266 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1269 function groups_get_course_data($courseid, cache
$cache = null) {
1270 if ($cache === null) {
1271 // Initialise a cache if we wern't given one.
1272 $cache = cache
::make('core', 'groupdata');
1274 // Try to retrieve it from the cache.
1275 $data = $cache->get($courseid);
1276 if ($data === false) {
1277 $data = groups_cache_groupdata($courseid, $cache);
1283 * Determine if the current user can see at least one of the groups of the specified user.
1285 * @param stdClass $course Course object.
1286 * @param int $userid user id to check against.
1287 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1288 * @return boolean true if visible, false otherwise
1291 function groups_user_groups_visible($course, $userid, $cm = null) {
1294 $groupmode = empty($cm) ?
groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1295 if ($groupmode == NOGROUPS ||
$groupmode == VISIBLEGROUPS
) {
1296 // Groups are not used, or everything is visible, no need to go any further.
1300 $context = empty($cm) ? context_course
::instance($course->id
) : context_module
::instance($cm->id
);
1301 if (has_capability('moodle/site:accessallgroups', $context)) {
1302 // User can see everything.
1305 // Group mode is separate, and user doesn't have access all groups capability.
1307 $usergroups = groups_get_all_groups($course->id
, $userid);
1308 $currentusergroups = groups_get_all_groups($course->id
, $USER->id
);
1310 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1311 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id
);
1314 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1315 if (!empty($samegroups)) {
1324 * Returns the users in the specified groups.
1326 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1328 * @param array $groupsids The list of groups ids to check
1329 * @param array $extrafields extra fields to be included in result
1330 * @param int $sort optional sorting of returned users
1331 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1334 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1337 $userfields = user_picture
::fields('u', $extrafields);
1338 list($insql, $params) = $DB->get_in_or_equal($groupsids);
1340 return $DB->get_records_sql("SELECT $userfields
1341 FROM {user} u, {groups_members} gm
1342 WHERE u.id = gm.userid AND gm.groupid $insql
1343 GROUP BY $userfields
1344 ORDER BY $sort", $params);
1348 * Returns users who share group membership with the specified user in the given actiivty.
1350 * @param stdClass|cm_info $cm course module
1351 * @param int $userid user id (empty for current user)
1352 * @return array a list of user
1355 function groups_get_activity_shared_group_members($cm, $userid = null) {
1358 if (empty($userid)) {
1362 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1363 // No groups no users.
1364 if (empty($groupsids)) {
1367 return groups_get_groups_members($groupsids);