2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
27 * INTERNAL FUNCTIONS - to be used by moodle core only
28 * require_once $CFG->dirroot.'/group/lib.php' must be used
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) {
44 if (is_object($userorid)) {
45 $userid = $userorid->id;
47 if (!isset($user->deleted)) {
48 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
52 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
59 if (is_object($grouporid)) {
60 $groupid = $grouporid->id;
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 $context = context_course::instance($group->courseid);
69 if (!is_enrolled($context, $userid)) {
73 if (groups_is_member($groupid, $userid)) {
77 $member = new stdClass();
78 $member->groupid = $groupid;
79 $member->userid = $userid;
80 $member->timeadded = time();
81 $member->component = '';
84 // Check the component exists if specified
85 if (!empty($component)) {
86 $dir = core_component::get_component_directory($component);
87 if ($dir && is_dir($dir)) {
88 // Component exists and can be used
89 $member->component = $component;
90 $member->itemid = $itemid;
92 throw new coding_exception('Invalid call to groups_add_member(). An invalid component was specified');
96 if ($itemid !== 0 && empty($member->component)) {
97 // An itemid can only be specified if a valid component was found
98 throw new coding_exception('Invalid call to groups_add_member(). A component must be specified if an itemid is given');
101 $DB->insert_record('groups_members', $member);
103 // Update group info, and group object.
104 $DB->set_field('groups', 'timemodified', $member->timeadded, array('id'=>$groupid));
105 $group->timemodified = $member->timeadded;
107 // Trigger group event.
109 'context' => $context,
110 'objectid' => $groupid,
111 'relateduserid' => $userid,
113 'component' => $member->component,
114 'itemid' => $member->itemid
117 $event = \core\event\group_member_added::create($params);
118 $event->add_record_snapshot('groups', $group);
125 * Checks whether the current user is permitted (using the normal UI) to
126 * remove a specific group member, assuming that they have access to remove
127 * group members in general.
129 * For automatically-created group member entries, this checks with the
130 * relevant plugin to see whether it is permitted. The default, if the plugin
131 * doesn't provide a function, is true.
133 * For other entries (and any which have already been deleted/don't exist) it
136 * @param mixed $grouporid The group id or group object
137 * @param mixed $userorid The user id or user object
138 * @return bool True if permitted, false otherwise
140 function groups_remove_member_allowed($grouporid, $userorid) {
143 if (is_object($userorid)) {
144 $userid = $userorid->id;
148 if (is_object($grouporid)) {
149 $groupid = $grouporid->id;
151 $groupid = $grouporid;
155 if (!($entry = $DB->get_record('groups_members',
156 array('groupid' => $groupid, 'userid' => $userid), '*', IGNORE_MISSING))) {
157 // If the entry does not exist, they are allowed to remove it (this
158 // is consistent with groups_remove_member below).
162 // If the entry does not have a component value, they can remove it
163 if (empty($entry->component)) {
167 // It has a component value, so we need to call a plugin function (if it
168 // exists); the default is to allow removal
169 return component_callback($entry->component, 'allow_group_member_remove',
170 array($entry->itemid, $entry->groupid, $entry->userid), true);
174 * Deletes the link between the specified user and group.
176 * @param mixed $grouporid The group id or group object
177 * @param mixed $userorid The user id or user object
178 * @return bool True if deletion was successful, false otherwise
180 function groups_remove_member($grouporid, $userorid) {
183 if (is_object($userorid)) {
184 $userid = $userorid->id;
189 if (is_object($grouporid)) {
190 $groupid = $grouporid->id;
193 $groupid = $grouporid;
194 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
197 if (!groups_is_member($groupid, $userid)) {
201 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
203 // Update group info.
205 $DB->set_field('groups', 'timemodified', $time, array('id' => $groupid));
206 $group->timemodified = $time;
208 // Trigger group event.
210 'context' => context_course::instance($group->courseid),
211 'objectid' => $groupid,
212 'relateduserid' => $userid
214 $event = \core\event\group_member_removed::create($params);
215 $event->add_record_snapshot('groups', $group);
224 * @param stdClass $data group properties
225 * @param stdClass $editform
226 * @param array $editoroptions
227 * @return id of group or false if error
229 function groups_create_group($data, $editform = false, $editoroptions = false) {
232 //check that courseid exists
233 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
234 $context = context_course::instance($course->id);
236 $data->timecreated = time();
237 $data->timemodified = $data->timecreated;
238 $data->name = trim($data->name);
239 if (isset($data->idnumber)) {
240 $data->idnumber = trim($data->idnumber);
241 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
242 throw new moodle_exception('idnumbertaken');
246 if ($editform and $editoroptions) {
247 $data->description = $data->description_editor['text'];
248 $data->descriptionformat = $data->description_editor['format'];
251 $data->id = $DB->insert_record('groups', $data);
253 if ($editform and $editoroptions) {
254 // Update description from editor with fixed files
255 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
256 $upd = new stdClass();
257 $upd->id = $data->id;
258 $upd->description = $data->description;
259 $upd->descriptionformat = $data->descriptionformat;
260 $DB->update_record('groups', $upd);
263 $group = $DB->get_record('groups', array('id'=>$data->id));
266 groups_update_group_icon($group, $data, $editform);
269 // Invalidate the grouping cache for the course
270 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($course->id));
272 // Trigger group event.
274 'context' => $context,
275 'objectid' => $group->id
277 $event = \core\event\group_created::create($params);
278 $event->add_record_snapshot('groups', $group);
287 * @param stdClass $data grouping properties
288 * @param array $editoroptions
289 * @return id of grouping or false if error
291 function groups_create_grouping($data, $editoroptions=null) {
294 $data->timecreated = time();
295 $data->timemodified = $data->timecreated;
296 $data->name = trim($data->name);
297 if (isset($data->idnumber)) {
298 $data->idnumber = trim($data->idnumber);
299 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
300 throw new moodle_exception('idnumbertaken');
304 if ($editoroptions !== null) {
305 $data->description = $data->description_editor['text'];
306 $data->descriptionformat = $data->description_editor['format'];
309 $id = $DB->insert_record('groupings', $data);
312 if ($editoroptions !== null) {
313 $description = new stdClass;
314 $description->id = $data->id;
315 $description->description_editor = $data->description_editor;
316 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
317 $DB->update_record('groupings', $description);
320 // Invalidate the grouping cache for the course
321 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
323 // Trigger group event.
325 'context' => context_course::instance($data->courseid),
328 $event = \core\event\grouping_created::create($params);
329 $event->set_legacy_eventdata($data);
336 * Update the group icon from form data
338 * @param stdClass $group group information
339 * @param stdClass $data
340 * @param stdClass $editform
342 function groups_update_group_icon($group, $data, $editform) {
344 require_once("$CFG->libdir/gdlib.php");
346 $fs = get_file_storage();
347 $context = context_course::instance($group->courseid, MUST_EXIST);
349 //TODO: it would make sense to allow picture deleting too (skodak)
350 if ($iconfile = $editform->save_temp_file('imagefile')) {
351 if (process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
352 $DB->set_field('groups', 'picture', 1, array('id'=>$group->id));
355 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
356 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id));
360 // Invalidate the group data as we've updated the group record.
361 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
368 * @param stdClass $data group properties (with magic quotes)
369 * @param stdClass $editform
370 * @param array $editoroptions
371 * @return bool true or exception
373 function groups_update_group($data, $editform = false, $editoroptions = false) {
376 $context = context_course::instance($data->courseid);
378 $data->timemodified = time();
379 $data->name = trim($data->name);
380 if (isset($data->idnumber)) {
381 $data->idnumber = trim($data->idnumber);
382 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
383 throw new moodle_exception('idnumbertaken');
387 if ($editform and $editoroptions) {
388 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
391 $DB->update_record('groups', $data);
393 // Invalidate the group data.
394 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
396 $group = $DB->get_record('groups', array('id'=>$data->id));
399 groups_update_group_icon($group, $data, $editform);
402 // Trigger group event.
404 'context' => $context,
405 'objectid' => $group->id
407 $event = \core\event\group_updated::create($params);
408 $event->add_record_snapshot('groups', $group);
417 * @param stdClass $data grouping properties (with magic quotes)
418 * @param array $editoroptions
419 * @return bool true or exception
421 function groups_update_grouping($data, $editoroptions=null) {
423 $data->timemodified = time();
424 $data->name = trim($data->name);
425 if (isset($data->idnumber)) {
426 $data->idnumber = trim($data->idnumber);
427 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
428 throw new moodle_exception('idnumbertaken');
431 if ($editoroptions !== null) {
432 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
434 $DB->update_record('groupings', $data);
436 // Invalidate the group data.
437 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
439 // Trigger group event.
441 'context' => context_course::instance($data->courseid),
442 'objectid' => $data->id
444 $event = \core\event\grouping_updated::create($params);
445 $event->set_legacy_eventdata($data);
452 * Delete a group best effort, first removing members and links with courses and groupings.
453 * Removes group avatar too.
455 * @param mixed $grouporid The id of group to delete or full group object
456 * @return bool True if deletion was successful, false otherwise
458 function groups_delete_group($grouporid) {
460 require_once("$CFG->libdir/gdlib.php");
462 if (is_object($grouporid)) {
463 $groupid = $grouporid->id;
466 $groupid = $grouporid;
467 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
468 //silently ignore attempts to delete missing already deleted groups ;-)
473 // delete group calendar events
474 $DB->delete_records('event', array('groupid'=>$groupid));
475 //first delete usage in groupings_groups
476 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
478 $DB->delete_records('groups_members', array('groupid'=>$groupid));
480 $DB->delete_records('groups', array('id'=>$groupid));
482 // Delete all files associated with this group
483 $context = context_course::instance($group->courseid);
484 $fs = get_file_storage();
485 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
486 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
488 // Invalidate the grouping cache for the course
489 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
491 // Trigger group event.
493 'context' => $context,
494 'objectid' => $groupid
496 $event = \core\event\group_deleted::create($params);
497 $event->add_record_snapshot('groups', $group);
506 * @param int $groupingorid
507 * @return bool success
509 function groups_delete_grouping($groupingorid) {
512 if (is_object($groupingorid)) {
513 $groupingid = $groupingorid->id;
514 $grouping = $groupingorid;
516 $groupingid = $groupingorid;
517 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
518 //silently ignore attempts to delete missing already deleted groupings ;-)
523 //first delete usage in groupings_groups
524 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
525 // remove the default groupingid from course
526 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
527 // remove the groupingid from all course modules
528 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
530 $DB->delete_records('groupings', array('id'=>$groupingid));
532 $context = context_course::instance($grouping->courseid);
533 $fs = get_file_storage();
534 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
535 foreach ($files as $file) {
539 // Invalidate the grouping cache for the course
540 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
542 // Trigger group event.
544 'context' => $context,
545 'objectid' => $groupingid
547 $event = \core\event\grouping_deleted::create($params);
548 $event->add_record_snapshot('groupings', $grouping);
555 * Remove all users (or one user) from all groups in course
557 * @param int $courseid
558 * @param int $userid 0 means all users
559 * @param bool $showfeedback
560 * @return bool success
562 function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
565 if (is_bool($userid)) {
566 debugging('Incorrect userid function parameter');
570 // Select * so that the function groups_remove_member() gets the whole record.
571 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
572 foreach ($groups as $group) {
574 $userids = array($userid);
576 $userids = $DB->get_fieldset_select('groups_members', 'userid', 'groupid = :groupid', array('groupid' => $group->id));
579 foreach ($userids as $id) {
580 groups_remove_member($group, $id);
584 // TODO MDL-41312 Remove events_trigger_legacy('groups_members_removed').
585 // This event is kept here for backwards compatibility, because it cannot be
586 // translated to a new event as it is wrong.
587 $eventdata = new stdClass();
588 $eventdata->courseid = $courseid;
589 $eventdata->userid = $userid;
590 events_trigger_legacy('groups_members_removed', $eventdata);
593 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
600 * Remove all groups from all groupings in course
602 * @param int $courseid
603 * @param bool $showfeedback
604 * @return bool success
606 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
609 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
610 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
611 array($courseid), '', 'groupid, groupingid');
613 foreach ($results as $result) {
614 groups_unassign_grouping($result->groupingid, $result->groupid, false);
617 // Invalidate the grouping cache for the course
618 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
620 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_groups_removed').
621 // This event is kept here for backwards compatibility, because it cannot be
622 // translated to a new event as it is wrong.
623 events_trigger_legacy('groups_groupings_groups_removed', $courseid);
625 // no need to show any feedback here - we delete usually first groupings and then groups
631 * Delete all groups from course
633 * @param int $courseid
634 * @param bool $showfeedback
635 * @return bool success
637 function groups_delete_groups($courseid, $showfeedback=false) {
638 global $CFG, $DB, $OUTPUT;
640 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
641 foreach ($groups as $group) {
642 groups_delete_group($group);
645 // Invalidate the grouping cache for the course
646 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
648 // TODO MDL-41312 Remove events_trigger_legacy('groups_groups_deleted').
649 // This event is kept here for backwards compatibility, because it cannot be
650 // translated to a new event as it is wrong.
651 events_trigger_legacy('groups_groups_deleted', $courseid);
654 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
661 * Delete all groupings from course
663 * @param int $courseid
664 * @param bool $showfeedback
665 * @return bool success
667 function groups_delete_groupings($courseid, $showfeedback=false) {
670 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
671 foreach ($groupings as $grouping) {
672 groups_delete_grouping($grouping);
675 // Invalidate the grouping cache for the course.
676 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
678 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_deleted').
679 // This event is kept here for backwards compatibility, because it cannot be
680 // translated to a new event as it is wrong.
681 events_trigger_legacy('groups_groupings_deleted', $courseid);
684 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
690 /* =================================== */
691 /* various functions used by groups UI */
692 /* =================================== */
695 * Obtains a list of the possible roles that group members might come from,
696 * on a course. Generally this includes only profile roles.
698 * @param context $context Context of course
699 * @return Array of role ID integers, or false if error/none.
701 function groups_get_possible_roles($context) {
702 $roles = get_profile_roles($context);
703 return array_keys($roles);
708 * Gets potential group members for grouping
710 * @param int $courseid The id of the course
711 * @param int $roleid The role to select users from
712 * @param int $cohortid restrict to cohort id
713 * @param string $orderby The column to sort users by
714 * @return array An array of the users
716 function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
719 $context = context_course::instance($courseid);
721 list($esql, $params) = get_enrolled_sql($context);
724 // We are looking for all users with this role assigned in this context or higher.
725 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
727 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
728 $where = "WHERE u.id IN (SELECT userid
729 FROM {role_assignments}
730 WHERE roleid = :roleid AND contextid $relatedctxsql)";
736 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
737 $params['cohortid'] = $cohortid;
742 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
744 JOIN ($esql) e ON e.id = u.id
749 return $DB->get_records_sql($sql, $params);
754 * Parse a group name for characters to replace
756 * @param string $format The format a group name will follow
757 * @param int $groupnumber The number of the group to be used in the parsed format string
758 * @return string the parsed format string
760 function groups_parse_name($format, $groupnumber) {
761 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
763 for($i=0; $i<$groupnumber; $i++) {
766 $str = str_replace('@', $letter, $format);
768 $str = str_replace('#', $groupnumber+1, $format);
774 * Assigns group into grouping
776 * @param int groupingid
778 * @param int $timeadded The time the group was added to the grouping.
779 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
780 * @return bool true or exception
782 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
785 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
788 $assign = new stdClass();
789 $assign->groupingid = $groupingid;
790 $assign->groupid = $groupid;
791 if ($timeadded != null) {
792 $assign->timeadded = (integer)$timeadded;
794 $assign->timeadded = time();
796 $DB->insert_record('groupings_groups', $assign);
798 if ($invalidatecache) {
799 // Invalidate the grouping cache for the course
800 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
801 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
808 * Unassigns group from grouping
810 * @param int groupingid
812 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
813 * @return bool success
815 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
817 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
819 if ($invalidatecache) {
820 // Invalidate the grouping cache for the course
821 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
822 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
829 * Lists users in a group based on their role on the course.
830 * Returns false if there's an error or there are no users in the group.
831 * Otherwise returns an array of role ID => role data, where role data includes:
832 * (role) $id, $shortname, $name
833 * $users: array of objects for each user which include the specified fields
834 * Users who do not have a role are stored in the returned array with key '-'
835 * and pseudo-role details (including a name, 'No role'). Users with multiple
836 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
837 * which roles each has by looking in the $roles array of the user object.
839 * @param int $groupid
840 * @param int $courseid Course ID (should match the group's course)
841 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
842 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
843 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
844 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
845 * @return array Complex array as described above
847 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
848 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
851 // Retrieve information about all users and their roles on the course or
852 // parent ('related') contexts
853 $context = context_course::instance($courseid);
855 // We are looking for all users with this role assigned in this context or higher.
856 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
858 if ($extrawheretest) {
859 $extrawheretest = ' AND ' . $extrawheretest;
862 if (is_null($sort)) {
863 list($sort, $sortparams) = users_order_by_sql('u');
864 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
867 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
868 FROM {groups_members} gm
869 JOIN {user} u ON u.id = gm.userid
870 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
871 LEFT JOIN {role} r ON r.id = ra.roleid
872 WHERE gm.groupid=:mgroupid
874 ORDER BY r.sortorder, $sort";
875 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
876 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
878 return groups_calculate_role_people($rs, $context);
882 * Internal function used by groups_get_members_by_role to handle the
883 * results of a database query that includes a list of users and possible
886 * @param moodle_recordset $rs The record set (may be false)
887 * @param int $context ID of course context
888 * @return array As described in groups_get_members_by_role
890 function groups_calculate_role_people($rs, $context) {
897 $allroles = role_fix_names(get_all_roles($context), $context);
899 // Array of all involved roles
901 // Array of all retrieved users
904 foreach ($rs as $rec) {
905 // Create information about user if this is a new one
906 if (!array_key_exists($rec->userid, $users)) {
907 // User data includes all the optional fields, but not any of the
908 // stuff we added to get the role details
909 $userdata = clone($rec);
910 unset($userdata->roleid);
911 unset($userdata->roleshortname);
912 unset($userdata->rolename);
913 unset($userdata->userid);
914 $userdata->id = $rec->userid;
916 // Make an array to hold the list of roles for this user
917 $userdata->roles = array();
918 $users[$rec->userid] = $userdata;
920 // If user has a role...
921 if (!is_null($rec->roleid)) {
922 // Create information about role if this is a new one
923 if (!array_key_exists($rec->roleid, $roles)) {
924 $role = $allroles[$rec->roleid];
925 $roledata = new stdClass();
926 $roledata->id = $role->id;
927 $roledata->shortname = $role->shortname;
928 $roledata->name = $role->localname;
929 $roledata->users = array();
930 $roles[$roledata->id] = $roledata;
932 // Record that user has role
933 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
938 // Return false if there weren't any users
939 if (count($users) == 0) {
943 // Add pseudo-role for multiple roles
944 $roledata = new stdClass();
945 $roledata->name = get_string('multipleroles','role');
946 $roledata->users = array();
947 $roles['*'] = $roledata;
949 $roledata = new stdClass();
950 $roledata->name = get_string('noroles','role');
951 $roledata->users = array();
952 $roles[0] = $roledata;
954 // Now we rearrange the data to store users by role
955 foreach ($users as $userid=>$userdata) {
956 $rolecount = count($userdata->roles);
957 if ($rolecount == 0) {
958 // does not have any roles
960 } else if($rolecount > 1) {
963 $userrole = reset($userdata->roles);
964 $roleid = $userrole->id;
966 $roles[$roleid]->users[$userid] = $userdata;
969 // Delete roles not used
970 foreach ($roles as $key=>$roledata) {
971 if (count($roledata->users)===0) {
976 // Return list of roles containing their users