Merge branch 'MDL-54742-master' of git://github.com/mihailges/moodle
[moodle.git] / lib / grouplib.php
blob469a01286996526e25810ad0319789be7a8a809a
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);
42 /**
43 * Determines if a group with a given groupid exists.
45 * @category group
46 * @param int $groupid The groupid to check for
47 * @return bool True if the group exists, false otherwise or if an error
48 * occurred.
50 function groups_group_exists($groupid) {
51 global $DB;
52 return $DB->record_exists('groups', array('id'=>$groupid));
55 /**
56 * Gets the name of a group with a specified id
58 * @category group
59 * @param int $groupid The id of the group
60 * @return string The name of the group
62 function groups_get_group_name($groupid) {
63 global $DB;
64 return $DB->get_field('groups', 'name', array('id'=>$groupid));
67 /**
68 * Gets the name of a grouping with a specified id
70 * @category group
71 * @param int $groupingid The id of the grouping
72 * @return string The name of the grouping
74 function groups_get_grouping_name($groupingid) {
75 global $DB;
76 return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
79 /**
80 * Returns the groupid of a group with the name specified for the course.
81 * Group names should be unique in course
83 * @category group
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) {
92 return $group->id;
95 return false;
98 /**
99 * Returns the groupid of a group with the idnumber specified for the course.
100 * Group idnumbers should be unique within course
102 * @category group
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)) {
109 return false;
111 $data = groups_get_course_data($courseid);
112 foreach ($data->groups as $group) {
113 if ($group->idnumber == $idnumber) {
114 return $group;
117 return false;
121 * Returns the groupingid of a grouping with the name specified for the course.
122 * Grouping names should be unique in course
124 * @category group
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;
136 return false;
140 * Returns the groupingid of a grouping with the idnumber specified for the course.
141 * Grouping names should be unique within course
143 * @category group
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)) {
150 return false;
152 $data = groups_get_course_data($courseid);
153 foreach ($data->groupings as $grouping) {
154 if ($grouping->idnumber == $idnumber) {
155 return $grouping;
158 return false;
162 * Get the group object
164 * @category group
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 bool|stdClass group object or false if not found
169 * @throws dml_exception
171 function groups_get_group($groupid, $fields='*', $strictness=IGNORE_MISSING) {
172 global $DB;
173 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
177 * Get the grouping object
179 * @category group
180 * @param int $groupingid ID of the group.
181 * @param string $fields
182 * @param int $strictness (IGNORE_MISSING - default)
183 * @return stdClass group object
185 function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING) {
186 global $DB;
187 return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
191 * Gets array of all groups in a specified course.
193 * @category group
194 * @param int $courseid The id of the course.
195 * @param mixed $userid optional user id or array of ids, returns only groups of the user.
196 * @param int $groupingid optional returns only groups in the specified grouping.
197 * @param string $fields
198 * @param bool $withmembers If true - this will return an extra field which is the list of userids that
199 * are members of this group.
200 * @return array Returns an array of the group objects (userid field returned if array in $userid)
202 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*', $withmembers=false) {
203 global $DB;
205 // We need to check that we each field in the fields list belongs to the group table and that it has not being
206 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
207 $knownfields = true;
208 if ($fields !== 'g.*') {
209 // Quickly check if the first field is no longer g.id as using the
210 // cache will return an array indexed differently than when expect
211 if (strpos($fields, 'g.*') !== 0 && strpos($fields, 'g.id') !== 0) {
212 $knownfields = false;
213 } else {
214 $fieldbits = explode(',', $fields);
215 foreach ($fieldbits as $bit) {
216 $bit = trim($bit);
217 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
218 $knownfields = false;
219 break;
225 if (empty($userid) && $knownfields && !$withmembers) {
226 // We can use the cache.
227 $data = groups_get_course_data($courseid);
228 if (empty($groupingid)) {
229 // All groups.. Easy!
230 $groups = $data->groups;
231 } else {
232 $groups = array();
233 foreach ($data->mappings as $mapping) {
234 if ($mapping->groupingid != $groupingid) {
235 continue;
237 if (isset($data->groups[$mapping->groupid])) {
238 $groups[$mapping->groupid] = $data->groups[$mapping->groupid];
242 // Yay! We could use the cache. One more query saved.
243 return $groups;
245 $memberselect = '';
246 $memberjoin = '';
248 if (empty($userid)) {
249 $userfrom = "";
250 $userwhere = "";
251 $params = array();
252 } else {
253 list($usql, $params) = $DB->get_in_or_equal($userid);
254 $userfrom = ", {groups_members} gm";
255 $userwhere = "AND g.id = gm.groupid AND gm.userid $usql";
258 if (!empty($groupingid)) {
259 $groupingfrom = ", {groupings_groups} gg";
260 $groupingwhere = "AND g.id = gg.groupid AND gg.groupingid = ?";
261 $params[] = $groupingid;
262 } else {
263 $groupingfrom = "";
264 $groupingwhere = "";
267 if ($withmembers) {
268 $memberselect = $DB->sql_concat("COALESCE(ugm.userid, 0)", "':'", 'g.id') . ' AS ugmid, ugm.userid, ';
269 $memberjoin = ' LEFT JOIN {groups_members} ugm ON ugm.groupid = g.id ';
272 array_unshift($params, $courseid);
274 $results = $DB->get_records_sql("SELECT $memberselect $fields
275 FROM {groups} g $userfrom $groupingfrom $memberjoin
276 WHERE g.courseid = ? $userwhere $groupingwhere
277 ORDER BY name ASC", $params);
279 if ($withmembers) {
280 // We need to post-process the results back into standard format.
281 $groups = [];
282 foreach ($results as $row) {
283 if (!isset($groups[$row->id])) {
284 $row->members = [$row->userid => $row->userid];
285 unset($row->userid);
286 unset($row->ugmid);
287 $groups[$row->id] = $row;
288 } else {
289 $groups[$row->id]->members[$row->userid] = $row->userid;
292 $results = $groups;
295 return $results;
299 * Gets array of all groups in a set of course.
301 * @category group
302 * @param array $courses Array of course objects or course ids.
303 * @return array Array of groups indexed by course id.
305 function groups_get_all_groups_for_courses($courses) {
306 global $DB;
308 if (empty($courses)) {
309 return [];
312 $groups = [];
313 $courseids = [];
315 foreach ($courses as $course) {
316 $courseid = is_object($course) ? $course->id : $course;
317 $groups[$courseid] = [];
318 $courseids[] = $courseid;
321 $groupfields = [
322 'g.id as gid',
323 'g.courseid',
324 'g.idnumber',
325 'g.name',
326 'g.description',
327 'g.descriptionformat',
328 'g.enrolmentkey',
329 'g.picture',
330 'g.hidepicture',
331 'g.timecreated',
332 'g.timemodified'
335 $groupsmembersfields = [
336 'gm.id as gmid',
337 'gm.groupid',
338 'gm.userid',
339 'gm.timeadded',
340 'gm.component',
341 'gm.itemid'
344 $concatidsql = $DB->sql_concat_join("'-'", ['g.id', 'COALESCE(gm.id, 0)']) . ' AS uniqid';
345 list($courseidsql, $params) = $DB->get_in_or_equal($courseids);
346 $groupfieldssql = implode(',', $groupfields);
347 $groupmembersfieldssql = implode(',', $groupsmembersfields);
348 $sql = "SELECT {$concatidsql}, {$groupfieldssql}, {$groupmembersfieldssql}
349 FROM {groups} g
350 LEFT JOIN {groups_members} gm
351 ON gm.groupid = g.id
352 WHERE g.courseid {$courseidsql}";
354 $results = $DB->get_records_sql($sql, $params);
356 // The results will come back as a flat dataset thanks to the left
357 // join so we will need to do some post processing to blow it out
358 // into a more usable data structure.
360 // This loop will extract the distinct groups from the result set
361 // and add it's list of members to the object as a property called
362 // 'members'. Then each group will be added to the result set indexed
363 // by it's course id.
365 // The resulting data structure for $groups should be:
366 // $groups = [
367 // '1' = [
368 // '1' => (object) [
369 // 'id' => 1,
370 // <rest of group properties>
371 // 'members' => [
372 // '1' => (object) [
373 // <group member properties>
374 // ],
375 // '2' => (object) [
376 // <group member properties>
377 // ]
378 // ]
379 // ],
380 // '2' => (object) [
381 // 'id' => 2,
382 // <rest of group properties>
383 // 'members' => [
384 // '1' => (object) [
385 // <group member properties>
386 // ],
387 // '3' => (object) [
388 // <group member properties>
389 // ]
390 // ]
391 // ]
392 // ]
393 // ]
395 foreach ($results as $key => $result) {
396 $groupid = $result->gid;
397 $courseid = $result->courseid;
398 $coursegroups = $groups[$courseid];
399 $groupsmembersid = $result->gmid;
400 $reducefunc = function($carry, $field) use ($result) {
401 // Iterate over the groups properties and pull
402 // them out into a separate object.
403 list($prefix, $field) = explode('.', $field);
405 if (property_exists($result, $field)) {
406 $carry[$field] = $result->{$field};
409 return $carry;
412 if (isset($coursegroups[$groupid])) {
413 $group = $coursegroups[$groupid];
414 } else {
415 $initial = [
416 'id' => $groupid,
417 'members' => []
419 $group = (object) array_reduce(
420 $groupfields,
421 $reducefunc,
422 $initial
426 if (!empty($groupsmembersid)) {
427 $initial = ['id' => $groupsmembersid];
428 $groupsmembers = (object) array_reduce(
429 $groupsmembersfields,
430 $reducefunc,
431 $initial
434 $group->members[$groupsmembers->userid] = $groupsmembers;
437 $coursegroups[$groupid] = $group;
438 $groups[$courseid] = $coursegroups;
441 return $groups;
445 * Gets array of all groups in current user.
447 * @since Moodle 2.5
448 * @category group
449 * @return array Returns an array of the group objects.
451 function groups_get_my_groups() {
452 global $DB, $USER;
453 return $DB->get_records_sql("SELECT *
454 FROM {groups_members} gm
455 JOIN {groups} g
456 ON g.id = gm.groupid
457 WHERE gm.userid = ?
458 ORDER BY name ASC", array($USER->id));
462 * Returns info about user's groups in course.
464 * @category group
465 * @param int $courseid
466 * @param int $userid $USER if not specified
467 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
469 function groups_get_user_groups($courseid, $userid=0) {
470 global $USER, $DB;
472 if (empty($userid)) {
473 $userid = $USER->id;
476 $cache = cache::make('core', 'user_group_groupings');
478 // Try to retrieve group ids from the cache.
479 $usergroups = $cache->get($userid);
481 if ($usergroups === false) {
482 $sql = "SELECT g.id, g.courseid, gg.groupingid
483 FROM {groups} g
484 JOIN {groups_members} gm ON gm.groupid = g.id
485 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
486 WHERE gm.userid = ?";
488 $rs = $DB->get_recordset_sql($sql, array($userid));
490 $usergroups = array();
491 $allgroups = array();
493 foreach ($rs as $group) {
494 if (!array_key_exists($group->courseid, $allgroups)) {
495 $allgroups[$group->courseid] = array();
497 $allgroups[$group->courseid][$group->id] = $group->id;
498 if (!array_key_exists($group->courseid, $usergroups)) {
499 $usergroups[$group->courseid] = array();
501 if (is_null($group->groupingid)) {
502 continue;
504 if (!array_key_exists($group->groupingid, $usergroups[$group->courseid])) {
505 $usergroups[$group->courseid][$group->groupingid] = array();
507 $usergroups[$group->courseid][$group->groupingid][$group->id] = $group->id;
509 $rs->close();
511 foreach (array_keys($allgroups) as $cid) {
512 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
515 // Cache the data.
516 $cache->set($userid, $usergroups);
519 if (array_key_exists($courseid, $usergroups)) {
520 return $usergroups[$courseid];
521 } else {
522 return array('0' => array());
527 * Gets an array of all groupings in a specified course. This value is cached
528 * for a single course (so you can call it repeatedly for the same course
529 * without a performance penalty).
531 * @category group
532 * @param int $courseid return all groupings from course with this courseid
533 * @return array Returns an array of the grouping objects (empty if none)
535 function groups_get_all_groupings($courseid) {
536 $data = groups_get_course_data($courseid);
537 return $data->groupings;
541 * Determines if the user is a member of the given group.
543 * If $userid is null, use the global object.
545 * @category group
546 * @param int $groupid The group to check for membership.
547 * @param int $userid The user to check against the group.
548 * @return bool True if the user is a member, false otherwise.
550 function groups_is_member($groupid, $userid=null) {
551 global $USER, $DB;
553 if (!$userid) {
554 $userid = $USER->id;
557 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
561 * Determines if current or specified is member of any active group in activity
563 * @category group
564 * @staticvar array $cache
565 * @param stdClass|cm_info $cm course module object
566 * @param int $userid id of user, null means $USER->id
567 * @return bool true if user member of at least one group used in activity
569 function groups_has_membership($cm, $userid=null) {
570 global $CFG, $USER, $DB;
572 static $cache = array();
574 if (empty($userid)) {
575 $userid = $USER->id;
578 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
579 if (isset($cache[$cachekey])) {
580 return($cache[$cachekey]);
583 if ($cm->groupingid) {
584 // find out if member of any group in selected activity grouping
585 $sql = "SELECT 'x'
586 FROM {groups_members} gm, {groupings_groups} gg
587 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
588 $params = array($userid, $cm->groupingid);
590 } else {
591 // no grouping used - check all groups in course
592 $sql = "SELECT 'x'
593 FROM {groups_members} gm, {groups} g
594 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
595 $params = array($userid, $cm->course);
598 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
600 return $cache[$cachekey];
604 * Returns the users in the specified group.
606 * @category group
607 * @param int $groupid The groupid to get the users for
608 * @param int $fields The fields to return
609 * @param int $sort optional sorting of returned users
610 * @return array|bool Returns an array of the users for the specified
611 * group or false if no users or an error returned.
613 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
614 global $DB;
616 return $DB->get_records_sql("SELECT $fields
617 FROM {user} u, {groups_members} gm
618 WHERE u.id = gm.userid AND gm.groupid = ?
619 ORDER BY $sort", array($groupid));
624 * Returns the users in the specified grouping.
626 * @category group
627 * @param int $groupingid The groupingid to get the users for
628 * @param string $fields The fields to return
629 * @param string $sort optional sorting of returned users
630 * @return array|bool Returns an array of the users for the specified
631 * group or false if no users or an error returned.
633 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
634 global $DB;
636 return $DB->get_records_sql("SELECT $fields
637 FROM {user} u
638 INNER JOIN {groups_members} gm ON u.id = gm.userid
639 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
640 WHERE gg.groupingid = ?
641 ORDER BY $sort", array($groupingid));
645 * Returns effective groupmode used in course
647 * @category group
648 * @param stdClass $course course object.
649 * @return int group mode
651 function groups_get_course_groupmode($course) {
652 return $course->groupmode;
656 * Returns effective groupmode used in activity, course setting
657 * overrides activity setting if groupmodeforce enabled.
659 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
661 * @category group
662 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
663 * @param stdClass $course object optional course object to improve perf
664 * @return int group mode
666 function groups_get_activity_groupmode($cm, $course=null) {
667 if ($cm instanceof cm_info) {
668 return $cm->effectivegroupmode;
670 if (isset($course->id) and $course->id == $cm->course) {
671 //ok
672 } else {
673 // Get course object (reuse $COURSE if possible).
674 $course = get_course($cm->course, false);
677 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
681 * Print group menu selector for course level.
683 * @category group
684 * @param stdClass $course course object
685 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
686 * @param bool $return return as string instead of printing
687 * @return mixed void or string depending on $return param
689 function groups_print_course_menu($course, $urlroot, $return=false) {
690 global $USER, $OUTPUT;
692 if (!$groupmode = $course->groupmode) {
693 if ($return) {
694 return '';
695 } else {
696 return;
700 $context = context_course::instance($course->id);
701 $aag = has_capability('moodle/site:accessallgroups', $context);
703 $usergroups = array();
704 if ($groupmode == VISIBLEGROUPS or $aag) {
705 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
706 // Get user's own groups and put to the top.
707 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
708 } else {
709 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
712 $activegroup = groups_get_course_group($course, true, $allowedgroups);
714 $groupsmenu = array();
715 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
716 $groupsmenu[0] = get_string('allparticipants');
719 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
721 if ($groupmode == VISIBLEGROUPS) {
722 $grouplabel = get_string('groupsvisible');
723 } else {
724 $grouplabel = get_string('groupsseparate');
727 if ($aag and $course->defaultgroupingid) {
728 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
729 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
733 if (count($groupsmenu) == 1) {
734 $groupname = reset($groupsmenu);
735 $output = $grouplabel.': '.$groupname;
736 } else {
737 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
738 $select->label = $grouplabel;
739 $output = $OUTPUT->render($select);
742 $output = '<div class="groupselector">'.$output.'</div>';
744 if ($return) {
745 return $output;
746 } else {
747 echo $output;
752 * Turn an array of groups into an array of menu options.
753 * @param array $groups of group objects.
754 * @return array groupid => formatted group name.
756 function groups_list_to_menu($groups) {
757 $groupsmenu = array();
758 foreach ($groups as $group) {
759 $groupsmenu[$group->id] = format_string($group->name);
761 return $groupsmenu;
765 * Takes user's allowed groups and own groups and formats for use in group selector menu
766 * If user has allowed groups + own groups will add to an optgroup
767 * Own groups are removed from allowed groups
768 * @param array $allowedgroups All groups user is allowed to see
769 * @param array $usergroups Groups user belongs to
770 * @return array
772 function groups_sort_menu_options($allowedgroups, $usergroups) {
773 $useroptions = array();
774 if ($usergroups) {
775 $useroptions = groups_list_to_menu($usergroups);
777 // Remove user groups from other groups list.
778 foreach ($usergroups as $group) {
779 unset($allowedgroups[$group->id]);
783 $allowedoptions = array();
784 if ($allowedgroups) {
785 $allowedoptions = groups_list_to_menu($allowedgroups);
788 if ($useroptions && $allowedoptions) {
789 return array(
790 1 => array(get_string('mygroups', 'group') => $useroptions),
791 2 => array(get_string('othergroups', 'group') => $allowedoptions)
793 } else if ($useroptions) {
794 return $useroptions;
795 } else {
796 return $allowedoptions;
801 * Generates html to print menu selector for course level, listing all groups.
802 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
804 * @param stdclass $course course object.
805 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
806 * @param bool $update set this to true to update current active group based on the group param.
807 * @param int $activegroup Change group active to this group if $update set to true.
809 * @return string html or void
811 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
812 global $SESSION, $OUTPUT, $USER;
814 $groupmode = groups_get_course_groupmode($course);
815 $context = context_course::instance($course->id);
816 $groupsmenu = array();
818 if (has_capability('moodle/site:accessallgroups', $context)) {
819 $groupsmenu[0] = get_string('allparticipants');
820 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
821 } else {
822 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
825 $groupsmenu += groups_list_to_menu($allowedgroups);
827 if ($update) {
828 // Init activegroup array if necessary.
829 if (!isset($SESSION->activegroup)) {
830 $SESSION->activegroup = array();
832 if (!isset($SESSION->activegroup[$course->id])) {
833 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
835 if (empty($groupsmenu[$activegroup])) {
836 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
838 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
841 $grouplabel = get_string('groups');
842 if (count($groupsmenu) == 0) {
843 return '';
844 } else if (count($groupsmenu) == 1) {
845 $groupname = reset($groupsmenu);
846 $output = $grouplabel.': '.$groupname;
847 } else {
848 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
849 $select->label = $grouplabel;
850 $output = $OUTPUT->render($select);
853 return $output;
858 * Print group menu selector for activity.
860 * @category group
861 * @param stdClass|cm_info $cm course module object
862 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
863 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
864 * @param bool $return return as string instead of printing
865 * @param bool $hideallparticipants If true, this prevents the 'All participants'
866 * option from appearing in cases where it normally would. This is intended for
867 * use only by activities that cannot display all groups together. (Note that
868 * selecting this option does not prevent groups_get_activity_group from
869 * returning 0; it will still do that if the user has chosen 'all participants'
870 * in another activity, or not chosen anything.)
871 * @return mixed void or string depending on $return param
873 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
874 global $USER, $OUTPUT;
876 if ($urlroot instanceof moodle_url) {
877 // no changes necessary
879 } else {
880 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
881 // Display error if urlroot is not absolute (this causes the non-JS version to break)
882 debugging('groups_print_activity_menu requires absolute URL for ' .
883 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
884 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
885 DEBUG_DEVELOPER);
887 $urlroot = new moodle_url($urlroot);
890 if (!$groupmode = groups_get_activity_groupmode($cm)) {
891 if ($return) {
892 return '';
893 } else {
894 return;
898 $context = context_module::instance($cm->id);
899 $aag = has_capability('moodle/site:accessallgroups', $context);
901 $usergroups = array();
902 if ($groupmode == VISIBLEGROUPS or $aag) {
903 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid); // any group in grouping
904 // Get user's own groups and put to the top.
905 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
906 } else {
907 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); // only assigned groups
910 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
912 $groupsmenu = array();
913 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
914 $groupsmenu[0] = get_string('allparticipants');
917 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
919 if ($groupmode == VISIBLEGROUPS) {
920 $grouplabel = get_string('groupsvisible');
921 } else {
922 $grouplabel = get_string('groupsseparate');
925 if ($aag and $cm->groupingid) {
926 if ($grouping = groups_get_grouping($cm->groupingid)) {
927 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
931 if (count($groupsmenu) == 1) {
932 $groupname = reset($groupsmenu);
933 $output = $grouplabel.': '.$groupname;
934 } else {
935 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
936 $select->label = $grouplabel;
937 $output = $OUTPUT->render($select);
940 $output = '<div class="groupselector">'.$output.'</div>';
942 if ($return) {
943 return $output;
944 } else {
945 echo $output;
950 * Returns group active in course, changes the group by default if 'group' page param present
952 * @category group
953 * @param stdClass $course course bject
954 * @param bool $update change active group if group param submitted
955 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
956 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
958 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
959 global $USER, $SESSION;
961 if (!$groupmode = $course->groupmode) {
962 // NOGROUPS used
963 return false;
966 $context = context_course::instance($course->id);
967 if (has_capability('moodle/site:accessallgroups', $context)) {
968 $groupmode = 'aag';
971 if (!is_array($allowedgroups)) {
972 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
973 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
974 } else {
975 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
979 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
981 // set new active group if requested
982 $changegroup = optional_param('group', -1, PARAM_INT);
983 if ($update and $changegroup != -1) {
985 if ($changegroup == 0) {
986 // do not allow changing to all groups without accessallgroups capability
987 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
988 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
991 } else {
992 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
993 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
998 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
1002 * Returns group active in activity, changes the group by default if 'group' page param present
1004 * @category group
1005 * @param stdClass|cm_info $cm course module object
1006 * @param bool $update change active group if group param submitted
1007 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
1008 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
1010 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
1011 global $USER, $SESSION;
1013 if (!$groupmode = groups_get_activity_groupmode($cm)) {
1014 // NOGROUPS used
1015 return false;
1018 $context = context_module::instance($cm->id);
1019 if (has_capability('moodle/site:accessallgroups', $context)) {
1020 $groupmode = 'aag';
1023 if (!is_array($allowedgroups)) {
1024 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1025 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
1026 } else {
1027 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
1031 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
1033 // set new active group if requested
1034 $changegroup = optional_param('group', -1, PARAM_INT);
1035 if ($update and $changegroup != -1) {
1037 if ($changegroup == 0) {
1038 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
1039 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1040 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
1043 } else {
1044 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1045 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
1050 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
1054 * Gets a list of groups that the user is allowed to access within the
1055 * specified activity.
1057 * @category group
1058 * @param stdClass|cm_info $cm Course-module
1059 * @param int $userid User ID (defaults to current user)
1060 * @return array An array of group objects, or false if none
1062 function groups_get_activity_allowed_groups($cm,$userid=0) {
1063 // Use current user by default
1064 global $USER;
1065 if(!$userid) {
1066 $userid=$USER->id;
1069 // Get groupmode for activity, taking into account course settings
1070 $groupmode=groups_get_activity_groupmode($cm);
1072 // If visible groups mode, or user has the accessallgroups capability,
1073 // then they can access all groups for the activity...
1074 $context = context_module::instance($cm->id);
1075 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
1076 return groups_get_all_groups($cm->course, 0, $cm->groupingid);
1077 } else {
1078 // ...otherwise they can only access groups they belong to
1079 return groups_get_all_groups($cm->course, $userid, $cm->groupingid);
1084 * Determine if a given group is visible to user or not in a given context.
1086 * @since Moodle 2.6
1087 * @param int $groupid Group id to test. 0 for all groups.
1088 * @param stdClass $course Course object.
1089 * @param stdClass $cm Course module object.
1090 * @param int $userid user id to test against. Defaults to $USER.
1091 * @return boolean true if visible, false otherwise
1093 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
1094 global $USER;
1096 if (empty($userid)) {
1097 $userid = $USER->id;
1100 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1101 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1102 // Groups are not used, or everything is visible, no need to go any further.
1103 return true;
1106 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1107 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
1108 // User can see everything. Groupid = 0 is handled here as well.
1109 return true;
1110 } else if ($groupid != 0) {
1111 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
1112 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
1113 if (array_key_exists($groupid, $groups)) {
1114 // User can see the group.
1115 return true;
1118 return false;
1122 * Get sql and parameters that will return user ids for a group
1124 * @param int $groupid
1125 * @return array($sql, $params)
1127 function groups_get_members_ids_sql($groupid) {
1128 $groupjoin = groups_get_members_join($groupid, 'u.id');
1130 $sql = "SELECT DISTINCT u.id
1131 FROM {user} u
1132 $groupjoin->joins
1133 WHERE u.deleted = 0";
1135 return array($sql, $groupjoin->params);
1139 * Get sql join to return users in a group
1141 * @param int $groupid
1142 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1143 * @return \core\dml\sql_join Contains joins, wheres, params
1145 function groups_get_members_join($groupid, $useridcolumn) {
1146 // Use unique prefix just in case somebody makes some SQL magic with the result.
1147 static $i = 0;
1148 $i++;
1149 $prefix = 'gm' . $i . '_';
1151 $join = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = $useridcolumn AND {$prefix}gm.groupid = :{$prefix}gmid)";
1152 $param = array("{$prefix}gmid" => $groupid);
1154 return new \core\dml\sql_join($join, '', $param);
1158 * Internal method, sets up $SESSION->activegroup and verifies previous value
1160 * @param int $courseid
1161 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1162 * @param int $groupingid 0 means all groups
1163 * @param array $allowedgroups list of groups user can see
1165 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1166 global $SESSION, $USER;
1168 // init activegroup array if necessary
1169 if (!isset($SESSION->activegroup)) {
1170 $SESSION->activegroup = array();
1172 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1173 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1176 // make sure that the current group info is ok
1177 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1178 // active group does not exist anymore or is 0
1179 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1180 // do not do this if all groups selected and groupmode is not separate
1181 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1185 // set up defaults if necessary
1186 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1187 if ($groupmode == 'aag') {
1188 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1190 } else if ($allowedgroups) {
1191 if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
1192 $firstgroup = reset($mygroups);
1193 } else {
1194 $firstgroup = reset($allowedgroups);
1196 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1198 } else {
1199 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1200 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1201 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1207 * Caches group data for a particular course to speed up subsequent requests.
1209 * @param int $courseid The course id to cache data for.
1210 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1211 * @return stdClass A data object containing groups, groupings, and mappings.
1213 function groups_cache_groupdata($courseid, cache $cache = null) {
1214 global $DB;
1216 if ($cache === null) {
1217 // Initialise a cache if we wern't given one.
1218 $cache = cache::make('core', 'groupdata');
1221 // Get the groups that belong to the course.
1222 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1223 // Get the groupings that belong to the course.
1224 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1226 if (!is_array($groups)) {
1227 $groups = array();
1230 if (!is_array($groupings)) {
1231 $groupings = array();
1234 if (!empty($groupings)) {
1235 // Finally get the mappings between the two.
1236 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1237 $mappings = $DB->get_records_sql("
1238 SELECT gg.id, gg.groupingid, gg.groupid
1239 FROM {groupings_groups} gg
1240 JOIN {groups} g ON g.id = gg.groupid
1241 WHERE gg.groupingid $insql
1242 ORDER BY g.name ASC", $params);
1243 } else {
1244 $mappings = array();
1247 // Prepare the data array.
1248 $data = new stdClass;
1249 $data->groups = $groups;
1250 $data->groupings = $groupings;
1251 $data->mappings = $mappings;
1252 // Cache the data.
1253 $cache->set($courseid, $data);
1254 // Finally return it so it can be used if desired.
1255 return $data;
1259 * Gets group data for a course.
1261 * This returns an object with the following properties:
1262 * - groups : An array of all the groups in the course.
1263 * - groupings : An array of all the groupings within the course.
1264 * - mappings : An array of group to grouping mappings.
1266 * @param int $courseid The course id to get data for.
1267 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1268 * @return stdClass
1270 function groups_get_course_data($courseid, cache $cache = null) {
1271 if ($cache === null) {
1272 // Initialise a cache if we wern't given one.
1273 $cache = cache::make('core', 'groupdata');
1275 // Try to retrieve it from the cache.
1276 $data = $cache->get($courseid);
1277 if ($data === false) {
1278 $data = groups_cache_groupdata($courseid, $cache);
1280 return $data;
1284 * Determine if the current user can see at least one of the groups of the specified user.
1286 * @param stdClass $course Course object.
1287 * @param int $userid user id to check against.
1288 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1289 * @return boolean true if visible, false otherwise
1290 * @since Moodle 2.9
1292 function groups_user_groups_visible($course, $userid, $cm = null) {
1293 global $USER;
1295 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1296 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1297 // Groups are not used, or everything is visible, no need to go any further.
1298 return true;
1301 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1302 if (has_capability('moodle/site:accessallgroups', $context)) {
1303 // User can see everything.
1304 return true;
1305 } else {
1306 // Group mode is separate, and user doesn't have access all groups capability.
1307 if (empty($cm)) {
1308 $usergroups = groups_get_all_groups($course->id, $userid);
1309 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1310 } else {
1311 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1312 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1315 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1316 if (!empty($samegroups)) {
1317 // We share groups!
1318 return true;
1321 return false;
1325 * Returns the users in the specified groups.
1327 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1329 * @param array $groupsids The list of groups ids to check
1330 * @param array $extrafields extra fields to be included in result
1331 * @param int $sort optional sorting of returned users
1332 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1333 * @since Moodle 3.3
1335 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1336 global $DB;
1338 $userfields = user_picture::fields('u', $extrafields);
1339 list($insql, $params) = $DB->get_in_or_equal($groupsids);
1341 return $DB->get_records_sql("SELECT $userfields
1342 FROM {user} u, {groups_members} gm
1343 WHERE u.id = gm.userid AND gm.groupid $insql
1344 GROUP BY $userfields
1345 ORDER BY $sort", $params);
1349 * Returns users who share group membership with the specified user in the given actiivty.
1351 * @param stdClass|cm_info $cm course module
1352 * @param int $userid user id (empty for current user)
1353 * @return array a list of user
1354 * @since Moodle 3.3
1356 function groups_get_activity_shared_group_members($cm, $userid = null) {
1357 global $USER;
1359 if (empty($userid)) {
1360 $userid = $USER;
1363 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1364 // No groups no users.
1365 if (empty($groupsids)) {
1366 return [];
1368 return groups_get_groups_members($groupsids);