Merge branch 'MDL-40255_M25' of git://github.com/lazydaisy/moodle into MOODLE_25_STABLE
[moodle.git] / lib / grouplib.php
blob3b3808289e5aa711aba584111b3261ad4cc15dca
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 * @return array Returns an array of the group objects (userid field returned if array in $userid)
199 function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*') {
200 global $DB;
202 // We need to check that we each field in the fields list belongs to the group table and that it has not being
203 // aliased. If its something else we need to avoid the cache and run the query as who knows whats going on.
204 $knownfields = true;
205 if ($fields !== 'g.*') {
206 $fieldbits = explode(',', $fields);
207 foreach ($fieldbits as $bit) {
208 $bit = trim($bit);
209 if (strpos($bit, 'g.') !== 0 or stripos($bit, ' AS ') !== false) {
210 $knownfields = false;
211 break;
216 if (empty($userid) && $knownfields) {
217 // We can use the cache.
218 $data = groups_get_course_data($courseid);
219 if (empty($groupingid)) {
220 // All groups.. Easy!
221 $groups = $data->groups;
222 } else {
223 $groups = array();
224 foreach ($data->mappings as $mapping) {
225 if ($mapping->groupingid != $groupingid) {
226 continue;
228 if (isset($data->groups[$mapping->groupid])) {
229 $groups[$mapping->groupid] = $data->groups[$mapping->groupid];
233 // Yay! We could use the cache. One more query saved.
234 return $groups;
238 if (empty($userid)) {
239 $userfrom = "";
240 $userwhere = "";
241 $params = array();
243 } else {
244 list($usql, $params) = $DB->get_in_or_equal($userid);
245 $userfrom = ", {groups_members} gm";
246 $userwhere = "AND g.id = gm.groupid AND gm.userid $usql";
249 if (!empty($groupingid)) {
250 $groupingfrom = ", {groupings_groups} gg";
251 $groupingwhere = "AND g.id = gg.groupid AND gg.groupingid = ?";
252 $params[] = $groupingid;
253 } else {
254 $groupingfrom = "";
255 $groupingwhere = "";
258 array_unshift($params, $courseid);
260 return $DB->get_records_sql("SELECT $fields
261 FROM {groups} g $userfrom $groupingfrom
262 WHERE g.courseid = ? $userwhere $groupingwhere
263 ORDER BY name ASC", $params);
268 * Gets array of all groups in current user.
270 * @since Moodle 2.5
271 * @category group
272 * @return array Returns an array of the group objects.
274 function groups_get_my_groups() {
275 global $DB, $USER;
276 return $DB->get_records_sql("SELECT *
277 FROM {groups_members} gm
278 JOIN {groups} g
279 ON g.id = gm.groupid
280 WHERE gm.userid = ?
281 ORDER BY name ASC", array($USER->id));
285 * Returns info about user's groups in course.
287 * @category group
288 * @param int $courseid
289 * @param int $userid $USER if not specified
290 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
292 function groups_get_user_groups($courseid, $userid=0) {
293 global $USER, $DB;
295 if (empty($userid)) {
296 $userid = $USER->id;
299 $sql = "SELECT g.id, gg.groupingid
300 FROM {groups} g
301 JOIN {groups_members} gm ON gm.groupid = g.id
302 LEFT JOIN {groupings_groups} gg ON gg.groupid = g.id
303 WHERE gm.userid = ? AND g.courseid = ?";
304 $params = array($userid, $courseid);
306 $rs = $DB->get_recordset_sql($sql, $params);
308 if (!$rs->valid()) {
309 $rs->close(); // Not going to iterate (but exit), close rs
310 return array('0' => array());
313 $result = array();
314 $allgroups = array();
316 foreach ($rs as $group) {
317 $allgroups[$group->id] = $group->id;
318 if (is_null($group->groupingid)) {
319 continue;
321 if (!array_key_exists($group->groupingid, $result)) {
322 $result[$group->groupingid] = array();
324 $result[$group->groupingid][$group->id] = $group->id;
326 $rs->close();
328 $result['0'] = array_keys($allgroups); // all groups
330 return $result;
334 * Gets an array of all groupings in a specified course. This value is cached
335 * for a single course (so you can call it repeatedly for the same course
336 * without a performance penalty).
338 * @category group
339 * @param int $courseid return all groupings from course with this courseid
340 * @return array Returns an array of the grouping objects (empty if none)
342 function groups_get_all_groupings($courseid) {
343 $data = groups_get_course_data($courseid);
344 return $data->groupings;
348 * Determines if the user is a member of the given group.
350 * If $userid is null, use the global object.
352 * @category group
353 * @param int $groupid The group to check for membership.
354 * @param int $userid The user to check against the group.
355 * @return bool True if the user is a member, false otherwise.
357 function groups_is_member($groupid, $userid=null) {
358 global $USER, $DB;
360 if (!$userid) {
361 $userid = $USER->id;
364 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
368 * Determines if current or specified is member of any active group in activity
370 * @category group
371 * @staticvar array $cache
372 * @param cm_info $cm course module object
373 * @param int $userid id of user, null means $USER->id
374 * @return bool true if user member of at least one group used in activity
376 function groups_has_membership($cm, $userid=null) {
377 global $CFG, $USER, $DB;
379 static $cache = array();
381 if (empty($userid)) {
382 $userid = $USER->id;
385 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
386 if (isset($cache[$cachekey])) {
387 return($cache[$cachekey]);
390 if ($cm->groupingid) {
391 // find out if member of any group in selected activity grouping
392 $sql = "SELECT 'x'
393 FROM {groups_members} gm, {groupings_groups} gg
394 WHERE gm.userid = ? AND gm.groupid = gg.groupid AND gg.groupingid = ?";
395 $params = array($userid, $cm->groupingid);
397 } else {
398 // no grouping used - check all groups in course
399 $sql = "SELECT 'x'
400 FROM {groups_members} gm, {groups} g
401 WHERE gm.userid = ? AND gm.groupid = g.id AND g.courseid = ?";
402 $params = array($userid, $cm->course);
405 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
407 return $cache[$cachekey];
411 * Returns the users in the specified group.
413 * @category group
414 * @param int $groupid The groupid to get the users for
415 * @param int $fields The fields to return
416 * @param int $sort optional sorting of returned users
417 * @return array|bool Returns an array of the users for the specified
418 * group or false if no users or an error returned.
420 function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
421 global $DB;
423 return $DB->get_records_sql("SELECT $fields
424 FROM {user} u, {groups_members} gm
425 WHERE u.id = gm.userid AND gm.groupid = ?
426 ORDER BY $sort", array($groupid));
431 * Returns the users in the specified grouping.
433 * @category group
434 * @param int $groupingid The groupingid to get the users for
435 * @param string $fields The fields to return
436 * @param string $sort optional sorting of returned users
437 * @return array|bool Returns an array of the users for the specified
438 * group or false if no users or an error returned.
440 function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
441 global $DB;
443 return $DB->get_records_sql("SELECT $fields
444 FROM {user} u
445 INNER JOIN {groups_members} gm ON u.id = gm.userid
446 INNER JOIN {groupings_groups} gg ON gm.groupid = gg.groupid
447 WHERE gg.groupingid = ?
448 ORDER BY $sort", array($groupingid));
452 * Returns effective groupmode used in course
454 * @category group
455 * @param stdClass $course course object.
456 * @return int group mode
458 function groups_get_course_groupmode($course) {
459 return $course->groupmode;
463 * Returns effective groupmode used in activity, course setting
464 * overrides activity setting if groupmodeforce enabled.
466 * @category group
467 * @param cm_info $cm the course module object. Only the ->course and ->groupmode need to be set.
468 * @param stdClass $course object optional course object to improve perf
469 * @return int group mode
471 function groups_get_activity_groupmode($cm, $course=null) {
472 global $COURSE, $DB;
474 // get course object (reuse COURSE if possible)
475 if (isset($course->id) and $course->id == $cm->course) {
476 //ok
477 } else if ($cm->course == $COURSE->id) {
478 $course = $COURSE;
479 } else {
480 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
481 print_error('invalidcourseid');
485 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
489 * Print group menu selector for course level.
491 * @category group
492 * @param stdClass $course course object
493 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
494 * @param bool $return return as string instead of printing
495 * @return mixed void or string depending on $return param
497 function groups_print_course_menu($course, $urlroot, $return=false) {
498 global $USER, $OUTPUT;
500 if (!$groupmode = $course->groupmode) {
501 if ($return) {
502 return '';
503 } else {
504 return;
508 $context = context_course::instance($course->id);
509 $aag = has_capability('moodle/site:accessallgroups', $context);
511 if ($groupmode == VISIBLEGROUPS or $aag) {
512 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
513 } else {
514 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
517 $activegroup = groups_get_course_group($course, true, $allowedgroups);
519 $groupsmenu = array();
520 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
521 $groupsmenu[0] = get_string('allparticipants');
524 if ($allowedgroups) {
525 foreach ($allowedgroups as $group) {
526 $groupsmenu[$group->id] = format_string($group->name);
530 if ($groupmode == VISIBLEGROUPS) {
531 $grouplabel = get_string('groupsvisible');
532 } else {
533 $grouplabel = get_string('groupsseparate');
536 if ($aag and $course->defaultgroupingid) {
537 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
538 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
542 if (count($groupsmenu) == 1) {
543 $groupname = reset($groupsmenu);
544 $output = $grouplabel.': '.$groupname;
545 } else {
546 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
547 $select->label = $grouplabel;
548 $output = $OUTPUT->render($select);
551 $output = '<div class="groupselector">'.$output.'</div>';
553 if ($return) {
554 return $output;
555 } else {
556 echo $output;
561 * Print group menu selector for activity.
563 * @category group
564 * @param stdClass $cm course module object
565 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
566 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
567 * @param bool $return return as string instead of printing
568 * @param bool $hideallparticipants If true, this prevents the 'All participants'
569 * option from appearing in cases where it normally would. This is intended for
570 * use only by activities that cannot display all groups together. (Note that
571 * selecting this option does not prevent groups_get_activity_group from
572 * returning 0; it will still do that if the user has chosen 'all participants'
573 * in another activity, or not chosen anything.)
574 * @return mixed void or string depending on $return param
576 function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
577 global $USER, $OUTPUT;
579 if ($urlroot instanceof moodle_url) {
580 // no changes necessary
582 } else {
583 if (strpos($urlroot, 'http') !== 0) { // Will also work for https
584 // Display error if urlroot is not absolute (this causes the non-JS version to break)
585 debugging('groups_print_activity_menu requires absolute URL for ' .
586 '$urlroot, not <tt>' . s($urlroot) . '</tt>. Example: ' .
587 'groups_print_activity_menu($cm, $CFG->wwwroot . \'/mod/mymodule/view.php?id=13\');',
588 DEBUG_DEVELOPER);
590 $urlroot = new moodle_url($urlroot);
593 if (!$groupmode = groups_get_activity_groupmode($cm)) {
594 if ($return) {
595 return '';
596 } else {
597 return;
601 $context = context_module::instance($cm->id);
602 $aag = has_capability('moodle/site:accessallgroups', $context);
604 if ($groupmode == VISIBLEGROUPS or $aag) {
605 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid); // any group in grouping
606 } else {
607 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); // only assigned groups
610 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
612 $groupsmenu = array();
613 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
614 $groupsmenu[0] = get_string('allparticipants');
617 if ($allowedgroups) {
618 foreach ($allowedgroups as $group) {
619 $groupsmenu[$group->id] = format_string($group->name);
623 if ($groupmode == VISIBLEGROUPS) {
624 $grouplabel = get_string('groupsvisible');
625 } else {
626 $grouplabel = get_string('groupsseparate');
629 if ($aag and $cm->groupingid) {
630 if ($grouping = groups_get_grouping($cm->groupingid)) {
631 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
635 if (count($groupsmenu) == 1) {
636 $groupname = reset($groupsmenu);
637 $output = $grouplabel.': '.$groupname;
638 } else {
639 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
640 $select->label = $grouplabel;
641 $output = $OUTPUT->render($select);
644 $output = '<div class="groupselector">'.$output.'</div>';
646 if ($return) {
647 return $output;
648 } else {
649 echo $output;
654 * Returns group active in course, changes the group by default if 'group' page param present
656 * @category group
657 * @param stdClass $course course bject
658 * @param bool $update change active group if group param submitted
659 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
660 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
662 function groups_get_course_group($course, $update=false, $allowedgroups=null) {
663 global $USER, $SESSION;
665 if (!$groupmode = $course->groupmode) {
666 // NOGROUPS used
667 return false;
670 $context = context_course::instance($course->id);
671 if (has_capability('moodle/site:accessallgroups', $context)) {
672 $groupmode = 'aag';
675 if (!is_array($allowedgroups)) {
676 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
677 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
678 } else {
679 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
683 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
685 // set new active group if requested
686 $changegroup = optional_param('group', -1, PARAM_INT);
687 if ($update and $changegroup != -1) {
689 if ($changegroup == 0) {
690 // do not allow changing to all groups without accessallgroups capability
691 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
692 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
695 } else {
696 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
697 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
702 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
706 * Returns group active in activity, changes the group by default if 'group' page param present
708 * @category group
709 * @param stdClass $cm course module object
710 * @param bool $update change active group if group param submitted
711 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
712 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
714 function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
715 global $USER, $SESSION;
717 if (!$groupmode = groups_get_activity_groupmode($cm)) {
718 // NOGROUPS used
719 return false;
722 $context = context_module::instance($cm->id);
723 if (has_capability('moodle/site:accessallgroups', $context)) {
724 $groupmode = 'aag';
727 if (!is_array($allowedgroups)) {
728 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
729 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
730 } else {
731 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
735 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
737 // set new active group if requested
738 $changegroup = optional_param('group', -1, PARAM_INT);
739 if ($update and $changegroup != -1) {
741 if ($changegroup == 0) {
742 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
743 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
744 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
747 } else {
748 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
749 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
754 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
758 * Gets a list of groups that the user is allowed to access within the
759 * specified activity.
761 * @category group
762 * @param stdClass $cm Course-module
763 * @param int $userid User ID (defaults to current user)
764 * @return array An array of group objects, or false if none
766 function groups_get_activity_allowed_groups($cm,$userid=0) {
767 // Use current user by default
768 global $USER;
769 if(!$userid) {
770 $userid=$USER->id;
773 // Get groupmode for activity, taking into account course settings
774 $groupmode=groups_get_activity_groupmode($cm);
776 // If visible groups mode, or user has the accessallgroups capability,
777 // then they can access all groups for the activity...
778 $context = context_module::instance($cm->id);
779 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context)) {
780 return groups_get_all_groups($cm->course, 0, $cm->groupingid);
781 } else {
782 // ...otherwise they can only access groups they belong to
783 return groups_get_all_groups($cm->course, $userid, $cm->groupingid);
788 * Determine if a course module is currently visible to a user
790 * $USER If $userid is null, use the global object.
792 * @category group
793 * @param stdClass $cm The course module
794 * @param int $userid The user to check against the group.
795 * @return bool True if the user can view the course module, false otherwise.
797 function groups_course_module_visible($cm, $userid=null) {
798 global $CFG, $USER;
800 if (empty($userid)) {
801 $userid = $USER->id;
803 if (empty($CFG->enablegroupmembersonly)) {
804 return true;
806 if (empty($cm->groupmembersonly)) {
807 return true;
809 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id), $userid) or groups_has_membership($cm, $userid)) {
810 return true;
812 return false;
816 * Internal method, sets up $SESSION->activegroup and verifies previous value
818 * @param int $courseid
819 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
820 * @param int $groupingid 0 means all groups
821 * @param array $allowedgroups list of groups user can see
823 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
824 global $SESSION, $USER;
826 // init activegroup array if necessary
827 if (!isset($SESSION->activegroup)) {
828 $SESSION->activegroup = array();
830 if (!array_key_exists($courseid, $SESSION->activegroup)) {
831 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
834 // make sure that the current group info is ok
835 if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
836 // active group does not exist anymore or is 0
837 if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
838 // do not do this if all groups selected and groupmode is not separate
839 unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
843 // set up defaults if necessary
844 if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
845 if ($groupmode == 'aag') {
846 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
848 } else if ($allowedgroups) {
849 if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
850 $firstgroup = reset($mygroups);
851 } else {
852 $firstgroup = reset($allowedgroups);
854 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
856 } else {
857 // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
858 // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
859 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
865 * Caches group data for a particular course to speed up subsequent requests.
867 * @param int $courseid The course id to cache data for.
868 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
869 * @return stdClass A data object containing groups, groupings, and mappings.
871 function groups_cache_groupdata($courseid, cache $cache = null) {
872 global $DB;
874 if ($cache === null) {
875 // Initialise a cache if we wern't given one.
876 $cache = cache::make('core', 'groupdata');
879 // Get the groups that belong to the course.
880 $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
881 // Get the groupings that belong to the course.
882 $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
884 if (!is_array($groups)) {
885 $groups = array();
888 if (!is_array($groupings)) {
889 $groupings = array();
892 if (!empty($groupings)) {
893 // Finally get the mappings between the two.
894 $mappings = $DB->get_records_list('groupings_groups', 'groupingid', array_keys($groupings), '', 'id,groupingid,groupid');
895 } else {
896 $mappings = array();
899 // Prepare the data array.
900 $data = new stdClass;
901 $data->groups = $groups;
902 $data->groupings = $groupings;
903 $data->mappings = $mappings;
904 // Cache the data.
905 $cache->set($courseid, $data);
906 // Finally return it so it can be used if desired.
907 return $data;
911 * Gets group data for a course.
913 * This returns an object with the following properties:
914 * - groups : An array of all the groups in the course.
915 * - groupings : An array of all the groupings within the course.
916 * - mappings : An array of group to grouping mappings.
918 * @param int $courseid The course id to get data for.
919 * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
920 * @return stdClass
922 function groups_get_course_data($courseid, cache $cache = null) {
923 if ($cache === null) {
924 // Initialise a cache if we wern't given one.
925 $cache = cache::make('core', 'groupdata');
927 // Try to retrieve it from the cache.
928 $data = $cache->get($courseid);
929 if ($data === false) {
930 $data = groups_cache_groupdata($courseid, $cache);
932 return $data;