MDL-63086 block_rss_client: Move skip time calculation to task
[moodle.git] / lib / grouplib.php
blob336e372dcf5fda73a491bfcdf15be1a57ad7592b
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 current user.
301 * @since Moodle 2.5
302 * @category group
303 * @return array Returns an array of the group objects.
305 function groups_get_my_groups() {
306 global $DB, $USER;
307 return $DB->get_records_sql("SELECT *
308 FROM {groups_members} gm
309 JOIN {groups} g
310 ON g.id = gm.groupid
311 WHERE gm.userid = ?
312 ORDER BY name ASC", array($USER->id));
316 * Returns info about user's groups in course.
318 * @category group
319 * @param int $courseid
320 * @param int $userid $USER if not specified
321 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
323 function groups_get_user_groups($courseid, $userid=0) {
324 global $USER, $DB;
326 if (empty($userid)) {
327 $userid = $USER->id;
330 $cache = cache::make('core', 'user_group_groupings');
332 // Try to retrieve group ids from the cache.
333 $usergroups = $cache->get($userid);
335 if ($usergroups === false) {
336 $sql = "SELECT g.id, g.courseid, gg.groupingid
337 FROM {groups} g
338 JOIN {groups_members} gm ON gm.groupid = g.id
339 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
340 WHERE gm.userid = ?";
342 $rs = $DB->get_recordset_sql($sql, array($userid));
344 $usergroups = array();
345 $allgroups = array();
347 foreach ($rs as $group) {
348 if (!array_key_exists($group->courseid, $allgroups)) {
349 $allgroups[$group->courseid] = array();
351 $allgroups[$group->courseid][$group->id] = $group->id;
352 if (!array_key_exists($group->courseid, $usergroups)) {
353 $usergroups[$group->courseid] = array();
355 if (is_null($group->groupingid)) {
356 continue;
358 if (!array_key_exists($group->groupingid, $usergroups[$group->courseid])) {
359 $usergroups[$group->courseid][$group->groupingid] = array();
361 $usergroups[$group->courseid][$group->groupingid][$group->id] = $group->id;
363 $rs->close();
365 foreach (array_keys($allgroups) as $cid) {
366 $usergroups[$cid]['0'] = array_keys($allgroups[$cid]); // All user groups in the course.
369 // Cache the data.
370 $cache->set($userid, $usergroups);
373 if (array_key_exists($courseid, $usergroups)) {
374 return $usergroups[$courseid];
375 } else {
376 return array('0' => array());
381 * Gets an array of all groupings in a specified course. This value is cached
382 * for a single course (so you can call it repeatedly for the same course
383 * without a performance penalty).
385 * @category group
386 * @param int $courseid return all groupings from course with this courseid
387 * @return array Returns an array of the grouping objects (empty if none)
389 function groups_get_all_groupings($courseid) {
390 $data = groups_get_course_data($courseid);
391 return $data->groupings;
395 * Determines if the user is a member of the given group.
397 * If $userid is null, use the global object.
399 * @category group
400 * @param int $groupid The group to check for membership.
401 * @param int $userid The user to check against the group.
402 * @return bool True if the user is a member, false otherwise.
404 function groups_is_member($groupid, $userid=null) {
405 global $USER, $DB;
407 if (!$userid) {
408 $userid = $USER->id;
411 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
415 * Determines if current or specified is member of any active group in activity
417 * @category group
418 * @staticvar array $cache
419 * @param stdClass|cm_info $cm course module object
420 * @param int $userid id of user, null means $USER->id
421 * @return bool true if user member of at least one group used in activity
423 function groups_has_membership($cm, $userid=null) {
424 global $CFG, $USER, $DB;
426 static $cache = array();
428 if (empty($userid)) {
429 $userid = $USER->id;
432 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
433 if (isset($cache[$cachekey])) {
434 return($cache[$cachekey]);
437 if ($cm->groupingid) {
438 // find out if member of any group in selected activity grouping
439 $sql = "SELECT 'x'
440 FROM {groups_members} gm, {groupings_groups} gg
441 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
442 $params = array($userid, $cm->groupingid);
444 } else {
445 // no grouping used - check all groups in course
446 $sql = "SELECT 'x'
447 FROM {groups_members} gm, {groups} g
448 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
449 $params = array($userid, $cm->course);
452 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
454 return $cache[$cachekey];
458 * Returns the users in the specified group.
460 * @category group
461 * @param int $groupid The groupid to get the users for
462 * @param int $fields The fields to return
463 * @param int $sort optional sorting of returned users
464 * @return array|bool Returns an array of the users for the specified
465 * group or false if no users or an error returned.
467 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
468 global $DB;
470 return $DB->get_records_sql("SELECT $fields
471 FROM {user} u, {groups_members} gm
472 WHERE u.id = gm.userid AND gm.groupid = ?
473 ORDER BY $sort", array($groupid));
478 * Returns the users in the specified grouping.
480 * @category group
481 * @param int $groupingid The groupingid to get the users for
482 * @param string $fields The fields to return
483 * @param string $sort optional sorting of returned users
484 * @return array|bool Returns an array of the users for the specified
485 * group or false if no users or an error returned.
487 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
488 global $DB;
490 return $DB->get_records_sql("SELECT $fields
491 FROM {user} u
492 INNER JOIN {groups_members} gm ON u.id = gm.userid
493 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
494 WHERE gg.groupingid = ?
495 ORDER BY $sort", array($groupingid));
499 * Returns effective groupmode used in course
501 * @category group
502 * @param stdClass $course course object.
503 * @return int group mode
505 function groups_get_course_groupmode($course) {
506 return $course->groupmode;
510 * Returns effective groupmode used in activity, course setting
511 * overrides activity setting if groupmodeforce enabled.
513 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
515 * @category group
516 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
517 * @param stdClass $course object optional course object to improve perf
518 * @return int group mode
520 function groups_get_activity_groupmode($cm, $course=null) {
521 if ($cm instanceof cm_info) {
522 return $cm->effectivegroupmode;
524 if (isset($course->id) and $course->id == $cm->course) {
525 //ok
526 } else {
527 // Get course object (reuse $COURSE if possible).
528 $course = get_course($cm->course, false);
531 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
535 * Print group menu selector for course level.
537 * @category group
538 * @param stdClass $course course object
539 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
540 * @param bool $return return as string instead of printing
541 * @return mixed void or string depending on $return param
543 function groups_print_course_menu($course, $urlroot, $return=false) {
544 global $USER, $OUTPUT;
546 if (!$groupmode = $course->groupmode) {
547 if ($return) {
548 return '';
549 } else {
550 return;
554 $context = context_course::instance($course->id);
555 $aag = has_capability('moodle/site:accessallgroups', $context);
557 $usergroups = array();
558 if ($groupmode == VISIBLEGROUPS or $aag) {
559 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
560 // Get user's own groups and put to the top.
561 $usergroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
562 } else {
563 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
566 $activegroup = groups_get_course_group($course, true, $allowedgroups);
568 $groupsmenu = array();
569 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
570 $groupsmenu[0] = get_string('allparticipants');
573 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
575 if ($groupmode == VISIBLEGROUPS) {
576 $grouplabel = get_string('groupsvisible');
577 } else {
578 $grouplabel = get_string('groupsseparate');
581 if ($aag and $course->defaultgroupingid) {
582 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
583 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
587 if (count($groupsmenu) == 1) {
588 $groupname = reset($groupsmenu);
589 $output = $grouplabel.': '.$groupname;
590 } else {
591 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
592 $select->label = $grouplabel;
593 $output = $OUTPUT->render($select);
596 $output = '<div class="groupselector">'.$output.'</div>';
598 if ($return) {
599 return $output;
600 } else {
601 echo $output;
606 * Turn an array of groups into an array of menu options.
607 * @param array $groups of group objects.
608 * @return array groupid => formatted group name.
610 function groups_list_to_menu($groups) {
611 $groupsmenu = array();
612 foreach ($groups as $group) {
613 $groupsmenu[$group->id] = format_string($group->name);
615 return $groupsmenu;
619 * Takes user's allowed groups and own groups and formats for use in group selector menu
620 * If user has allowed groups + own groups will add to an optgroup
621 * Own groups are removed from allowed groups
622 * @param array $allowedgroups All groups user is allowed to see
623 * @param array $usergroups Groups user belongs to
624 * @return array
626 function groups_sort_menu_options($allowedgroups, $usergroups) {
627 $useroptions = array();
628 if ($usergroups) {
629 $useroptions = groups_list_to_menu($usergroups);
631 // Remove user groups from other groups list.
632 foreach ($usergroups as $group) {
633 unset($allowedgroups[$group->id]);
637 $allowedoptions = array();
638 if ($allowedgroups) {
639 $allowedoptions = groups_list_to_menu($allowedgroups);
642 if ($useroptions && $allowedoptions) {
643 return array(
644 1 => array(get_string('mygroups', 'group') => $useroptions),
645 2 => array(get_string('othergroups', 'group') => $allowedoptions)
647 } else if ($useroptions) {
648 return $useroptions;
649 } else {
650 return $allowedoptions;
655 * Generates html to print menu selector for course level, listing all groups.
656 * Note: This api does not do any group mode check use groups_print_course_menu() instead if you want proper checks.
658 * @param stdclass $course course object.
659 * @param string|moodle_url $urlroot return address. Accepts either a string or a moodle_url.
660 * @param bool $update set this to true to update current active group based on the group param.
661 * @param int $activegroup Change group active to this group if $update set to true.
663 * @return string html or void
665 function groups_allgroups_course_menu($course, $urlroot, $update = false, $activegroup = 0) {
666 global $SESSION, $OUTPUT, $USER;
668 $groupmode = groups_get_course_groupmode($course);
669 $context = context_course::instance($course->id);
670 $groupsmenu = array();
672 if (has_capability('moodle/site:accessallgroups', $context)) {
673 $groupsmenu[0] = get_string('allparticipants');
674 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
675 } else {
676 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
679 $groupsmenu += groups_list_to_menu($allowedgroups);
681 if ($update) {
682 // Init activegroup array if necessary.
683 if (!isset($SESSION->activegroup)) {
684 $SESSION->activegroup = array();
686 if (!isset($SESSION->activegroup[$course->id])) {
687 $SESSION->activegroup[$course->id] = array(SEPARATEGROUPS => array(), VISIBLEGROUPS => array(), 'aag' => array());
689 if (empty($groupsmenu[$activegroup])) {
690 $activegroup = key($groupsmenu); // Force set to one of accessible groups.
692 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $activegroup;
695 $grouplabel = get_string('groups');
696 if (count($groupsmenu) == 0) {
697 return '';
698 } else if (count($groupsmenu) == 1) {
699 $groupname = reset($groupsmenu);
700 $output = $grouplabel.': '.$groupname;
701 } else {
702 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
703 $select->label = $grouplabel;
704 $output = $OUTPUT->render($select);
707 return $output;
712 * Print group menu selector for activity.
714 * @category group
715 * @param stdClass|cm_info $cm course module object
716 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
717 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
718 * @param bool $return return as string instead of printing
719 * @param bool $hideallparticipants If true, this prevents the 'All participants'
720 * option from appearing in cases where it normally would. This is intended for
721 * use only by activities that cannot display all groups together. (Note that
722 * selecting this option does not prevent groups_get_activity_group from
723 * returning 0; it will still do that if the user has chosen 'all participants'
724 * in another activity, or not chosen anything.)
725 * @return mixed void or string depending on $return param
727 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
728 global $USER, $OUTPUT;
730 if ($urlroot instanceof moodle_url) {
731 // no changes necessary
733 } else {
734 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
735 // Display error if urlroot is not absolute (this causes the non-JS version to break)
736 debugging('groups_print_activity_menu requires absolute URL for ' .
737 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
738 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
739 DEBUG_DEVELOPER);
741 $urlroot = new moodle_url($urlroot);
744 if (!$groupmode = groups_get_activity_groupmode($cm)) {
745 if ($return) {
746 return '';
747 } else {
748 return;
752 $context = context_module::instance($cm->id);
753 $aag = has_capability('moodle/site:accessallgroups', $context);
755 $usergroups = array();
756 if ($groupmode == VISIBLEGROUPS or $aag) {
757 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid); // any group in grouping
758 // Get user's own groups and put to the top.
759 $usergroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
760 } else {
761 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); // only assigned groups
764 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
766 $groupsmenu = array();
767 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
768 $groupsmenu[0] = get_string('allparticipants');
771 $groupsmenu += groups_sort_menu_options($allowedgroups, $usergroups);
773 if ($groupmode == VISIBLEGROUPS) {
774 $grouplabel = get_string('groupsvisible');
775 } else {
776 $grouplabel = get_string('groupsseparate');
779 if ($aag and $cm->groupingid) {
780 if ($grouping = groups_get_grouping($cm->groupingid)) {
781 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
785 if (count($groupsmenu) == 1) {
786 $groupname = reset($groupsmenu);
787 $output = $grouplabel.': '.$groupname;
788 } else {
789 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
790 $select->label = $grouplabel;
791 $output = $OUTPUT->render($select);
794 $output = '<div class="groupselector">'.$output.'</div>';
796 if ($return) {
797 return $output;
798 } else {
799 echo $output;
804 * Returns group active in course, changes the group by default if 'group' page param present
806 * @category group
807 * @param stdClass $course course bject
808 * @param bool $update change active group if group param submitted
809 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
810 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
812 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
813 global $USER, $SESSION;
815 if (!$groupmode = $course->groupmode) {
816 // NOGROUPS used
817 return false;
820 $context = context_course::instance($course->id);
821 if (has_capability('moodle/site:accessallgroups', $context)) {
822 $groupmode = 'aag';
825 if (!is_array($allowedgroups)) {
826 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
827 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
828 } else {
829 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
833 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
835 // set new active group if requested
836 $changegroup = optional_param('group', -1, PARAM_INT);
837 if ($update and $changegroup != -1) {
839 if ($changegroup == 0) {
840 // do not allow changing to all groups without accessallgroups capability
841 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
842 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
845 } else {
846 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
847 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
852 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
856 * Returns group active in activity, changes the group by default if 'group' page param present
858 * @category group
859 * @param stdClass|cm_info $cm course module object
860 * @param bool $update change active group if group param submitted
861 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
862 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
864 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
865 global $USER, $SESSION;
867 if (!$groupmode = groups_get_activity_groupmode($cm)) {
868 // NOGROUPS used
869 return false;
872 $context = context_module::instance($cm->id);
873 if (has_capability('moodle/site:accessallgroups', $context)) {
874 $groupmode = 'aag';
877 if (!is_array($allowedgroups)) {
878 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
879 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
880 } else {
881 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
885 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
887 // set new active group if requested
888 $changegroup = optional_param('group', -1, PARAM_INT);
889 if ($update and $changegroup != -1) {
891 if ($changegroup == 0) {
892 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
893 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
894 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
897 } else {
898 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
899 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
904 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
908 * Gets a list of groups that the user is allowed to access within the
909 * specified activity.
911 * @category group
912 * @param stdClass|cm_info $cm Course-module
913 * @param int $userid User ID (defaults to current user)
914 * @return array An array of group objects, or false if none
916 function groups_get_activity_allowed_groups($cm,$userid=0) {
917 // Use current user by default
918 global $USER;
919 if(!$userid) {
920 $userid=$USER->id;
923 // Get groupmode for activity, taking into account course settings
924 $groupmode=groups_get_activity_groupmode($cm);
926 // If visible groups mode, or user has the accessallgroups capability,
927 // then they can access all groups for the activity...
928 $context = context_module::instance($cm->id);
929 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context, $userid)) {
930 return groups_get_all_groups($cm->course, 0, $cm->groupingid);
931 } else {
932 // ...otherwise they can only access groups they belong to
933 return groups_get_all_groups($cm->course, $userid, $cm->groupingid);
938 * Determine if a given group is visible to user or not in a given context.
940 * @since Moodle 2.6
941 * @param int $groupid Group id to test. 0 for all groups.
942 * @param stdClass $course Course object.
943 * @param stdClass $cm Course module object.
944 * @param int $userid user id to test against. Defaults to $USER.
945 * @return boolean true if visible, false otherwise
947 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
948 global $USER;
950 if (empty($userid)) {
951 $userid = $USER->id;
954 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
955 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
956 // Groups are not used, or everything is visible, no need to go any further.
957 return true;
960 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
961 if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
962 // User can see everything. Groupid = 0 is handled here as well.
963 return true;
964 } else if ($groupid != 0) {
965 // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
966 $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
967 if (array_key_exists($groupid, $groups)) {
968 // User can see the group.
969 return true;
972 return false;
976 * Get sql and parameters that will return user ids for a group
978 * @param int $groupid
979 * @return array($sql, $params)
981 function groups_get_members_ids_sql($groupid) {
982 $groupjoin = groups_get_members_join($groupid, 'u.id');
984 $sql = "SELECT DISTINCT u.id
985 FROM {user} u
986 $groupjoin->joins
987 WHERE u.deleted = 0";
989 return array($sql, $groupjoin->params);
993 * Get sql join to return users in a group
995 * @param int $groupid
996 * @param string $useridcolumn The column of the user id from the calling SQL, e.g. u.id
997 * @return \core\dml\sql_join Contains joins, wheres, params
999 function groups_get_members_join($groupid, $useridcolumn) {
1000 // Use unique prefix just in case somebody makes some SQL magic with the result.
1001 static $i = 0;
1002 $i++;
1003 $prefix = 'gm' . $i . '_';
1005 $join = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = $useridcolumn AND {$prefix}gm.groupid = :{$prefix}gmid)";
1006 $param = array("{$prefix}gmid" => $groupid);
1008 return new \core\dml\sql_join($join, '', $param);
1012 * Internal method, sets up $SESSION->activegroup and verifies previous value
1014 * @param int $courseid
1015 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
1016 * @param int $groupingid 0 means all groups
1017 * @param array $allowedgroups list of groups user can see
1019 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
1020 global $SESSION, $USER;
1022 // init activegroup array if necessary
1023 if (!isset($SESSION->activegroup)) {
1024 $SESSION->activegroup = array();
1026 if (!array_key_exists($courseid, $SESSION->activegroup)) {
1027 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
1030 // make sure that the current group info is ok
1031 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
1032 // active group does not exist anymore or is 0
1033 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
1034 // do not do this if all groups selected and groupmode is not separate
1035 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
1039 // set up defaults if necessary
1040 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
1041 if ($groupmode == 'aag') {
1042 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
1044 } else if ($allowedgroups) {
1045 if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
1046 $firstgroup = reset($mygroups);
1047 } else {
1048 $firstgroup = reset($allowedgroups);
1050 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
1052 } else {
1053 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
1054 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
1055 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
1061 * Caches group data for a particular course to speed up subsequent requests.
1063 * @param int $courseid The course id to cache data for.
1064 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1065 * @return stdClass A data object containing groups, groupings, and mappings.
1067 function groups_cache_groupdata($courseid, cache $cache = null) {
1068 global $DB;
1070 if ($cache === null) {
1071 // Initialise a cache if we wern't given one.
1072 $cache = cache::make('core', 'groupdata');
1075 // Get the groups that belong to the course.
1076 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
1077 // Get the groupings that belong to the course.
1078 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
1080 if (!is_array($groups)) {
1081 $groups = array();
1084 if (!is_array($groupings)) {
1085 $groupings = array();
1088 if (!empty($groupings)) {
1089 // Finally get the mappings between the two.
1090 list($insql, $params) = $DB->get_in_or_equal(array_keys($groupings));
1091 $mappings = $DB->get_records_sql("
1092 SELECT gg.id, gg.groupingid, gg.groupid
1093 FROM {groupings_groups} gg
1094 JOIN {groups} g ON g.id = gg.groupid
1095 WHERE gg.groupingid $insql
1096 ORDER BY g.name ASC", $params);
1097 } else {
1098 $mappings = array();
1101 // Prepare the data array.
1102 $data = new stdClass;
1103 $data->groups = $groups;
1104 $data->groupings = $groupings;
1105 $data->mappings = $mappings;
1106 // Cache the data.
1107 $cache->set($courseid, $data);
1108 // Finally return it so it can be used if desired.
1109 return $data;
1113 * Gets group data for a course.
1115 * This returns an object with the following properties:
1116 * - groups : An array of all the groups in the course.
1117 * - groupings : An array of all the groupings within the course.
1118 * - mappings : An array of group to grouping mappings.
1120 * @param int $courseid The course id to get data for.
1121 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
1122 * @return stdClass
1124 function groups_get_course_data($courseid, cache $cache = null) {
1125 if ($cache === null) {
1126 // Initialise a cache if we wern't given one.
1127 $cache = cache::make('core', 'groupdata');
1129 // Try to retrieve it from the cache.
1130 $data = $cache->get($courseid);
1131 if ($data === false) {
1132 $data = groups_cache_groupdata($courseid, $cache);
1134 return $data;
1138 * Determine if the current user can see at least one of the groups of the specified user.
1140 * @param stdClass $course Course object.
1141 * @param int $userid user id to check against.
1142 * @param stdClass $cm Course module object. Optional, just for checking at activity level instead course one.
1143 * @return boolean true if visible, false otherwise
1144 * @since Moodle 2.9
1146 function groups_user_groups_visible($course, $userid, $cm = null) {
1147 global $USER;
1149 $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
1150 if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
1151 // Groups are not used, or everything is visible, no need to go any further.
1152 return true;
1155 $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
1156 if (has_capability('moodle/site:accessallgroups', $context)) {
1157 // User can see everything.
1158 return true;
1159 } else {
1160 // Group mode is separate, and user doesn't have access all groups capability.
1161 if (empty($cm)) {
1162 $usergroups = groups_get_all_groups($course->id, $userid);
1163 $currentusergroups = groups_get_all_groups($course->id, $USER->id);
1164 } else {
1165 $usergroups = groups_get_activity_allowed_groups($cm, $userid);
1166 $currentusergroups = groups_get_activity_allowed_groups($cm, $USER->id);
1169 $samegroups = array_intersect_key($currentusergroups, $usergroups);
1170 if (!empty($samegroups)) {
1171 // We share groups!
1172 return true;
1175 return false;
1179 * Returns the users in the specified groups.
1181 * This function does not return complete user objects by default. It returns the user_picture basic fields.
1183 * @param array $groupsids The list of groups ids to check
1184 * @param array $extrafields extra fields to be included in result
1185 * @param int $sort optional sorting of returned users
1186 * @return array|bool Returns an array of the users for the specified group or false if no users or an error returned.
1187 * @since Moodle 3.3
1189 function groups_get_groups_members($groupsids, $extrafields=null, $sort='lastname ASC') {
1190 global $DB;
1192 $userfields = user_picture::fields('u', $extrafields);
1193 list($insql, $params) = $DB->get_in_or_equal($groupsids);
1195 return $DB->get_records_sql("SELECT $userfields
1196 FROM {user} u, {groups_members} gm
1197 WHERE u.id = gm.userid AND gm.groupid $insql
1198 GROUP BY $userfields
1199 ORDER BY $sort", $params);
1203 * Returns users who share group membership with the specified user in the given actiivty.
1205 * @param stdClass|cm_info $cm course module
1206 * @param int $userid user id (empty for current user)
1207 * @return array a list of user
1208 * @since Moodle 3.3
1210 function groups_get_activity_shared_group_members($cm, $userid = null) {
1211 global $USER;
1213 if (empty($userid)) {
1214 $userid = $USER;
1217 $groupsids = array_keys(groups_get_activity_allowed_groups($cm, $userid));
1218 // No groups no users.
1219 if (empty($groupsids)) {
1220 return [];
1222 return groups_get_groups_members($groupsids);