MDL-40354 groups: Add unit tests for the api groups_group_visible()
[moodle.git] / lib / grouplib.php
CommitLineData
e4f0a85e 1<?php
2
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/>.
17
18/**
78bfb562
PS
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4d8e2417 21 * @package core_group
e4f0a85e 22 */
2c386f82 23
78bfb562
PS
24defined('MOODLE_INTERNAL') || die();
25
13534ef7 26/**
ffc536af 27 * Groups not used in course or activity
13534ef7
ML
28 */
29define('NOGROUPS', 0);
30
31/**
ffc536af 32 * Groups used, users do not see other groups
13534ef7
ML
33 */
34define('SEPARATEGROUPS', 1);
5bf243d1 35
5bf243d1 36/**
ffc536af 37 * Groups used, students see other groups
13534ef7
ML
38 */
39define('VISIBLEGROUPS', 2);
40
41
42/**
43 * Determines if a group with a given groupid exists.
e4f0a85e 44 *
4d8e2417 45 * @category group
5bf243d1 46 * @param int $groupid The groupid to check for
4d8e2417 47 * @return bool True if the group exists, false otherwise or if an error
13534ef7 48 * occurred.
5bf243d1 49 */
50function groups_group_exists($groupid) {
f33e1ed4 51 global $DB;
52 return $DB->record_exists('groups', array('id'=>$groupid));
5bf243d1 53}
54
55/**
56 * Gets the name of a group with a specified id
e4f0a85e 57 *
4d8e2417 58 * @category group
5bf243d1 59 * @param int $groupid The id of the group
60 * @return string The name of the group
61 */
62function groups_get_group_name($groupid) {
f33e1ed4 63 global $DB;
64 return $DB->get_field('groups', 'name', array('id'=>$groupid));
5bf243d1 65}
2c386f82 66
4d8e3407 67/**
68 * Gets the name of a grouping with a specified id
e4f0a85e 69 *
4d8e2417 70 * @category group
4d8e3407 71 * @param int $groupingid The id of the grouping
72 * @return string The name of the grouping
73 */
74function groups_get_grouping_name($groupingid) {
f33e1ed4 75 global $DB;
76 return $DB->get_field('groupings', 'name', array('id'=>$groupingid));
4d8e3407 77}
78
2c386f82 79/**
80 * Returns the groupid of a group with the name specified for the course.
81 * Group names should be unique in course
e4f0a85e 82 *
4d8e2417 83 * @category group
2c386f82 84 * @param int $courseid The id of the course
85 * @param string $name name of group (without magic quotes)
86 * @return int $groupid
87 */
88function groups_get_group_by_name($courseid, $name) {
e17dbeeb
SH
89 $data = groups_get_course_data($courseid);
90 foreach ($data->groups as $group) {
91 if ($group->name == $name) {
92 return $group->id;
93 }
2c386f82 94 }
ddff2fa8 95 return false;
96}
2c386f82 97
74b714df
ARN
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 */
107function groups_get_group_by_idnumber($courseid, $idnumber) {
74b714df
ARN
108 if (empty($idnumber)) {
109 return false;
e17dbeeb
SH
110 }
111 $data = groups_get_course_data($courseid);
112 foreach ($data->groups as $group) {
113 if ($group->idnumber == $idnumber) {
114 return $group;
115 }
74b714df
ARN
116 }
117 return false;
118}
119
ddff2fa8 120/**
121 * Returns the groupingid of a grouping with the name specified for the course.
122 * Grouping names should be unique in course
e4f0a85e 123 *
4d8e2417 124 * @category group
ddff2fa8 125 * @param int $courseid The id of the course
126 * @param string $name name of group (without magic quotes)
127 * @return int $groupid
128 */
129function groups_get_grouping_by_name($courseid, $name) {
e17dbeeb
SH
130 $data = groups_get_course_data($courseid);
131 foreach ($data->groupings as $grouping) {
132 if ($grouping->name == $name) {
133 return $grouping->id;
134 }
ddff2fa8 135 }
136 return false;
2c386f82 137}
138
74b714df
ARN
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 */
148function groups_get_grouping_by_idnumber($courseid, $idnumber) {
74b714df
ARN
149 if (empty($idnumber)) {
150 return false;
e17dbeeb
SH
151 }
152 $data = groups_get_course_data($courseid);
153 foreach ($data->groupings as $grouping) {
154 if ($grouping->idnumber == $idnumber) {
155 return $grouping;
156 }
74b714df
ARN
157 }
158 return false;
159}
160
2c386f82 161/**
162 * Get the group object
e4f0a85e 163 *
4d8e2417 164 * @category group
e4f0a85e 165 * @param int $groupid ID of the group.
4d8e2417
AG
166 * @param string $fields (default is all fields)
167 * @param int $strictness (IGNORE_MISSING - default)
168 * @return stdGlass group object
2c386f82 169 */
9a0df45a 170function groups_get_group($groupid, $fields='*', $strictness=IGNORE_MISSING) {
f33e1ed4 171 global $DB;
9a0df45a 172 return $DB->get_record('groups', array('id'=>$groupid), $fields, $strictness);
2c386f82 173}
174
f16fa0a3 175/**
176 * Get the grouping object
e4f0a85e 177 *
4d8e2417 178 * @category group
e4f0a85e 179 * @param int $groupingid ID of the group.
9a0df45a 180 * @param string $fields
4d8e2417
AG
181 * @param int $strictness (IGNORE_MISSING - default)
182 * @return stdClass group object
f16fa0a3 183 */
9a0df45a 184function groups_get_grouping($groupingid, $fields='*', $strictness=IGNORE_MISSING) {
f33e1ed4 185 global $DB;
9a0df45a 186 return $DB->get_record('groupings', array('id'=>$groupingid), $fields, $strictness);
f16fa0a3 187}
188
2c386f82 189/**
190 * Gets array of all groups in a specified course.
e4f0a85e 191 *
4d8e2417 192 * @category group
2c386f82 193 * @param int $courseid The id of the course.
65bcf17b 194 * @param mixed $userid optional user id or array of ids, returns only groups of the user.
62d63838 195 * @param int $groupingid optional returns only groups in the specified grouping.
e4f0a85e 196 * @param string $fields
998ced08 197 * @return array Returns an array of the group objects (userid field returned if array in $userid)
2c386f82 198 */
65bcf17b 199function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*') {
998ced08 200 global $DB;
2c386f82 201
e17dbeeb
SH
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 }
215
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 }
236
237
65bcf17b 238 if (empty($userid)) {
62d63838 239 $userfrom = "";
240 $userwhere = "";
f33e1ed4 241 $params = array();
65bcf17b 242
243 } else {
f33e1ed4 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";
62d63838 247 }
2c386f82 248
62d63838 249 if (!empty($groupingid)) {
f33e1ed4 250 $groupingfrom = ", {groupings_groups} gg";
251 $groupingwhere = "AND g.id = gg.groupid AND gg.groupingid = ?";
252 $params[] = $groupingid;
2c386f82 253 } else {
62d63838 254 $groupingfrom = "";
255 $groupingwhere = "";
2c386f82 256 }
62d63838 257
f33e1ed4 258 array_unshift($params, $courseid);
259
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);
2c386f82 264}
265
475896bd
AA
266
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 */
274function 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));
282}
283
dd97c328 284/**
285 * Returns info about user's groups in course.
e4f0a85e 286 *
4d8e2417 287 * @category group
dd97c328 288 * @param int $courseid
289 * @param int $userid $USER if not specified
e4f0a85e 290 * @return array Array[groupingid][groupid] including grouping id 0 which means all groups
dd97c328 291 */
292function groups_get_user_groups($courseid, $userid=0) {
998ced08 293 global $USER, $DB;
dd97c328 294
295 if (empty($userid)) {
296 $userid = $USER->id;
297 }
298
f33e1ed4 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);
305
b967c541
EL
306 $rs = $DB->get_recordset_sql($sql, $params);
307
308 if (!$rs->valid()) {
309 $rs->close(); // Not going to iterate (but exit), close rs
dd97c328 310 return array('0' => array());
311 }
312
0b943ef1 313 $result = array();
314 $allgroups = array();
117bd748 315
f33e1ed4 316 foreach ($rs as $group) {
ca182d90 317 $allgroups[$group->id] = $group->id;
dd97c328 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 }
f33e1ed4 326 $rs->close();
0b943ef1 327
328 $result['0'] = array_keys($allgroups); // all groups
dd97c328 329
330 return $result;
331}
332
acf000b0 333/**
ae3fbf7b 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).
117bd748 337 *
4d8e2417 338 * @category group
ae3fbf7b 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)
acf000b0 341 */
342function groups_get_all_groupings($courseid) {
e17dbeeb
SH
343 $data = groups_get_course_data($courseid);
344 return $data->groupings;
acf000b0 345}
346
2c386f82 347/**
348 * Determines if the user is a member of the given group.
349 *
aaeba371 350 * If $userid is null, use the global object.
351 *
4d8e2417 352 * @category group
2c386f82 353 * @param int $groupid The group to check for membership.
354 * @param int $userid The user to check against the group.
4d8e2417 355 * @return bool True if the user is a member, false otherwise.
2c386f82 356 */
357function groups_is_member($groupid, $userid=null) {
f33e1ed4 358 global $USER, $DB;
2c386f82 359
360 if (!$userid) {
361 $userid = $USER->id;
362 }
363
f33e1ed4 364 return $DB->record_exists('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
2c386f82 365}
366
f8e3d5f0 367/**
368 * Determines if current or specified is member of any active group in activity
e4f0a85e 369 *
4d8e2417 370 * @category group
e4f0a85e 371 * @staticvar array $cache
4d8e2417
AG
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
f8e3d5f0 375 */
376function groups_has_membership($cm, $userid=null) {
f33e1ed4 377 global $CFG, $USER, $DB;
f16fa0a3 378
e0bc99e4 379 static $cache = array();
f16fa0a3 380
f8e3d5f0 381 if (empty($userid)) {
382 $userid = $USER->id;
383 }
384
e0bc99e4 385 $cachekey = $userid.'|'.$cm->course.'|'.$cm->groupingid;
386 if (isset($cache[$cachekey])) {
387 return($cache[$cachekey]);
388 }
389
f8e3d5f0 390 if ($cm->groupingid) {
391 // find out if member of any group in selected activity grouping
392 $sql = "SELECT 'x'
f33e1ed4 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);
f8e3d5f0 396
397 } else {
398 // no grouping used - check all groups in course
399 $sql = "SELECT 'x'
f33e1ed4 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);
f8e3d5f0 403 }
f16fa0a3 404
f33e1ed4 405 $cache[$cachekey] = $DB->record_exists_sql($sql, $params);
f16fa0a3 406
e0bc99e4 407 return $cache[$cachekey];
f8e3d5f0 408}
409
62d63838 410/**
411 * Returns the users in the specified group.
e4f0a85e 412 *
4d8e2417 413 * @category group
62d63838 414 * @param int $groupid The groupid to get the users for
e6839677 415 * @param int $fields The fields to return
62d63838 416 * @param int $sort optional sorting of returned users
e4f0a85e 417 * @return array|bool Returns an array of the users for the specified
62d63838 418 * group or false if no users or an error returned.
419 */
e6839677 420function groups_get_members($groupid, $fields='u.*', $sort='lastname ASC') {
f33e1ed4 421 global $DB;
62d63838 422
f33e1ed4 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));
62d63838 427}
428
e6839677 429
430/**
431 * Returns the users in the specified grouping.
e4f0a85e 432 *
4d8e2417 433 * @category group
e6839677 434 * @param int $groupingid The groupingid to get the users for
4d8e2417
AG
435 * @param string $fields The fields to return
436 * @param string $sort optional sorting of returned users
e4f0a85e 437 * @return array|bool Returns an array of the users for the specified
e6839677 438 * group or false if no users or an error returned.
439 */
440function groups_get_grouping_members($groupingid, $fields='u.*', $sort='lastname ASC') {
f33e1ed4 441 global $DB;
442
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));
e6839677 449}
450
b2bc96d1 451/**
452 * Returns effective groupmode used in course
117bd748 453 *
4d8e2417
AG
454 * @category group
455 * @param stdClass $course course object.
456 * @return int group mode
b2bc96d1 457 */
458function groups_get_course_groupmode($course) {
459 return $course->groupmode;
460}
461
13534ef7
ML
462/**
463 * Returns effective groupmode used in activity, course setting
464 * overrides activity setting if groupmodeforce enabled.
e4f0a85e 465 *
4d8e2417
AG
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
13534ef7 470 */
dd97c328 471function groups_get_activity_groupmode($cm, $course=null) {
f33e1ed4 472 global $COURSE, $DB;
13534ef7
ML
473
474 // get course object (reuse COURSE if possible)
dd97c328 475 if (isset($course->id) and $course->id == $cm->course) {
476 //ok
477 } else if ($cm->course == $COURSE->id) {
13534ef7
ML
478 $course = $COURSE;
479 } else {
f33e1ed4 480 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
06e84d52 481 print_error('invalidcourseid');
13534ef7
ML
482 }
483 }
484
485 return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
486}
487
b2bc96d1 488/**
489 * Print group menu selector for course level.
e4f0a85e 490 *
4d8e2417 491 * @category group
998ced08 492 * @param stdClass $course course object
4d8e2417
AG
493 * @param mixed $urlroot return address. Accepts either a string or a moodle_url
494 * @param bool $return return as string instead of printing
b2bc96d1 495 * @return mixed void or string depending on $return param
496 */
497function groups_print_course_menu($course, $urlroot, $return=false) {
998ced08 498 global $USER, $OUTPUT;
b2bc96d1 499
500 if (!$groupmode = $course->groupmode) {
501 if ($return) {
502 return '';
503 } else {
504 return;
505 }
506 }
1d57f862 507
b0c6dc1c 508 $context = context_course::instance($course->id);
998ced08 509 $aag = has_capability('moodle/site:accessallgroups', $context);
1d57f862 510
998ced08
PS
511 if ($groupmode == VISIBLEGROUPS or $aag) {
512 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
1d57f862
PS
513 } else {
514 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
1d57f862 515 }
b2bc96d1 516
998ced08 517 $activegroup = groups_get_course_group($course, true, $allowedgroups);
b2bc96d1 518
519 $groupsmenu = array();
998ced08 520 if (!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) {
b2bc96d1 521 $groupsmenu[0] = get_string('allparticipants');
522 }
523
524 if ($allowedgroups) {
525 foreach ($allowedgroups as $group) {
526 $groupsmenu[$group->id] = format_string($group->name);
527 }
528 }
529
530 if ($groupmode == VISIBLEGROUPS) {
531 $grouplabel = get_string('groupsvisible');
532 } else {
533 $grouplabel = get_string('groupsseparate');
534 }
535
998ced08
PS
536 if ($aag and $course->defaultgroupingid) {
537 if ($grouping = groups_get_grouping($course->defaultgroupingid)) {
538 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
539 }
540 }
541
b2bc96d1 542 if (count($groupsmenu) == 1) {
543 $groupname = reset($groupsmenu);
544 $output = $grouplabel.': '.$groupname;
545 } else {
f8dab966
PS
546 $select = new single_select(new moodle_url($urlroot), 'group', $groupsmenu, $activegroup, null, 'selectgroup');
547 $select->label = $grouplabel;
548 $output = $OUTPUT->render($select);
b2bc96d1 549 }
550
551 $output = '<div class="groupselector">'.$output.'</div>';
552
553 if ($return) {
554 return $output;
555 } else {
556 echo $output;
557 }
558}
559
13534ef7
ML
560/**
561 * Print group menu selector for activity.
e4f0a85e 562 *
4d8e2417 563 * @category group
998ced08
PS
564 * @param stdClass $cm course module object
565 * @param string|moodle_url $urlroot return address that users get to if they choose an option;
f1035deb 566 * should include any parameters needed, e.g. "$CFG->wwwroot/mod/forum/view.php?id=34"
4d8e2417
AG
567 * @param bool $return return as string instead of printing
568 * @param bool $hideallparticipants If true, this prevents the 'All participants'
f16fa0a3 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.)
13534ef7
ML
574 * @return mixed void or string depending on $return param
575 */
18d43e96 576function groups_print_activity_menu($cm, $urlroot, $return=false, $hideallparticipants=false) {
998ced08 577 global $USER, $OUTPUT;
c0d4238d 578
998ced08
PS
579 if ($urlroot instanceof moodle_url) {
580 // no changes necessary
581
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);
f1035deb
SM
591 }
592
13534ef7
ML
593 if (!$groupmode = groups_get_activity_groupmode($cm)) {
594 if ($return) {
595 return '';
596 } else {
597 return;
598 }
599 }
1d57f862 600
b0c6dc1c 601 $context = context_module::instance($cm->id);
998ced08 602 $aag = has_capability('moodle/site:accessallgroups', $context);
1d57f862 603
998ced08
PS
604 if ($groupmode == VISIBLEGROUPS or $aag) {
605 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid); // any group in grouping
1d57f862
PS
606 } else {
607 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid); // only assigned groups
1d57f862
PS
608 }
609
998ced08 610 $activegroup = groups_get_activity_group($cm, true, $allowedgroups);
13534ef7
ML
611
612 $groupsmenu = array();
998ced08 613 if ((!$allowedgroups or $groupmode == VISIBLEGROUPS or $aag) and !$hideallparticipants) {
13534ef7
ML
614 $groupsmenu[0] = get_string('allparticipants');
615 }
616
617 if ($allowedgroups) {
618 foreach ($allowedgroups as $group) {
619 $groupsmenu[$group->id] = format_string($group->name);
620 }
621 }
622
623 if ($groupmode == VISIBLEGROUPS) {
624 $grouplabel = get_string('groupsvisible');
625 } else {
626 $grouplabel = get_string('groupsseparate');
627 }
628
998ced08
PS
629 if ($aag and $cm->groupingid) {
630 if ($grouping = groups_get_grouping($cm->groupingid)) {
631 $grouplabel = $grouplabel . ' (' . format_string($grouping->name) . ')';
632 }
633 }
634
13534ef7
ML
635 if (count($groupsmenu) == 1) {
636 $groupname = reset($groupsmenu);
637 $output = $grouplabel.': '.$groupname;
638 } else {
998ced08 639 $select = new single_select($urlroot, 'group', $groupsmenu, $activegroup, null, 'selectgroup');
f8dab966
PS
640 $select->label = $grouplabel;
641 $output = $OUTPUT->render($select);
13534ef7
ML
642 }
643
644 $output = '<div class="groupselector">'.$output.'</div>';
645
646 if ($return) {
647 return $output;
648 } else {
649 echo $output;
650 }
651}
652
b2bc96d1 653/**
654 * Returns group active in course, changes the group by default if 'group' page param present
655 *
4d8e2417 656 * @category group
998ced08 657 * @param stdClass $course course bject
4d8e2417 658 * @param bool $update change active group if group param submitted
998ced08 659 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_course_menu())
b2bc96d1 660 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
661 */
998ced08
PS
662function groups_get_course_group($course, $update=false, $allowedgroups=null) {
663 global $USER, $SESSION;
b2bc96d1 664
665 if (!$groupmode = $course->groupmode) {
666 // NOGROUPS used
667 return false;
668 }
669
b0c6dc1c 670 $context = context_course::instance($course->id);
1d57f862 671 if (has_capability('moodle/site:accessallgroups', $context)) {
b0dcd128 672 $groupmode = 'aag';
b2bc96d1 673 }
674
998ced08
PS
675 if (!is_array($allowedgroups)) {
676 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
677 $allowedgroups = groups_get_all_groups($course->id, 0, $course->defaultgroupingid);
b2bc96d1 678 } else {
998ced08 679 $allowedgroups = groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid);
b2bc96d1 680 }
681 }
682
998ced08
PS
683 _group_verify_activegroup($course->id, $groupmode, $course->defaultgroupingid, $allowedgroups);
684
b2bc96d1 685 // set new active group if requested
686 $changegroup = optional_param('group', -1, PARAM_INT);
687 if ($update and $changegroup != -1) {
b2bc96d1 688
689 if ($changegroup == 0) {
690 // do not allow changing to all groups without accessallgroups capability
998ced08
PS
691 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
692 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = 0;
b2bc96d1 693 }
694
695 } else {
b2bc96d1 696 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
998ced08 697 $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid] = $changegroup;
b2bc96d1 698 }
699 }
700 }
701
998ced08 702 return $SESSION->activegroup[$course->id][$groupmode][$course->defaultgroupingid];
b2bc96d1 703}
704
13534ef7
ML
705/**
706 * Returns group active in activity, changes the group by default if 'group' page param present
707 *
4d8e2417 708 * @category group
998ced08 709 * @param stdClass $cm course module object
4d8e2417 710 * @param bool $update change active group if group param submitted
998ced08 711 * @param array $allowedgroups list of groups user may access (INTERNAL, to be used only from groups_print_activity_menu())
13534ef7
ML
712 * @return mixed false if groups not used, int if groups used, 0 means all groups (access must be verified in SEPARATE mode)
713 */
998ced08
PS
714function groups_get_activity_group($cm, $update=false, $allowedgroups=null) {
715 global $USER, $SESSION;
c0d4238d 716
13534ef7
ML
717 if (!$groupmode = groups_get_activity_groupmode($cm)) {
718 // NOGROUPS used
719 return false;
720 }
721
b0c6dc1c 722 $context = context_module::instance($cm->id);
1d57f862 723 if (has_capability('moodle/site:accessallgroups', $context)) {
b0dcd128 724 $groupmode = 'aag';
13534ef7
ML
725 }
726
998ced08
PS
727 if (!is_array($allowedgroups)) {
728 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
729 $allowedgroups = groups_get_all_groups($cm->course, 0, $cm->groupingid);
13534ef7 730 } else {
998ced08 731 $allowedgroups = groups_get_all_groups($cm->course, $USER->id, $cm->groupingid);
13534ef7
ML
732 }
733 }
734
998ced08
PS
735 _group_verify_activegroup($cm->course, $groupmode, $cm->groupingid, $allowedgroups);
736
13534ef7
ML
737 // set new active group if requested
738 $changegroup = optional_param('group', -1, PARAM_INT);
739 if ($update and $changegroup != -1) {
13534ef7
ML
740
741 if ($changegroup == 0) {
b0dcd128 742 // allgroups visible only in VISIBLEGROUPS or when accessallgroups
998ced08 743 if ($groupmode == VISIBLEGROUPS or $groupmode === 'aag') {
13534ef7
ML
744 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = 0;
745 }
746
747 } else {
13534ef7
ML
748 if ($allowedgroups and array_key_exists($changegroup, $allowedgroups)) {
749 $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid] = $changegroup;
750 }
751 }
752 }
753
754 return $SESSION->activegroup[$cm->course][$groupmode][$cm->groupingid];
755}
62d63838 756
18d43e96 757/**
f16fa0a3 758 * Gets a list of groups that the user is allowed to access within the
18d43e96 759 * specified activity.
e4f0a85e 760 *
4d8e2417
AG
761 * @category group
762 * @param stdClass $cm Course-module
18d43e96 763 * @param int $userid User ID (defaults to current user)
764 * @return array An array of group objects, or false if none
765 */
cdaa9410 766function groups_get_activity_allowed_groups($cm,$userid=0) {
18d43e96 767 // Use current user by default
768 global $USER;
769 if(!$userid) {
770 $userid=$USER->id;
771 }
f16fa0a3 772
18d43e96 773 // Get groupmode for activity, taking into account course settings
774 $groupmode=groups_get_activity_groupmode($cm);
775
776 // If visible groups mode, or user has the accessallgroups capability,
777 // then they can access all groups for the activity...
b0c6dc1c 778 $context = context_module::instance($cm->id);
18d43e96 779 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context)) {
f16fa0a3 780 return groups_get_all_groups($cm->course, 0, $cm->groupingid);
18d43e96 781 } else {
782 // ...otherwise they can only access groups they belong to
f16fa0a3 783 return groups_get_all_groups($cm->course, $userid, $cm->groupingid);
784 }
18d43e96 785}
786
dcd8db68 787/**
788 * Determine if a course module is currently visible to a user
aaeba371 789 *
790 * $USER If $userid is null, use the global object.
791 *
4d8e2417
AG
792 * @category group
793 * @param stdClass $cm The course module
dcd8db68 794 * @param int $userid The user to check against the group.
4d8e2417 795 * @return bool True if the user can view the course module, false otherwise.
dcd8db68 796 */
797function groups_course_module_visible($cm, $userid=null) {
798 global $CFG, $USER;
f16fa0a3 799
dcd8db68 800 if (empty($userid)) {
801 $userid = $USER->id;
802 }
98da6021 803 if (empty($CFG->enablegroupmembersonly)) {
dd97c328 804 return true;
dcd8db68 805 }
806 if (empty($cm->groupmembersonly)) {
dd97c328 807 return true;
dcd8db68 808 }
b0c6dc1c 809 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id), $userid) or groups_has_membership($cm, $userid)) {
dd97c328 810 return true;
dcd8db68 811 }
dd97c328 812 return false;
dcd8db68 813}
998ced08
PS
814
815/**
816 * Internal method, sets up $SESSION->activegroup and verifies previous value
817 *
998ced08
PS
818 * @param int $courseid
819 * @param int|string $groupmode SEPARATEGROUPS, VISIBLEGROUPS or 'aag' (access all groups)
820 * @param int $groupingid 0 means all groups
4d8e2417 821 * @param array $allowedgroups list of groups user can see
998ced08
PS
822 */
823function _group_verify_activegroup($courseid, $groupmode, $groupingid, array $allowedgroups) {
c160da9c 824 global $SESSION, $USER;
998ced08
PS
825
826 // init activegroup array if necessary
827 if (!isset($SESSION->activegroup)) {
828 $SESSION->activegroup = array();
829 }
830 if (!array_key_exists($courseid, $SESSION->activegroup)) {
831 $SESSION->activegroup[$courseid] = array(SEPARATEGROUPS=>array(), VISIBLEGROUPS=>array(), 'aag'=>array());
832 }
833
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]);
840 }
841 }
842
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
847
848 } else if ($allowedgroups) {
c160da9c
PS
849 if ($groupmode != SEPARATEGROUPS and $mygroups = groups_get_all_groups($courseid, $USER->id, $groupingid)) {
850 $firstgroup = reset($mygroups);
851 } else {
852 $firstgroup = reset($allowedgroups);
853 }
998ced08
PS
854 $SESSION->activegroup[$courseid][$groupmode][$groupingid] = $firstgroup->id;
855
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;
860 }
861 }
74b714df 862}
e17dbeeb
SH
863
864/**
865 * Caches group data for a particular course to speed up subsequent requests.
866 *
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.
870 */
871function groups_cache_groupdata($courseid, cache $cache = null) {
872 global $DB;
873
874 if ($cache === null) {
875 // Initialise a cache if we wern't given one.
876 $cache = cache::make('core', 'groupdata');
877 }
878
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');
883
884 if (!is_array($groups)) {
885 $groups = array();
886 }
887
888 if (!is_array($groupings)) {
889 $groupings = array();
890 }
891
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();
897 }
898
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;
908}
909
910/**
911 * Gets group data for a course.
912 *
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.
917 *
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
921 */
922function 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');
926 }
927 // Try to retrieve it from the cache.
928 $data = $cache->get($courseid);
929 if ($data === false) {
930 $data = groups_cache_groupdata($courseid, $cache);
931 }
932 return $data;
475896bd 933}