MDL-38953 behat: Step definition to send a message
[moodle.git] / group / lib.php
blobb8d13b0733ace7015b01568a94437c1bfcef28c7
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Extra library for groups and groupings.
21 * @copyright 2006 The Open University, J.White AT open.ac.uk, Petr Skoda (skodak)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package core_group
27 * INTERNAL FUNCTIONS - to be used by moodle core only
28 * require_once $CFG->dirroot.'/group/lib.php' must be used
31 /**
32 * Adds a specified user to a group
34 * @param mixed $grouporid The group id or group object
35 * @param mixed $userorid The user id or user object
36 * @param string $component Optional component name e.g. 'enrol_imsenterprise'
37 * @param int $itemid Optional itemid associated with component
38 * @return bool True if user added successfully or the user is already a
39 * member of the group, false otherwise.
41 function groups_add_member($grouporid, $userorid, $component=null, $itemid=0) {
42 global $DB;
44 if (is_object($userorid)) {
45 $userid = $userorid->id;
46 $user = $userorid;
47 if (!isset($user->deleted)) {
48 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
50 } else {
51 $userid = $userorid;
52 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
55 if ($user->deleted) {
56 return false;
59 if (is_object($grouporid)) {
60 $groupid = $grouporid->id;
61 $group = $grouporid;
62 } else {
63 $groupid = $grouporid;
64 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
67 //check if the user a participant of the group course
68 if (!is_enrolled(context_course::instance($group->courseid), $userid)) {
69 return false;
72 if (groups_is_member($groupid, $userid)) {
73 return true;
76 $member = new stdClass();
77 $member->groupid = $groupid;
78 $member->userid = $userid;
79 $member->timeadded = time();
80 $member->component = '';
81 $member->itemid = 0;
83 // Check the component exists if specified
84 if (!empty($component)) {
85 $dir = get_component_directory($component);
86 if ($dir && is_dir($dir)) {
87 // Component exists and can be used
88 $member->component = $component;
89 $member->itemid = $itemid;
90 } else {
91 throw new coding_exception('Invalid call to groups_add_member(). An invalid component was specified');
95 if ($itemid !== 0 && empty($member->component)) {
96 // An itemid can only be specified if a valid component was found
97 throw new coding_exception('Invalid call to groups_add_member(). A component must be specified if an itemid is given');
100 $DB->insert_record('groups_members', $member);
102 //update group info
103 $DB->set_field('groups', 'timemodified', $member->timeadded, array('id'=>$groupid));
105 //trigger groups events
106 $eventdata = new stdClass();
107 $eventdata->groupid = $groupid;
108 $eventdata->userid = $userid;
109 $eventdata->component = $member->component;
110 $eventdata->itemid = $member->itemid;
111 events_trigger('groups_member_added', $eventdata);
113 return true;
117 * Checks whether the current user is permitted (using the normal UI) to
118 * remove a specific group member, assuming that they have access to remove
119 * group members in general.
121 * For automatically-created group member entries, this checks with the
122 * relevant plugin to see whether it is permitted. The default, if the plugin
123 * doesn't provide a function, is true.
125 * For other entries (and any which have already been deleted/don't exist) it
126 * just returns true.
128 * @param mixed $grouporid The group id or group object
129 * @param mixed $userorid The user id or user object
130 * @return bool True if permitted, false otherwise
132 function groups_remove_member_allowed($grouporid, $userorid) {
133 global $DB;
135 if (is_object($userorid)) {
136 $userid = $userorid->id;
137 } else {
138 $userid = $userorid;
140 if (is_object($grouporid)) {
141 $groupid = $grouporid->id;
142 } else {
143 $groupid = $grouporid;
146 // Get entry
147 if (!($entry = $DB->get_record('groups_members',
148 array('groupid' => $groupid, 'userid' => $userid), '*', IGNORE_MISSING))) {
149 // If the entry does not exist, they are allowed to remove it (this
150 // is consistent with groups_remove_member below).
151 return true;
154 // If the entry does not have a component value, they can remove it
155 if (empty($entry->component)) {
156 return true;
159 // It has a component value, so we need to call a plugin function (if it
160 // exists); the default is to allow removal
161 return component_callback($entry->component, 'allow_group_member_remove',
162 array($entry->itemid, $entry->groupid, $entry->userid), true);
166 * Deletes the link between the specified user and group.
168 * @param mixed $grouporid The group id or group object
169 * @param mixed $userorid The user id or user object
170 * @return bool True if deletion was successful, false otherwise
172 function groups_remove_member($grouporid, $userorid) {
173 global $DB;
175 if (is_object($userorid)) {
176 $userid = $userorid->id;
177 $user = $userorid;
178 } else {
179 $userid = $userorid;
180 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
183 if (is_object($grouporid)) {
184 $groupid = $grouporid->id;
185 $group = $grouporid;
186 } else {
187 $groupid = $grouporid;
188 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
191 if (!groups_is_member($groupid, $userid)) {
192 return true;
195 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
197 //update group info
198 $DB->set_field('groups', 'timemodified', time(), array('id'=>$groupid));
200 //trigger groups events
201 $eventdata = new stdClass();
202 $eventdata->groupid = $groupid;
203 $eventdata->userid = $userid;
204 events_trigger('groups_member_removed', $eventdata);
206 return true;
210 * Add a new group
212 * @param stdClass $data group properties
213 * @param stdClass $editform
214 * @param array $editoroptions
215 * @return id of group or false if error
217 function groups_create_group($data, $editform = false, $editoroptions = false) {
218 global $CFG, $DB;
220 //check that courseid exists
221 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
222 $context = context_course::instance($course->id);
224 $data->timecreated = time();
225 $data->timemodified = $data->timecreated;
226 $data->name = trim($data->name);
227 if (isset($data->idnumber)) {
228 $data->idnumber = trim($data->idnumber);
229 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
230 throw new moodle_exception('idnumbertaken');
234 if ($editform and $editoroptions) {
235 $data->description = $data->description_editor['text'];
236 $data->descriptionformat = $data->description_editor['format'];
239 $data->id = $DB->insert_record('groups', $data);
241 if ($editform and $editoroptions) {
242 // Update description from editor with fixed files
243 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
244 $upd = new stdClass();
245 $upd->id = $data->id;
246 $upd->description = $data->description;
247 $upd->descriptionformat = $data->descriptionformat;
248 $DB->update_record('groups', $upd);
251 $group = $DB->get_record('groups', array('id'=>$data->id));
253 if ($editform) {
254 groups_update_group_icon($group, $data, $editform);
257 // Invalidate the grouping cache for the course
258 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($course->id));
260 //trigger groups events
261 events_trigger('groups_group_created', $group);
263 return $group->id;
267 * Add a new grouping
269 * @param stdClass $data grouping properties
270 * @param array $editoroptions
271 * @return id of grouping or false if error
273 function groups_create_grouping($data, $editoroptions=null) {
274 global $DB;
276 $data->timecreated = time();
277 $data->timemodified = $data->timecreated;
278 $data->name = trim($data->name);
279 if (isset($data->idnumber)) {
280 $data->idnumber = trim($data->idnumber);
281 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
282 throw new moodle_exception('idnumbertaken');
286 if ($editoroptions !== null) {
287 $data->description = $data->description_editor['text'];
288 $data->descriptionformat = $data->description_editor['format'];
291 $id = $DB->insert_record('groupings', $data);
293 //trigger groups events
294 $data->id = $id;
296 if ($editoroptions !== null) {
297 $description = new stdClass;
298 $description->id = $data->id;
299 $description->description_editor = $data->description_editor;
300 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
301 $DB->update_record('groupings', $description);
304 // Invalidate the grouping cache for the course
305 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
307 events_trigger('groups_grouping_created', $data);
309 return $id;
313 * Update the group icon from form data
315 * @param stdClass $group group information
316 * @param stdClass $data
317 * @param stdClass $editform
319 function groups_update_group_icon($group, $data, $editform) {
320 global $CFG, $DB;
321 require_once("$CFG->libdir/gdlib.php");
323 $fs = get_file_storage();
324 $context = context_course::instance($group->courseid, MUST_EXIST);
326 //TODO: it would make sense to allow picture deleting too (skodak)
327 if ($iconfile = $editform->save_temp_file('imagefile')) {
328 if (process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
329 $DB->set_field('groups', 'picture', 1, array('id'=>$group->id));
330 $group->picture = 1;
331 } else {
332 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
333 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id));
334 $group->picture = 0;
336 @unlink($iconfile);
337 // Invalidate the group data as we've updated the group record.
338 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
343 * Update group
345 * @param stdClass $data group properties (with magic quotes)
346 * @param stdClass $editform
347 * @param array $editoroptions
348 * @return bool true or exception
350 function groups_update_group($data, $editform = false, $editoroptions = false) {
351 global $CFG, $DB;
353 $context = context_course::instance($data->courseid);
355 $data->timemodified = time();
356 $data->name = trim($data->name);
357 if (isset($data->idnumber)) {
358 $data->idnumber = trim($data->idnumber);
359 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
360 throw new moodle_exception('idnumbertaken');
364 if ($editform and $editoroptions) {
365 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
368 $DB->update_record('groups', $data);
370 // Invalidate the group data.
371 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
373 $group = $DB->get_record('groups', array('id'=>$data->id));
375 if ($editform) {
376 groups_update_group_icon($group, $data, $editform);
379 //trigger groups events
380 events_trigger('groups_group_updated', $group);
383 return true;
387 * Update grouping
389 * @param stdClass $data grouping properties (with magic quotes)
390 * @param array $editoroptions
391 * @return bool true or exception
393 function groups_update_grouping($data, $editoroptions=null) {
394 global $DB;
395 $data->timemodified = time();
396 $data->name = trim($data->name);
397 if (isset($data->idnumber)) {
398 $data->idnumber = trim($data->idnumber);
399 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
400 throw new moodle_exception('idnumbertaken');
403 if ($editoroptions !== null) {
404 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
406 $DB->update_record('groupings', $data);
408 // Invalidate the group data.
409 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
411 //trigger groups events
412 events_trigger('groups_grouping_updated', $data);
414 return true;
418 * Delete a group best effort, first removing members and links with courses and groupings.
419 * Removes group avatar too.
421 * @param mixed $grouporid The id of group to delete or full group object
422 * @return bool True if deletion was successful, false otherwise
424 function groups_delete_group($grouporid) {
425 global $CFG, $DB;
426 require_once("$CFG->libdir/gdlib.php");
428 if (is_object($grouporid)) {
429 $groupid = $grouporid->id;
430 $group = $grouporid;
431 } else {
432 $groupid = $grouporid;
433 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
434 //silently ignore attempts to delete missing already deleted groups ;-)
435 return true;
439 // delete group calendar events
440 $DB->delete_records('event', array('groupid'=>$groupid));
441 //first delete usage in groupings_groups
442 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
443 //delete members
444 $DB->delete_records('groups_members', array('groupid'=>$groupid));
445 //group itself last
446 $DB->delete_records('groups', array('id'=>$groupid));
448 // Delete all files associated with this group
449 $context = context_course::instance($group->courseid);
450 $fs = get_file_storage();
451 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
452 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
454 // Invalidate the grouping cache for the course
455 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
457 //trigger groups events
458 events_trigger('groups_group_deleted', $group);
460 return true;
464 * Delete grouping
466 * @param int $groupingorid
467 * @return bool success
469 function groups_delete_grouping($groupingorid) {
470 global $DB;
472 if (is_object($groupingorid)) {
473 $groupingid = $groupingorid->id;
474 $grouping = $groupingorid;
475 } else {
476 $groupingid = $groupingorid;
477 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
478 //silently ignore attempts to delete missing already deleted groupings ;-)
479 return true;
483 //first delete usage in groupings_groups
484 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
485 // remove the default groupingid from course
486 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
487 // remove the groupingid from all course modules
488 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
489 //group itself last
490 $DB->delete_records('groupings', array('id'=>$groupingid));
492 $context = context_course::instance($grouping->courseid);
493 $fs = get_file_storage();
494 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
495 foreach ($files as $file) {
496 $file->delete();
499 // Invalidate the grouping cache for the course
500 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
502 //trigger groups events
503 events_trigger('groups_grouping_deleted', $grouping);
505 return true;
509 * Remove all users (or one user) from all groups in course
511 * @param int $courseid
512 * @param int $userid 0 means all users
513 * @param bool $showfeedback
514 * @return bool success
516 function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
517 global $DB, $OUTPUT;
519 if (is_bool($userid)) {
520 debugging('Incorrect userid function parameter');
521 return false;
524 $params = array('courseid'=>$courseid);
526 if ($userid) {
527 $usersql = "AND userid = :userid";
528 $params['userid'] = $userid;
529 } else {
530 $usersql = "";
533 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = :courseid";
534 $DB->delete_records_select('groups_members', "groupid IN ($groupssql) $usersql", $params);
536 //trigger groups events
537 $eventdata = new stdClass();
538 $eventdata->courseid = $courseid;
539 $eventdata->userid = $userid;
540 events_trigger('groups_members_removed', $eventdata);
542 if ($showfeedback) {
543 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
546 return true;
550 * Remove all groups from all groupings in course
552 * @param int $courseid
553 * @param bool $showfeedback
554 * @return bool success
556 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
557 global $DB, $OUTPUT;
559 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
560 $DB->delete_records_select('groupings_groups', "groupid IN ($groupssql)", array($courseid));
562 // Invalidate the grouping cache for the course
563 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
565 //trigger groups events
566 events_trigger('groups_groupings_groups_removed', $courseid);
568 // no need to show any feedback here - we delete usually first groupings and then groups
570 return true;
574 * Delete all groups from course
576 * @param int $courseid
577 * @param bool $showfeedback
578 * @return bool success
580 function groups_delete_groups($courseid, $showfeedback=false) {
581 global $CFG, $DB, $OUTPUT;
583 // delete any uses of groups
584 // Any associated files are deleted as part of groups_delete_groupings_groups
585 groups_delete_groupings_groups($courseid, $showfeedback);
586 groups_delete_group_members($courseid, 0, $showfeedback);
588 // delete group pictures and descriptions
589 $context = context_course::instance($courseid);
590 $fs = get_file_storage();
591 $fs->delete_area_files($context->id, 'group');
593 // delete group calendar events
594 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
595 $DB->delete_records_select('event', "groupid IN ($groupssql)", array($courseid));
597 $context = context_course::instance($courseid);
598 $fs = get_file_storage();
599 $fs->delete_area_files($context->id, 'group');
601 $DB->delete_records('groups', array('courseid'=>$courseid));
603 // Invalidate the grouping cache for the course
604 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
606 // trigger groups events
607 events_trigger('groups_groups_deleted', $courseid);
609 if ($showfeedback) {
610 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
613 return true;
617 * Delete all groupings from course
619 * @param int $courseid
620 * @param bool $showfeedback
621 * @return bool success
623 function groups_delete_groupings($courseid, $showfeedback=false) {
624 global $DB, $OUTPUT;
626 // delete any uses of groupings
627 $sql = "DELETE FROM {groupings_groups}
628 WHERE groupingid in (SELECT id FROM {groupings} g WHERE g.courseid = ?)";
629 $DB->execute($sql, array($courseid));
631 // remove the default groupingid from course
632 $DB->set_field('course', 'defaultgroupingid', 0, array('id'=>$courseid));
633 // remove the groupingid from all course modules
634 $DB->set_field('course_modules', 'groupingid', 0, array('course'=>$courseid));
636 // Delete all files associated with groupings for this course
637 $context = context_course::instance($courseid);
638 $fs = get_file_storage();
639 $fs->delete_area_files($context->id, 'grouping');
641 $DB->delete_records('groupings', array('courseid'=>$courseid));
643 // Invalidate the grouping cache for the course
644 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
646 // trigger groups events
647 events_trigger('groups_groupings_deleted', $courseid);
649 if ($showfeedback) {
650 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
653 return true;
656 /* =================================== */
657 /* various functions used by groups UI */
658 /* =================================== */
661 * Obtains a list of the possible roles that group members might come from,
662 * on a course. Generally this includes only profile roles.
664 * @param context $context Context of course
665 * @return Array of role ID integers, or false if error/none.
667 function groups_get_possible_roles($context) {
668 $roles = get_profile_roles($context);
669 return array_keys($roles);
674 * Gets potential group members for grouping
676 * @param int $courseid The id of the course
677 * @param int $roleid The role to select users from
678 * @param int $cohortid restrict to cohort id
679 * @param string $orderby The column to sort users by
680 * @return array An array of the users
682 function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
683 global $DB;
685 $context = context_course::instance($courseid);
687 // we are looking for all users with this role assigned in this context or higher
688 $listofcontexts = get_related_contexts_string($context);
690 list($esql, $params) = get_enrolled_sql($context);
692 if ($roleid) {
693 $params['roleid'] = $roleid;
694 $where = "WHERE u.id IN (SELECT userid
695 FROM {role_assignments}
696 WHERE roleid = :roleid AND contextid $listofcontexts)";
697 } else {
698 $where = "";
701 if ($cohortid) {
702 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
703 $params['cohortid'] = $cohortid;
704 } else {
705 $cohortjoin = "";
708 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
709 FROM {user} u
710 JOIN ($esql) e ON e.id = u.id
711 $cohortjoin
712 $where
713 ORDER BY $orderby";
715 return $DB->get_records_sql($sql, $params);
720 * Parse a group name for characters to replace
722 * @param string $format The format a group name will follow
723 * @param int $groupnumber The number of the group to be used in the parsed format string
724 * @return string the parsed format string
726 function groups_parse_name($format, $groupnumber) {
727 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
728 $letter = 'A';
729 for($i=0; $i<$groupnumber; $i++) {
730 $letter++;
732 $str = str_replace('@', $letter, $format);
733 } else {
734 $str = str_replace('#', $groupnumber+1, $format);
736 return($str);
740 * Assigns group into grouping
742 * @param int groupingid
743 * @param int groupid
744 * @param int $timeadded The time the group was added to the grouping.
745 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
746 * @return bool true or exception
748 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
749 global $DB;
751 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
752 return true;
754 $assign = new stdClass();
755 $assign->groupingid = $groupingid;
756 $assign->groupid = $groupid;
757 if ($timeadded != null) {
758 $assign->timeadded = (integer)$timeadded;
759 } else {
760 $assign->timeadded = time();
762 $DB->insert_record('groupings_groups', $assign);
764 if ($invalidatecache) {
765 // Invalidate the grouping cache for the course
766 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
767 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
770 return true;
774 * Unassigns group from grouping
776 * @param int groupingid
777 * @param int groupid
778 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
779 * @return bool success
781 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
782 global $DB;
783 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
785 if ($invalidatecache) {
786 // Invalidate the grouping cache for the course
787 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
788 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
791 return true;
795 * Lists users in a group based on their role on the course.
796 * Returns false if there's an error or there are no users in the group.
797 * Otherwise returns an array of role ID => role data, where role data includes:
798 * (role) $id, $shortname, $name
799 * $users: array of objects for each user which include the specified fields
800 * Users who do not have a role are stored in the returned array with key '-'
801 * and pseudo-role details (including a name, 'No role'). Users with multiple
802 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
803 * which roles each has by looking in the $roles array of the user object.
805 * @param int $groupid
806 * @param int $courseid Course ID (should match the group's course)
807 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
808 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
809 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
810 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
811 * @return array Complex array as described above
813 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
814 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
815 global $CFG, $DB;
817 // Retrieve information about all users and their roles on the course or
818 // parent ('related') contexts
819 $context = context_course::instance($courseid);
821 if ($extrawheretest) {
822 $extrawheretest = ' AND ' . $extrawheretest;
825 if (is_null($sort)) {
826 list($sort, $sortparams) = users_order_by_sql('u');
827 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
830 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
831 FROM {groups_members} gm
832 JOIN {user} u ON u.id = gm.userid
833 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid ".get_related_contexts_string($context).")
834 LEFT JOIN {role} r ON r.id = ra.roleid
835 WHERE gm.groupid=:mgroupid
836 ".$extrawheretest."
837 ORDER BY r.sortorder, $sort";
838 $whereorsortparams['mgroupid'] = $groupid;
839 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
841 return groups_calculate_role_people($rs, $context);
845 * Internal function used by groups_get_members_by_role to handle the
846 * results of a database query that includes a list of users and possible
847 * roles on a course.
849 * @param moodle_recordset $rs The record set (may be false)
850 * @param int $context ID of course context
851 * @return array As described in groups_get_members_by_role
853 function groups_calculate_role_people($rs, $context) {
854 global $CFG, $DB;
856 if (!$rs) {
857 return array();
860 $allroles = role_fix_names(get_all_roles($context), $context);
862 // Array of all involved roles
863 $roles = array();
864 // Array of all retrieved users
865 $users = array();
866 // Fill arrays
867 foreach ($rs as $rec) {
868 // Create information about user if this is a new one
869 if (!array_key_exists($rec->userid, $users)) {
870 // User data includes all the optional fields, but not any of the
871 // stuff we added to get the role details
872 $userdata = clone($rec);
873 unset($userdata->roleid);
874 unset($userdata->roleshortname);
875 unset($userdata->rolename);
876 unset($userdata->userid);
877 $userdata->id = $rec->userid;
879 // Make an array to hold the list of roles for this user
880 $userdata->roles = array();
881 $users[$rec->userid] = $userdata;
883 // If user has a role...
884 if (!is_null($rec->roleid)) {
885 // Create information about role if this is a new one
886 if (!array_key_exists($rec->roleid, $roles)) {
887 $role = $allroles[$rec->roleid];
888 $roledata = new stdClass();
889 $roledata->id = $role->id;
890 $roledata->shortname = $role->shortname;
891 $roledata->name = $role->localname;
892 $roledata->users = array();
893 $roles[$roledata->id] = $roledata;
895 // Record that user has role
896 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
899 $rs->close();
901 // Return false if there weren't any users
902 if (count($users) == 0) {
903 return false;
906 // Add pseudo-role for multiple roles
907 $roledata = new stdClass();
908 $roledata->name = get_string('multipleroles','role');
909 $roledata->users = array();
910 $roles['*'] = $roledata;
912 $roledata = new stdClass();
913 $roledata->name = get_string('noroles','role');
914 $roledata->users = array();
915 $roles[0] = $roledata;
917 // Now we rearrange the data to store users by role
918 foreach ($users as $userid=>$userdata) {
919 $rolecount = count($userdata->roles);
920 if ($rolecount == 0) {
921 // does not have any roles
922 $roleid = 0;
923 } else if($rolecount > 1) {
924 $roleid = '*';
925 } else {
926 $userrole = reset($userdata->roles);
927 $roleid = $userrole->id;
929 $roles[$roleid]->users[$userid] = $userdata;
932 // Delete roles not used
933 foreach ($roles as $key=>$roledata) {
934 if (count($roledata->users)===0) {
935 unset($roles[$key]);
939 // Return list of roles containing their users
940 return $roles;