528bf5819afbfb8f64dde9e149abfeafe04a5ff0
[moodle.git] / lib / grouplib.php
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.
14 //
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
22  */
24 defined('MOODLE_INTERNAL') || die();
26 /**
27  * Groups not used in course or activity
28  */
29 define('NOGROUPS', 0);
31 /**
32  * Groups used, users do not see other groups
33  */
34 define('SEPARATEGROUPS', 1);
36 /**
37  * Groups used, students see other groups
38  */
39 define('VISIBLEGROUPS', 2);
42 /**
43  * Determines if a group with a given groupid exists.
44  *
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.
49  */
50 function groups_group_exists($groupid) {
51     global $DB;
52     return $DB->record_exists('groups', array('id'=>$groupid));
53 }
55 /**
56  * Gets the name of a group with a specified id
57  *
58  * @category group
59  * @param int $groupid The id of the group
60  * @return string The name of the group
61  */
62 function groups_get_group_name($groupid) {
63     global $DB;
64     return $DB->get_field('groups', 'name', array('id'=>$groupid));
65 }
67 /**
68  * Gets the name of a grouping with a specified id
69  *
70  * @category group
71  * @param int $groupingid The id of the grouping
72  * @return string The name of the grouping
73  */
74 function groups_get_grouping_name($groupingid) {
75     global $DB;
76     return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
77 }
79 /**
80  * Returns the groupid of a group with the name specified for the course.
81  * Group names should be unique in course
82  *
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
87  */
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;
93         }
94     }
95     return false;
96 }
98 /**
99  * Returns the groupid of a group with the idnumber specified for the course.
100  * Group idnumbers should be unique within course
101  *
102  * @category group
103  * @param int $courseid The id of the course
104  * @param string $idnumber idnumber of group
105  * @return group object
106  */
107 function groups_get_group_by_idnumber($courseid, $idnumber) {
108     if (empty($idnumber)) {
109         return false;
110     }
111     $data = groups_get_course_data($courseid);
112     foreach ($data->groups as $group) {
113         if ($group->idnumber == $idnumber) {
114             return $group;
115         }
116     }
117     return false;
120 /**
121  * Returns the groupingid of a grouping with the name specified for the course.
122  * Grouping names should be unique in course
123  *
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
128  */
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;
134         }
135     }
136     return false;
139 /**
140  * Returns the groupingid of a grouping with the idnumber specified for the course.
141  * Grouping names should be unique within course
142  *
143  * @category group
144  * @param int $courseid The id of the course
145  * @param string $idnumber idnumber of the group
146  * @return grouping object
147  */
148 function groups_get_grouping_by_idnumber($courseid, $idnumber) {
149     if (empty($idnumber)) {
150         return false;
151     }
152     $data = groups_get_course_data($courseid);
153     foreach ($data->groupings as $grouping) {
154         if ($grouping->idnumber == $idnumber) {
155             return $grouping;
156         }
157     }
158     return false;
161 /**
162  * Get the group object
163  *
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
169  */
170 function groups_get_group($groupid, $fields='*', $strictness=IGNORE_MISSING) {
171     global $DB;
172     return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
175 /**
176  * Get the grouping object
177  *
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
183  */
184 function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING) {
185     global $DB;
186     return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
189 /**
190  * Gets array of all groups in a specified course.
191  *
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)
198  */
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;
212             }
213         }
214     }
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;
227                 }
228                 if (isset($data->groups[$mapping->groupid])) {
229                     $groups[$mapping->groupid] = $data->groups[$mapping->groupid];
230                 }
231             }
232         }
233         // Yay! We could use the cache. One more query saved.
234         return $groups;
235     }
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";
247     }
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 = "";
256     }
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);
267 /**
268  * Gets array of all groups in current user.
269  *
270  * @since Moodle 2.5
271  * @category group
272  * @return array Returns an array of the group objects.
273  */
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));
284 /**
285  * Returns info about user's groups in course.
286  *
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
291  */
292 function groups_get_user_groups($courseid, $userid=0) {
293     global $USER, $DB;
295     if (empty($userid)) {
296         $userid = $USER->id;
297     }
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());
311     }
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;
320         }
321         if (!array_key_exists($group->groupingid, $result)) {
322             $result[$group->groupingid] = array();
323         }
324         $result[$group->groupingid][$group->id] = $group->id;
325     }
326     $rs->close();
328     $result['0'] = array_keys($allgroups); // all groups
330     return $result;
333 /**
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).
337  *
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)
341  */
342 function groups_get_all_groupings($courseid) {
343     $data = groups_get_course_data($courseid);
344     return $data->groupings;
347 /**
348  * Determines if the user is a member of the given group.
349  *
350  * If $userid is null, use the global object.
351  *
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.
356  */
357 function groups_is_member($groupid, $userid=null) {
358     global $USER, $DB;
360     if (!$userid) {
361         $userid = $USER->id;
362     }
364     return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
367 /**
368  * Determines if current or specified is member of any active group in activity
369  *
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
375  */
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;
383     }
385     $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
386     if (isset($cache[$cachekey])) {
387         return($cache[$cachekey]);
388     }
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);
403     }
405     $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
407     return $cache[$cachekey];
410 /**
411  * Returns the users in the specified group.
412  *
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.
419  */
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));
430 /**
431  * Returns the users in the specified grouping.
432  *
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.
439  */
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));
451 /**
452  * Returns effective groupmode used in course
453  *
454  * @category group
455  * @param stdClass $course course object.
456  * @return int group mode
457  */
458 function groups_get_course_groupmode($course) {
459     return $course->groupmode;
462 /**
463  * Returns effective groupmode used in activity, course setting
464  * overrides activity setting if groupmodeforce enabled.
465  *
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
470  */
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');
482         }
483     }
485     return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
488 /**
489  * Print group menu selector for course level.
490  *
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
496  */
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;
505         }
506     }
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);
515     }
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');
522     }
524     if ($allowedgroups) {
525         foreach ($allowedgroups as $group) {
526             $groupsmenu[$group->id] = format_string($group->name);
527         }
528     }
530     if ($groupmode == VISIBLEGROUPS) {
531         $grouplabel = get_string('groupsvisible');
532     } else {
533         $grouplabel = get_string('groupsseparate');
534     }
536     if ($aag and $course->defaultgroupingid) {
537         if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
538             $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
539         }
540     }
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);
549     }
551     $output = '<div class="groupselector">'.$output.'</div>';
553     if ($return) {
554         return $output;
555     } else {
556         echo $output;
557     }
560 /**
561  * Print group menu selector for activity.
562  *
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
575  */
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);
589         }
590         $urlroot = new moodle_url($urlroot);
591     }
593     if (!$groupmode = groups_get_activity_groupmode($cm)) {
594         if ($return) {
595             return '';
596         } else {
597             return;
598         }
599     }
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
608     }
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');
615     }
617     if ($allowedgroups) {
618         foreach ($allowedgroups as $group) {
619             $groupsmenu[$group->id] = format_string($group->name);
620         }
621     }
623     if ($groupmode == VISIBLEGROUPS) {
624         $grouplabel = get_string('groupsvisible');
625     } else {
626         $grouplabel = get_string('groupsseparate');
627     }
629     if ($aag and $cm->groupingid) {
630         if ($grouping = groups_get_grouping($cm->groupingid)) {
631             $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
632         }
633     }
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);
642     }
644     $output = '<div class="groupselector">'.$output.'</div>';
646     if ($return) {
647         return $output;
648     } else {
649         echo $output;
650     }
653 /**
654  * Returns group active in course, changes the group by default if 'group' page param present
655  *
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)
661  */
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;
668     }
670     $context = context_course::instance($course->id);
671     if (has_capability('moodle/site:accessallgroups', $context)) {
672         $groupmode = 'aag';
673     }
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);
680         }
681     }
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;
693             }
695         } else {
696             if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
697                 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
698             }
699         }
700     }
702     return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
705 /**
706  * Returns group active in activity, changes the group by default if 'group' page param present
707  *
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)
713  */
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;
720     }
722     $context = context_module::instance($cm->id);
723     if (has_capability('moodle/site:accessallgroups', $context)) {
724         $groupmode = 'aag';
725     }
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);
732         }
733     }
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;
745             }
747         } else {
748             if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
749                 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
750             }
751         }
752     }
754     return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
757 /**
758  * Gets a list of groups that the user is allowed to access within the
759  * specified activity.
760  *
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
765  */
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;
771     }
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, $userid)) {
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);
784     }
787 /**
788  * Determine if a course module is currently visible to a user
789  *
790  * $USER If $userid is null, use the global object.
791  *
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.
796  */
797 function groups_course_module_visible($cm, $userid=null) {
798     global $CFG, $USER;
800     if (empty($userid)) {
801         $userid = $USER->id;
802     }
803     if (empty($CFG->enablegroupmembersonly)) {
804         return true;
805     }
806     if (empty($cm->groupmembersonly)) {
807         return true;
808     }
809     if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id), $userid) or groups_has_membership($cm, $userid)) {
810         return true;
811     }
812     return false;
815 /**
816  * Determine if a given group is visible to user or not in a given context.
817  *
818  * @since Moodle 2.6
819  * @param int      $groupid Group id to test. 0 for all groups.
820  * @param stdClass $course  Course object.
821  * @param stdClass $cm      Course module object.
822  * @param int      $userid  user id to test against. Defaults to $USER.
823  * @return boolean true if visible, false otherwise
824  */
825 function groups_group_visible($groupid, $course, $cm = null, $userid = null) {
826     global $USER;
828     if (empty($userid)) {
829         $userid = $USER->id;
830     }
832     $groupmode = empty($cm) ? groups_get_course_groupmode($course) : groups_get_activity_groupmode($cm, $course);
833     if ($groupmode == NOGROUPS || $groupmode == VISIBLEGROUPS) {
834         // Groups are not used, or everything is visible, no need to go any further.
835         return true;
836     }
838     $context = empty($cm) ? context_course::instance($course->id) : context_module::instance($cm->id);
839     if (has_capability('moodle/site:accessallgroups', $context, $userid)) {
840         // User can see everything. Groupid = 0 is handled here as well.
841         return true;
842     } else if ($groupid != 0) {
843         // Group mode is separate, and user doesn't have access all groups capability. Check if user can see requested group.
844         $groups = empty($cm) ? groups_get_all_groups($course->id, $userid) : groups_get_activity_allowed_groups($cm, $userid);
845         if (array_key_exists($groupid, $groups)) {
846             // User can see the group.
847             return true;
848         }
849     }
850     return false;
853 /**
854  * Internal method, sets up $SESSION->activegroup and verifies previous value
855  *
856  * @param int $courseid
857  * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
858  * @param int $groupingid 0 means all groups
859  * @param array $allowedgroups list of groups user can see
860  */
861 function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
862     global $SESSION, $USER;
864     // init activegroup array if necessary
865     if (!isset($SESSION->activegroup)) {
866         $SESSION->activegroup = array();
867     }
868     if (!array_key_exists($courseid, $SESSION->activegroup)) {
869         $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
870     }
872     // make sure that the current group info is ok
873     if (array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode]) and !array_key_exists($SESSION->activegroup[$courseid][$groupmode][$groupingid], $allowedgroups)) {
874         // active group does not exist anymore or is 0
875         if ($SESSION->activegroup[$courseid][$groupmode][$groupingid] > 0 or $groupmode == SEPARATEGROUPS) {
876             // do not do this if all groups selected and groupmode is not separate
877             unset($SESSION->activegroup[$courseid][$groupmode][$groupingid]);
878         }
879     }
881     // set up defaults if necessary
882     if (!array_key_exists($groupingid, $SESSION->activegroup[$courseid][$groupmode])) {
883         if ($groupmode == 'aag') {
884             $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0; // all groups by default if user has accessallgroups
886         } else if ($allowedgroups) {
887             if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
888                 $firstgroup = reset($mygroups);
889             } else {
890                 $firstgroup = reset($allowedgroups);
891             }
892             $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
894         } else {
895             // this happen when user not assigned into group in SEPARATEGROUPS mode or groups do not exist yet
896             // mod authors must add extra checks for this when SEPARATEGROUPS mode used (such as when posting to forum)
897             $SESSION->activegroup[$courseid][$groupmode][$groupingid] = 0;
898         }
899     }
902 /**
903  * Caches group data for a particular course to speed up subsequent requests.
904  *
905  * @param int $courseid The course id to cache data for.
906  * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
907  * @return stdClass A data object containing groups, groupings, and mappings.
908  */
909 function groups_cache_groupdata($courseid, cache $cache = null) {
910     global $DB;
912     if ($cache === null) {
913         // Initialise a cache if we wern't given one.
914         $cache = cache::make('core', 'groupdata');
915     }
917     // Get the groups that belong to the course.
918     $groups = $DB->get_records('groups', array('courseid' => $courseid), 'name ASC');
919     // Get the groupings that belong to the course.
920     $groupings = $DB->get_records('groupings', array('courseid' => $courseid), 'name ASC');
922     if (!is_array($groups)) {
923         $groups = array();
924     }
926     if (!is_array($groupings)) {
927         $groupings = array();
928     }
930     if (!empty($groupings)) {
931         // Finally get the mappings between the two.
932         $mappings = $DB->get_records_list('groupings_groups', 'groupingid', array_keys($groupings), '', 'id,groupingid,groupid');
933     } else {
934         $mappings = array();
935     }
937     // Prepare the data array.
938     $data = new stdClass;
939     $data->groups = $groups;
940     $data->groupings = $groupings;
941     $data->mappings = $mappings;
942     // Cache the data.
943     $cache->set($courseid, $data);
944     // Finally return it so it can be used if desired.
945     return $data;
948 /**
949  * Gets group data for a course.
950  *
951  * This returns an object with the following properties:
952  *   - groups : An array of all the groups in the course.
953  *   - groupings : An array of all the groupings within the course.
954  *   - mappings : An array of group to grouping mappings.
955  *
956  * @param int $courseid The course id to get data for.
957  * @param cache $cache The cache if it has already been initialised. If not a new one will be created.
958  * @return stdClass
959  */
960 function groups_get_course_data($courseid, cache $cache = null) {
961     if ($cache === null) {
962         // Initialise a cache if we wern't given one.
963         $cache = cache::make('core', 'groupdata');
964     }
965     // Try to retrieve it from the cache.
966     $data = $cache->get($courseid);
967     if ($data === false) {
968         $data = groups_cache_groupdata($courseid, $cache);
969     }
970     return $data;