Merge branch 'MDL-60125-master' of git://github.com/andrewnicols/moodle
[moodle.git] / lib / grouplib.php
blob8893d1322005d2ffca0f9021ecf615631f859ebb
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 stdGlass group object
170 function groups_get_group($groupid, $fields='*', $strictness=IGNORE_MISSING) {
171 global $DB;
172 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
176 * Get the grouping object
178 * @category group
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) {
185 global $DB;
186 return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
190 * Gets array of all groups in a specified course.
192 * @category group
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) {
202 global $DB;
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.
206 $knownfields = true;
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;
212 } else {
213 $fieldbits = explode(',', $fields);
214 foreach ($fieldbits as $bit) {
215 $bit = trim($bit);
216 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
217 $knownfields = false;
218 break;
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;
230 } else {
231 $groups = array();
232 foreach ($data->mappings as $mapping) {
233 if ($mapping->groupingid != $groupingid) {
234 continue;
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.
242 return $groups;
244 $memberselect = '';
245 $memberjoin = '';
247 if (empty($userid)) {
248 $userfrom = "";
249 $userwhere = "";
250 $params = array();
251 } else {
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;
261 } else {
262 $groupingfrom = "";
263 $groupingwhere = "";
266 if ($withmembers) {
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);
278 if ($withmembers) {
279 // We need to post-process the results back into standard format.
280 $groups = [];
281 foreach ($results as $row) {
282 if (!isset($groups[$row->id])) {
283 $row->members = [$row->userid => $row->userid];
284 unset($row->userid);
285 unset($row->ugmid);
286 $groups[$row->id] = $row;
287 } else {
288 $groups[$row->id]->members[$row->userid] = $row->userid;
291 $results = $groups;
294 return $results;
298 * Gets array of all groups in a set of course.
300 * @category group
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) {
305 global $DB;
307 if (empty($courses)) {
308 return [];
311 $groups = [];
312 $courseids = [];
314 foreach ($courses as $course) {
315 $courseid = is_object($course) ? $course->id : $course;
316 $groups[$courseid] = [];
317 $courseids[] = $courseid;
320 $groupfields = [
321 'g.id as gid',
322 'g.courseid',
323 'g.idnumber',
324 'g.name',
325 'g.description',
326 'g.descriptionformat',
327 'g.enrolmentkey',
328 'g.picture',
329 'g.hidepicture',
330 'g.timecreated',
331 'g.timemodified'
334 $groupsmembersfields = [
335 'gm.id as gmid',
336 'gm.groupid',
337 'gm.userid',
338 'gm.timeadded',
339 'gm.component',
340 'gm.itemid'
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}
348 FROM {groups} g
349 LEFT JOIN {groups_members} gm
350 ON gm.groupid = g.id
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:
365 // $groups = [
366 // '1' = [
367 // '1' => (object) [
368 // 'id' => 1,
369 // <rest of group properties>
370 // 'members' => [
371 // '1' => (object) [
372 // <group member properties>
373 // ],
374 // '2' => (object) [
375 // <group member properties>
376 // ]
377 // ]
378 // ],
379 // '2' => (object) [
380 // 'id' => 2,
381 // <rest of group properties>
382 // 'members' => [
383 // '1' => (object) [
384 // <group member properties>
385 // ],
386 // '3' => (object) [
387 // <group member properties>
388 // ]
389 // ]
390 // ]
391 // ]
392 // ]
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};
408 return $carry;
411 if (isset($coursegroups[$groupid])) {
412 $group = $coursegroups[$groupid];
413 } else {
414 $initial = [
415 'id' => $groupid,
416 'members' => []
418 $group = (object) array_reduce(
419 $groupfields,
420 $reducefunc,
421 $initial
425 if (!empty($groupsmembersid)) {
426 $initial = ['id' => $groupsmembersid];
427 $groupsmembers = (object) array_reduce(
428 $groupsmembersfields,
429 $reducefunc,
430 $initial
433 $group->members[$groupsmembers->userid] = $groupsmembers;
436 $coursegroups[$groupid] = $group;
437 $groups[$courseid] = $coursegroups;
440 return $groups;
444 * Gets array of all groups in current user.
446 * @since Moodle 2.5
447 * @category group
448 * @return array Returns an array of the group objects.
450 function groups_get_my_groups() {
451 global $DB, $USER;
452 return $DB->get_records_sql("SELECT *
453 FROM {groups_members} gm
454 JOIN {groups} g
455 ON g.id = gm.groupid
456 WHERE gm.userid = ?
457 ORDER BY name ASC", array($USER->id));
461 * Returns info about user's groups in course.
463 * @category group
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) {
469 global $USER, $DB;
471 if (empty($userid)) {
472 $userid = $USER->id;
475 $sql = "SELECT g.id, gg.groupingid
476 FROM {groups} g
477 JOIN {groups_members} gm ON gm.groupid = g.id
478 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
479 WHERE gm.userid = ? AND g.courseid = ?";
480 $params = array($userid, $courseid);
482 $rs = $DB->get_recordset_sql($sql, $params);
484 if (!$rs->valid()) {
485 $rs->close(); // Not going to iterate (but exit), close rs
486 return array('0' => array());
489 $result = array();
490 $allgroups = array();
492 foreach ($rs as $group) {
493 $allgroups[$group->id] = $group->id;
494 if (is_null($group->groupingid)) {
495 continue;
497 if (!array_key_exists($group->groupingid, $result)) {
498 $result[$group->groupingid] = array();
500 $result[$group->groupingid][$group->id] = $group->id;
502 $rs->close();
504 $result['0'] = array_keys($allgroups); // all groups
506 return $result;
510 * Gets an array of all groupings in a specified course. This value is cached
511 * for a single course (so you can call it repeatedly for the same course
512 * without a performance penalty).
514 * @category group
515 * @param int $courseid return all groupings from course with this courseid
516 * @return array Returns an array of the grouping objects (empty if none)
518 function groups_get_all_groupings($courseid) {
519 $data = groups_get_course_data($courseid);
520 return $data->groupings;
524 * Determines if the user is a member of the given group.
526 * If $userid is null, use the global object.
528 * @category group
529 * @param int $groupid The group to check for membership.
530 * @param int $userid The user to check against the group.
531 * @return bool True if the user is a member, false otherwise.
533 function groups_is_member($groupid, $userid=null) {
534 global $USER, $DB;
536 if (!$userid) {
537 $userid = $USER->id;
540 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
544 * Determines if current or specified is member of any active group in activity
546 * @category group
547 * @staticvar array $cache
548 * @param stdClass|cm_info $cm course module object
549 * @param int $userid id of user, null means $USER->id
550 * @return bool true if user member of at least one group used in activity
552 function groups_has_membership($cm, $userid=null) {
553 global $CFG, $USER, $DB;
555 static $cache = array();
557 if (empty($userid)) {
558 $userid = $USER->id;
561 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
562 if (isset($cache[$cachekey])) {
563 return($cache[$cachekey]);
566 if ($cm->groupingid) {
567 // find out if member of any group in selected activity grouping
568 $sql = "SELECT 'x'
569 FROM {groups_members} gm, {groupings_groups} gg
570 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
571 $params = array($userid, $cm->groupingid);
573 } else {
574 // no grouping used - check all groups in course
575 $sql = "SELECT 'x'
576 FROM {groups_members} gm, {groups} g
577 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
578 $params = array($userid, $cm->course);
581 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
583 return $cache[$cachekey];
587 * Returns the users in the specified group.
589 * @category group
590 * @param int $groupid The groupid to get the users for
591 * @param int $fields The fields to return
592 * @param int $sort optional sorting of returned users
593 * @return array|bool Returns an array of the users for the specified
594 * group or false if no users or an error returned.
596 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
597 global $DB;
599 return $DB->get_records_sql("SELECT $fields
600 FROM {user} u, {groups_members} gm
601 WHERE u.id = gm.userid AND gm.groupid = ?
602 ORDER BY $sort", array($groupid));
607 * Returns the users in the specified grouping.
609 * @category group
610 * @param int $groupingid The groupingid to get the users for
611 * @param string $fields The fields to return
612 * @param string $sort optional sorting of returned users
613 * @return array|bool Returns an array of the users for the specified
614 * group or false if no users or an error returned.
616 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
617 global $DB;
619 return $DB->get_records_sql("SELECT $fields
620 FROM {user} u
621 INNER JOIN {groups_members} gm ON u.id = gm.userid
622 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
623 WHERE gg.groupingid = ?
624 ORDER BY $sort", array($groupingid));
628 * Returns effective groupmode used in course
630 * @category group
631 * @param stdClass $course course object.
632 * @return int group mode
634 function groups_get_course_groupmode($course) {
635 return $course->groupmode;
639 * Returns effective groupmode used in activity, course setting
640 * overrides activity setting if groupmodeforce enabled.
642 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
644 * @category group
645 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
646 * @param stdClass $course object optional course object to improve perf
647 * @return int group mode
649 function groups_get_activity_groupmode($cm, $course=null) {
650 if ($cm instanceof cm_info) {
651 return $cm->effectivegroupmode;
653 if (isset($course->id) and $course->id == $cm->course) {
654 //ok
655 } else {
656 // Get course object (reuse $COURSE if possible).
657 $course = get_course($cm->course, false);
660 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
664 * Print group menu selector for course level.
666 * @category group
667 * @param stdClass $course course object
668 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
669 * @param bool $return return as string instead of printing
670 * @return mixed void or string depending on $return param
672 function groups_print_course_menu($course, $urlroot, $return=false) {
673 global $USER, $OUTPUT;
675 if (!$groupmode = $course->groupmode) {
676 if ($return) {
677 return '';
678 } else {
679 return;
683 $context = context_course::instance($course->id);
684 $aag = has_capability('moodle/site:accessallgroups', $context);
686 $usergroups = array();
687 if ($groupmode == VISIBLEGROUPS or $aag) {
688 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
689 // Get user's own groups and put to the top.
690 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
691 } else {
692 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
695 $activegroup = groups_get_course_group($course, true, $allowedgroups);
697 $groupsmenu = array();
698 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
699 $groupsmenu[0] = get_string('allparticipants');
702 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
704 if ($groupmode == VISIBLEGROUPS) {
705 $grouplabel = get_string('groupsvisible');
706 } else {
707 $grouplabel = get_string('groupsseparate');
710 if ($aag and $course->defaultgroupingid) {
711 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
712 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
716 if (count($groupsmenu) == 1) {
717 $groupname = reset($groupsmenu);
718 $output = $grouplabel.': '.$groupname;
719 } else {
720 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
721 $select->label = $grouplabel;
722 $output = $OUTPUT->render($select);
725 $output = '<div class="groupselector">'.$output.'</div>';
727 if ($return) {
728 return $output;
729 } else {
730 echo $output;
735 * Turn an array of groups into an array of menu options.
736 * @param array $groups of group objects.
737 * @return array groupid => formatted group name.
739 function groups_list_to_menu($groups) {
740 $groupsmenu = array();
741 foreach ($groups as $group) {
742 $groupsmenu[$group->id] = format_string($group->name);
744 return $groupsmenu;
748 * Takes user's allowed groups and own groups and formats for use in group selector menu
749 * If user has allowed groups + own groups will add to an optgroup
750 * Own groups are removed from allowed groups
751 * @param array $allowedgroups All groups user is allowed to see
752 * @param array $usergroups Groups user belongs to
753 * @return array
755 function groups_sort_menu_options($allowedgroups, $usergroups) {
756 $useroptions = array();
757 if ($usergroups) {
758 $useroptions = groups_list_to_menu($usergroups);
760 // Remove user groups from other groups list.
761 foreach ($usergroups as $group) {
762 unset($allowedgroups[$group->id]);
766 $allowedoptions = array();
767 if ($allowedgroups) {
768 $allowedoptions = groups_list_to_menu($allowedgroups);
771 if ($useroptions && $allowedoptions) {
772 return array(
773 1 => array(get_string('mygroups', 'group') => $useroptions),
774 2 => array(get_string('othergroups', 'group') => $allowedoptions)
776 } else if ($useroptions) {
777 return $useroptions;
778 } else {
779 return $allowedoptions;
784 * Generates html to print menu selector for course level, listing all groups.
785 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
787 * @param stdclass $course course object.
788 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
789 * @param bool $update set this to true to update current active group based on the group param.
790 * @param int $activegroup Change group active to this group if $update set to true.
792 * @return string html or void
794 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
795 global $SESSION, $OUTPUT, $USER;
797 $groupmode = groups_get_course_groupmode($course);
798 $context = context_course::instance($course->id);
799 $groupsmenu = array();
801 if (has_capability('moodle/site:accessallgroups', $context)) {
802 $groupsmenu[0] = get_string('allparticipants');
803 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
804 } else {
805 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
808 $groupsmenu += groups_list_to_menu($allowedgroups);
810 if ($update) {
811 // Init activegroup array if necessary.
812 if (!isset($SESSION->activegroup)) {
813 $SESSION->activegroup = array();
815 if (!isset($SESSION->activegroup[$course->id])) {
816 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
818 if (empty($groupsmenu[$activegroup])) {
819 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
821 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
824 $grouplabel = get_string('groups');
825 if (count($groupsmenu) == 0) {
826 return '';
827 } else if (count($groupsmenu) == 1) {
828 $groupname = reset($groupsmenu);
829 $output = $grouplabel.': '.$groupname;
830 } else {
831 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
832 $select->label = $grouplabel;
833 $output = $OUTPUT->render($select);
836 return $output;
841 * Print group menu selector for activity.
843 * @category group
844 * @param stdClass|cm_info $cm course module object
845 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
846 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
847 * @param bool $return return as string instead of printing
848 * @param bool $hideallparticipants If true, this prevents the 'All participants'
849 * option from appearing in cases where it normally would. This is intended for
850 * use only by activities that cannot display all groups together. (Note that
851 * selecting this option does not prevent groups_get_activity_group from
852 * returning 0; it will still do that if the user has chosen 'all participants'
853 * in another activity, or not chosen anything.)
854 * @return mixed void or string depending on $return param
856 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
857 global $USER, $OUTPUT;
859 if ($urlroot instanceof moodle_url) {
860 // no changes necessary
862 } else {
863 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
864 // Display error if urlroot is not absolute (this causes the non-JS version to break)
865 debugging('groups_print_activity_menu requires absolute URL for ' .
866 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
867 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
868 DEBUG_DEVELOPER);
870 $urlroot = new moodle_url($urlroot);
873 if (!$groupmode = groups_get_activity_groupmode($cm)) {
874 if ($return) {
875 return '';
876 } else {
877 return;
881 $context = context_module::instance($cm->id);
882 $aag = has_capability('moodle/site:accessallgroups', $context);
884 $usergroups = array();
885 if ($groupmode == VISIBLEGROUPS or $aag) {
886 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid); // any group in grouping
887 // Get user's own groups and put to the top.
888 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
889 } else {
890 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); // only assigned groups
893 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
895 $groupsmenu = array();
896 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
897 $groupsmenu[0] = get_string('allparticipants');
900 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
902 if ($groupmode == VISIBLEGROUPS) {
903 $grouplabel = get_string('groupsvisible');
904 } else {
905 $grouplabel = get_string('groupsseparate');
908 if ($aag and $cm->groupingid) {
909 if ($grouping = groups_get_grouping($cm->groupingid)) {
910 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
914 if (count($groupsmenu) == 1) {
915 $groupname = reset($groupsmenu);
916 $output = $grouplabel.': '.$groupname;
917 } else {
918 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
919 $select->label = $grouplabel;
920 $output = $OUTPUT->render($select);
923 $output = '<div class="groupselector">'.$output.'</div>';
925 if ($return) {
926 return $output;
927 } else {
928 echo $output;
933 * Returns group active in course, changes the group by default if 'group' page param present
935 * @category group
936 * @param stdClass $course course bject
937 * @param bool $update change active group if group param submitted
938 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
939 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
941 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
942 global $USER, $SESSION;
944 if (!$groupmode = $course->groupmode) {
945 // NOGROUPS used
946 return false;
949 $context = context_course::instance($course->id);
950 if (has_capability('moodle/site:accessallgroups', $context)) {
951 $groupmode = 'aag';
954 if (!is_array($allowedgroups)) {
955 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
956 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
957 } else {
958 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
962 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
964 // set new active group if requested
965 $changegroup = optional_param('group', -1, PARAM_INT);
966 if ($update and $changegroup != -1) {
968 if ($changegroup == 0) {
969 // do not allow changing to all groups without accessallgroups capability
970 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
971 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
974 } else {
975 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
976 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
981 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
985 * Returns group active in activity, changes the group by default if 'group' page param present
987 * @category group
988 * @param stdClass|cm_info $cm course module object
989 * @param bool $update change active group if group param submitted
990 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
991 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
993 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
994 global $USER, $SESSION;
996 if (!$groupmode = groups_get_activity_groupmode($cm)) {
997 // NOGROUPS used
998 return false;
1001 $context = context_module::instance($cm->id);
1002 if (has_capability('moodle/site:accessallgroups', $context)) {
1003 $groupmode = 'aag';
1006 if (!is_array($allowedgroups)) {
1007 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1008 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
1009 } else {
1010 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
1014 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
1016 // set new active group if requested
1017 $changegroup = optional_param('group', -1, PARAM_INT);
1018 if ($update and $changegroup != -1) {
1020 if ($changegroup == 0) {
1021 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
1022 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
1023 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
1026 } else {
1027 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
1028 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
1033 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
1037 * Gets a list of groups that the user is allowed to access within the
1038 * specified activity.
1040 * @category group
1041 * @param stdClass|cm_info $cm Course-module
1042 * @param int $userid User ID (defaults to current user)
1043 * @return array An array of group objects, or false if none
1045 function groups_get_activity_allowed_groups($cm,$userid=0) {
1046 // Use current user by default
1047 global $USER;
1048 if(!$userid) {
1049 $userid=$USER->id;
1052 // Get groupmode for activity, taking into account course settings
1053 $groupmode=groups_get_activity_groupmode($cm);
1055 // If visible groups mode, or user has the accessallgroups capability,
1056 // then they can access all groups for the activity...
1057 $context = context_module::instance($cm->id);
1058 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
1059 return groups_get_all_groups($cm->course, 0, $cm->groupingid);
1060 } else {
1061 // ...otherwise they can only access groups they belong to
1062 return groups_get_all_groups($cm->course, $userid, $cm->groupingid);
1067 * Determine if a given group is visible to user or not in a given context.
1069 * @since Moodle 2.6
1070 * @param int $groupid Group id to test. 0 for all groups.
1071 * @param stdClass $course Course object.
1072 * @param stdClass $cm Course module object.
1073 * @param int $userid user id to test against. Defaults to $USER.
1074 * @return boolean true if visible, false otherwise
1076 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
1077 global $USER;
1079 if (empty($userid)) {
1080 $userid = $USER->id;
1083 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1084 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1085 // Groups are not used, or everything is visible, no need to go any further.
1086 return true;
1089 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1090 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
1091 // User can see everything. Groupid = 0 is handled here as well.
1092 return true;
1093 } else if ($groupid != 0) {
1094 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
1095 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
1096 if (array_key_exists($groupid, $groups)) {
1097 // User can see the group.
1098 return true;
1101 return false;
1105 * Get sql and parameters that will return user ids for a group
1107 * @param int $groupid
1108 * @return array($sql, $params)
1110 function groups_get_members_ids_sql($groupid) {
1111 $groupjoin = groups_get_members_join($groupid, 'u.id');
1113 $sql = "SELECT DISTINCT u.id
1114 FROM {user} u
1115 $groupjoin->joins
1116 WHERE u.deleted = 0";
1118 return array($sql, $groupjoin->params);
1122 * Get sql join to return users in a group
1124 * @param int $groupid
1125 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
1126 * @return \core\dml\sql_join Contains joins, wheres, params
1128 function groups_get_members_join($groupid, $useridcolumn) {
1129 // Use unique prefix just in case somebody makes some SQL magic with the result.
1130 static $i = 0;
1131 $i++;
1132 $prefix = 'gm' . $i . '_';
1134 $join = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = $useridcolumn AND {$prefix}gm.groupid = :{$prefix}gmid)";
1135 $param = array("{$prefix}gmid" => $groupid);
1137 return new \core\dml\sql_join($join, '', $param);
1141 * Internal method, sets up $SESSION->activegroup and verifies previous value
1143 * @param int $courseid
1144 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1145 * @param int $groupingid 0 means all groups
1146 * @param array $allowedgroups list of groups user can see
1148 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1149 global $SESSION, $USER;
1151 // init activegroup array if necessary
1152 if (!isset($SESSION->activegroup)) {
1153 $SESSION->activegroup = array();
1155 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1156 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1159 // make sure that the current group info is ok
1160 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1161 // active group does not exist anymore or is 0
1162 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1163 // do not do this if all groups selected and groupmode is not separate
1164 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1168 // set up defaults if necessary
1169 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1170 if ($groupmode == 'aag') {
1171 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1173 } else if ($allowedgroups) {
1174 if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
1175 $firstgroup = reset($mygroups);
1176 } else {
1177 $firstgroup = reset($allowedgroups);
1179 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1181 } else {
1182 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1183 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1184 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1190 * Caches group data for a particular course to speed up subsequent requests.
1192 * @param int $courseid The course id to cache data for.
1193 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1194 * @return stdClass A data object containing groups, groupings, and mappings.
1196 function groups_cache_groupdata($courseid, cache $cache = null) {
1197 global $DB;
1199 if ($cache === null) {
1200 // Initialise a cache if we wern't given one.
1201 $cache = cache::make('core', 'groupdata');
1204 // Get the groups that belong to the course.
1205 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1206 // Get the groupings that belong to the course.
1207 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1209 if (!is_array($groups)) {
1210 $groups = array();
1213 if (!is_array($groupings)) {
1214 $groupings = array();
1217 if (!empty($groupings)) {
1218 // Finally get the mappings between the two.
1219 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1220 $mappings = $DB->get_records_sql("
1221 SELECT gg.id, gg.groupingid, gg.groupid
1222 FROM {groupings_groups} gg
1223 JOIN {groups} g ON g.id = gg.groupid
1224 WHERE gg.groupingid $insql
1225 ORDER BY g.name ASC", $params);
1226 } else {
1227 $mappings = array();
1230 // Prepare the data array.
1231 $data = new stdClass;
1232 $data->groups = $groups;
1233 $data->groupings = $groupings;
1234 $data->mappings = $mappings;
1235 // Cache the data.
1236 $cache->set($courseid, $data);
1237 // Finally return it so it can be used if desired.
1238 return $data;
1242 * Gets group data for a course.
1244 * This returns an object with the following properties:
1245 * - groups : An array of all the groups in the course.
1246 * - groupings : An array of all the groupings within the course.
1247 * - mappings : An array of group to grouping mappings.
1249 * @param int $courseid The course id to get data for.
1250 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1251 * @return stdClass
1253 function groups_get_course_data($courseid, cache $cache = null) {
1254 if ($cache === null) {
1255 // Initialise a cache if we wern't given one.
1256 $cache = cache::make('core', 'groupdata');
1258 // Try to retrieve it from the cache.
1259 $data = $cache->get($courseid);
1260 if ($data === false) {
1261 $data = groups_cache_groupdata($courseid, $cache);
1263 return $data;
1267 * Determine if the current user can see at least one of the groups of the specified user.
1269 * @param stdClass $course Course object.
1270 * @param int $userid user id to check against.
1271 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1272 * @return boolean true if visible, false otherwise
1273 * @since Moodle 2.9
1275 function groups_user_groups_visible($course, $userid, $cm = null) {
1276 global $USER;
1278 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1279 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1280 // Groups are not used, or everything is visible, no need to go any further.
1281 return true;
1284 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1285 if (has_capability('moodle/site:accessallgroups', $context)) {
1286 // User can see everything.
1287 return true;
1288 } else {
1289 // Group mode is separate, and user doesn't have access all groups capability.
1290 if (empty($cm)) {
1291 $usergroups = groups_get_all_groups($course->id, $userid);
1292 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1293 } else {
1294 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1295 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1298 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1299 if (!empty($samegroups)) {
1300 // We share groups!
1301 return true;
1304 return false;
1308 * Returns the users in the specified groups.
1310 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1312 * @param array $groupsids The list of groups ids to check
1313 * @param array $extrafields extra fields to be included in result
1314 * @param int $sort optional sorting of returned users
1315 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1316 * @since Moodle 3.3
1318 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1319 global $DB;
1321 $userfields = user_picture::fields('u', $extrafields);
1322 list($insql, $params) = $DB->get_in_or_equal($groupsids);
1324 return $DB->get_records_sql("SELECT $userfields
1325 FROM {user} u, {groups_members} gm
1326 WHERE u.id = gm.userid AND gm.groupid $insql
1327 GROUP BY $userfields
1328 ORDER BY $sort", $params);
1332 * Returns users who share group membership with the specified user in the given actiivty.
1334 * @param stdClass|cm_info $cm course module
1335 * @param int $userid user id (empty for current user)
1336 * @return array a list of user
1337 * @since Moodle 3.3
1339 function groups_get_activity_shared_group_members($cm, $userid = null) {
1340 global $USER;
1342 if (empty($userid)) {
1343 $userid = $USER;
1346 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1347 // No groups no users.
1348 if (empty($groupsids)) {
1349 return [];
1351 return groups_get_groups_members($groupsids);