Merge branch 'm24_MDL-38545_PHP_Strict_error' of https://github.com/scara/moodle...
[moodle.git] / group / lib.php
blob96ecb6e43e3568843f1e4f145e15154e729d60ee
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 //trigger groups events
258 events_trigger('groups_group_created', $group);
260 return $group->id;
264 * Add a new grouping
266 * @param stdClass $data grouping properties
267 * @param array $editoroptions
268 * @return id of grouping or false if error
270 function groups_create_grouping($data, $editoroptions=null) {
271 global $DB;
273 $data->timecreated = time();
274 $data->timemodified = $data->timecreated;
275 $data->name = trim($data->name);
276 if (isset($data->idnumber)) {
277 $data->idnumber = trim($data->idnumber);
278 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
279 throw new moodle_exception('idnumbertaken');
283 if ($editoroptions !== null) {
284 $data->description = $data->description_editor['text'];
285 $data->descriptionformat = $data->description_editor['format'];
288 $id = $DB->insert_record('groupings', $data);
290 //trigger groups events
291 $data->id = $id;
293 if ($editoroptions !== null) {
294 $description = new stdClass;
295 $description->id = $data->id;
296 $description->description_editor = $data->description_editor;
297 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
298 $DB->update_record('groupings', $description);
301 events_trigger('groups_grouping_created', $data);
303 return $id;
307 * Update the group icon from form data
309 * @param stdClass $group group information
310 * @param stdClass $data
311 * @param stdClass $editform
313 function groups_update_group_icon($group, $data, $editform) {
314 global $CFG, $DB;
315 require_once("$CFG->libdir/gdlib.php");
317 $fs = get_file_storage();
318 $context = context_course::instance($group->courseid, MUST_EXIST);
320 //TODO: it would make sense to allow picture deleting too (skodak)
321 if (!empty($CFG->gdversion)) {
322 if ($iconfile = $editform->save_temp_file('imagefile')) {
323 if (process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
324 $DB->set_field('groups', 'picture', 1, array('id'=>$group->id));
325 $group->picture = 1;
326 } else {
327 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
328 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id));
329 $group->picture = 0;
331 @unlink($iconfile);
337 * Update group
339 * @param stdClass $data group properties (with magic quotes)
340 * @param stdClass $editform
341 * @param array $editoroptions
342 * @return bool true or exception
344 function groups_update_group($data, $editform = false, $editoroptions = false) {
345 global $CFG, $DB;
347 $context = context_course::instance($data->courseid);
349 $data->timemodified = time();
350 $data->name = trim($data->name);
351 if (isset($data->idnumber)) {
352 $data->idnumber = trim($data->idnumber);
353 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
354 throw new moodle_exception('idnumbertaken');
358 if ($editform and $editoroptions) {
359 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
362 $DB->update_record('groups', $data);
364 $group = $DB->get_record('groups', array('id'=>$data->id));
366 if ($editform) {
367 groups_update_group_icon($group, $data, $editform);
370 //trigger groups events
371 events_trigger('groups_group_updated', $group);
374 return true;
378 * Update grouping
380 * @param stdClass $data grouping properties (with magic quotes)
381 * @param array $editoroptions
382 * @return bool true or exception
384 function groups_update_grouping($data, $editoroptions=null) {
385 global $DB;
386 $data->timemodified = time();
387 $data->name = trim($data->name);
388 if (isset($data->idnumber)) {
389 $data->idnumber = trim($data->idnumber);
390 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
391 throw new moodle_exception('idnumbertaken');
394 if ($editoroptions !== null) {
395 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
397 $DB->update_record('groupings', $data);
398 //trigger groups events
399 events_trigger('groups_grouping_updated', $data);
401 return true;
405 * Delete a group best effort, first removing members and links with courses and groupings.
406 * Removes group avatar too.
408 * @param mixed $grouporid The id of group to delete or full group object
409 * @return bool True if deletion was successful, false otherwise
411 function groups_delete_group($grouporid) {
412 global $CFG, $DB;
413 require_once("$CFG->libdir/gdlib.php");
415 if (is_object($grouporid)) {
416 $groupid = $grouporid->id;
417 $group = $grouporid;
418 } else {
419 $groupid = $grouporid;
420 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
421 //silently ignore attempts to delete missing already deleted groups ;-)
422 return true;
426 // delete group calendar events
427 $DB->delete_records('event', array('groupid'=>$groupid));
428 //first delete usage in groupings_groups
429 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
430 //delete members
431 $DB->delete_records('groups_members', array('groupid'=>$groupid));
432 //group itself last
433 $DB->delete_records('groups', array('id'=>$groupid));
435 // Delete all files associated with this group
436 $context = context_course::instance($group->courseid);
437 $fs = get_file_storage();
438 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
439 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
441 //trigger groups events
442 events_trigger('groups_group_deleted', $group);
444 return true;
448 * Delete grouping
450 * @param int $groupingorid
451 * @return bool success
453 function groups_delete_grouping($groupingorid) {
454 global $DB;
456 if (is_object($groupingorid)) {
457 $groupingid = $groupingorid->id;
458 $grouping = $groupingorid;
459 } else {
460 $groupingid = $groupingorid;
461 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
462 //silently ignore attempts to delete missing already deleted groupings ;-)
463 return true;
467 //first delete usage in groupings_groups
468 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
469 // remove the default groupingid from course
470 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
471 // remove the groupingid from all course modules
472 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
473 //group itself last
474 $DB->delete_records('groupings', array('id'=>$groupingid));
476 $context = context_course::instance($grouping->courseid);
477 $fs = get_file_storage();
478 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
479 foreach ($files as $file) {
480 $file->delete();
483 //trigger groups events
484 events_trigger('groups_grouping_deleted', $grouping);
486 return true;
490 * Remove all users (or one user) from all groups in course
492 * @param int $courseid
493 * @param int $userid 0 means all users
494 * @param bool $showfeedback
495 * @return bool success
497 function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
498 global $DB, $OUTPUT;
500 if (is_bool($userid)) {
501 debugging('Incorrect userid function parameter');
502 return false;
505 $params = array('courseid'=>$courseid);
507 if ($userid) {
508 $usersql = "AND userid = :userid";
509 $params['userid'] = $userid;
510 } else {
511 $usersql = "";
514 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = :courseid";
515 $DB->delete_records_select('groups_members', "groupid IN ($groupssql) $usersql", $params);
517 //trigger groups events
518 $eventdata = new stdClass();
519 $eventdata->courseid = $courseid;
520 $eventdata->userid = $userid;
521 events_trigger('groups_members_removed', $eventdata);
523 if ($showfeedback) {
524 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
527 return true;
531 * Remove all groups from all groupings in course
533 * @param int $courseid
534 * @param bool $showfeedback
535 * @return bool success
537 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
538 global $DB, $OUTPUT;
540 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
541 $DB->delete_records_select('groupings_groups', "groupid IN ($groupssql)", array($courseid));
543 //trigger groups events
544 events_trigger('groups_groupings_groups_removed', $courseid);
546 // no need to show any feedback here - we delete usually first groupings and then groups
548 return true;
552 * Delete all groups from course
554 * @param int $courseid
555 * @param bool $showfeedback
556 * @return bool success
558 function groups_delete_groups($courseid, $showfeedback=false) {
559 global $CFG, $DB, $OUTPUT;
561 // delete any uses of groups
562 // Any associated files are deleted as part of groups_delete_groupings_groups
563 groups_delete_groupings_groups($courseid, $showfeedback);
564 groups_delete_group_members($courseid, 0, $showfeedback);
566 // delete group pictures and descriptions
567 $context = context_course::instance($courseid);
568 $fs = get_file_storage();
569 $fs->delete_area_files($context->id, 'group');
571 // delete group calendar events
572 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
573 $DB->delete_records_select('event', "groupid IN ($groupssql)", array($courseid));
575 $context = context_course::instance($courseid);
576 $fs = get_file_storage();
577 $fs->delete_area_files($context->id, 'group');
579 $DB->delete_records('groups', array('courseid'=>$courseid));
581 // trigger groups events
582 events_trigger('groups_groups_deleted', $courseid);
584 if ($showfeedback) {
585 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
588 return true;
592 * Delete all groupings from course
594 * @param int $courseid
595 * @param bool $showfeedback
596 * @return bool success
598 function groups_delete_groupings($courseid, $showfeedback=false) {
599 global $DB, $OUTPUT;
601 // delete any uses of groupings
602 $sql = "DELETE FROM {groupings_groups}
603 WHERE groupingid in (SELECT id FROM {groupings} g WHERE g.courseid = ?)";
604 $DB->execute($sql, array($courseid));
606 // remove the default groupingid from course
607 $DB->set_field('course', 'defaultgroupingid', 0, array('id'=>$courseid));
608 // remove the groupingid from all course modules
609 $DB->set_field('course_modules', 'groupingid', 0, array('course'=>$courseid));
611 // Delete all files associated with groupings for this course
612 $context = context_course::instance($courseid);
613 $fs = get_file_storage();
614 $fs->delete_area_files($context->id, 'grouping');
616 $DB->delete_records('groupings', array('courseid'=>$courseid));
618 // trigger groups events
619 events_trigger('groups_groupings_deleted', $courseid);
621 if ($showfeedback) {
622 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
625 return true;
628 /* =================================== */
629 /* various functions used by groups UI */
630 /* =================================== */
633 * Obtains a list of the possible roles that group members might come from,
634 * on a course. Generally this includes only profile roles.
636 * @param context $context Context of course
637 * @return Array of role ID integers, or false if error/none.
639 function groups_get_possible_roles($context) {
640 $roles = get_profile_roles($context);
641 return array_keys($roles);
646 * Gets potential group members for grouping
648 * @param int $courseid The id of the course
649 * @param int $roleid The role to select users from
650 * @param int $cohortid restrict to cohort id
651 * @param string $orderby The column to sort users by
652 * @return array An array of the users
654 function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
655 global $DB;
657 $context = context_course::instance($courseid);
659 // we are looking for all users with this role assigned in this context or higher
660 $listofcontexts = get_related_contexts_string($context);
662 list($esql, $params) = get_enrolled_sql($context);
664 if ($roleid) {
665 $params['roleid'] = $roleid;
666 $where = "WHERE u.id IN (SELECT userid
667 FROM {role_assignments}
668 WHERE roleid = :roleid AND contextid $listofcontexts)";
669 } else {
670 $where = "";
673 if ($cohortid) {
674 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
675 $params['cohortid'] = $cohortid;
676 } else {
677 $cohortjoin = "";
680 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
681 FROM {user} u
682 JOIN ($esql) e ON e.id = u.id
683 $cohortjoin
684 $where
685 ORDER BY $orderby";
687 return $DB->get_records_sql($sql, $params);
692 * Parse a group name for characters to replace
694 * @param string $format The format a group name will follow
695 * @param int $groupnumber The number of the group to be used in the parsed format string
696 * @return string the parsed format string
698 function groups_parse_name($format, $groupnumber) {
699 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
700 $letter = 'A';
701 for($i=0; $i<$groupnumber; $i++) {
702 $letter++;
704 $str = str_replace('@', $letter, $format);
705 } else {
706 $str = str_replace('#', $groupnumber+1, $format);
708 return($str);
712 * Assigns group into grouping
714 * @param int groupingid
715 * @param int groupid
716 * @param int $timeadded The time the group was added to the grouping.
717 * @return bool true or exception
719 function groups_assign_grouping($groupingid, $groupid, $timeadded = null) {
720 global $DB;
722 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
723 return true;
725 $assign = new stdClass();
726 $assign->groupingid = $groupingid;
727 $assign->groupid = $groupid;
728 if ($timeadded != null) {
729 $assign->timeadded = (integer)$timeadded;
730 } else {
731 $assign->timeadded = time();
733 $DB->insert_record('groupings_groups', $assign);
735 return true;
739 * Unassigns group grom grouping
741 * @param int groupingid
742 * @param int groupid
743 * @return bool success
745 function groups_unassign_grouping($groupingid, $groupid) {
746 global $DB;
747 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
749 return true;
753 * Lists users in a group based on their role on the course.
754 * Returns false if there's an error or there are no users in the group.
755 * Otherwise returns an array of role ID => role data, where role data includes:
756 * (role) $id, $shortname, $name
757 * $users: array of objects for each user which include the specified fields
758 * Users who do not have a role are stored in the returned array with key '-'
759 * and pseudo-role details (including a name, 'No role'). Users with multiple
760 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
761 * which roles each has by looking in the $roles array of the user object.
763 * @param int $groupid
764 * @param int $courseid Course ID (should match the group's course)
765 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
766 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
767 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
768 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
769 * @return array Complex array as described above
771 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
772 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
773 global $CFG, $DB;
775 // Retrieve information about all users and their roles on the course or
776 // parent ('related') contexts
777 $context = context_course::instance($courseid);
779 if ($extrawheretest) {
780 $extrawheretest = ' AND ' . $extrawheretest;
783 if (is_null($sort)) {
784 list($sort, $sortparams) = users_order_by_sql('u');
785 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
788 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
789 FROM {groups_members} gm
790 JOIN {user} u ON u.id = gm.userid
791 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid ".get_related_contexts_string($context).")
792 LEFT JOIN {role} r ON r.id = ra.roleid
793 WHERE gm.groupid=:mgroupid
794 ".$extrawheretest."
795 ORDER BY r.sortorder, $sort";
796 $whereorsortparams['mgroupid'] = $groupid;
797 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
799 return groups_calculate_role_people($rs, $context);
803 * Internal function used by groups_get_members_by_role to handle the
804 * results of a database query that includes a list of users and possible
805 * roles on a course.
807 * @param moodle_recordset $rs The record set (may be false)
808 * @param int $context ID of course context
809 * @return array As described in groups_get_members_by_role
811 function groups_calculate_role_people($rs, $context) {
812 global $CFG, $DB;
814 if (!$rs) {
815 return array();
818 $allroles = role_fix_names(get_all_roles($context), $context);
820 // Array of all involved roles
821 $roles = array();
822 // Array of all retrieved users
823 $users = array();
824 // Fill arrays
825 foreach ($rs as $rec) {
826 // Create information about user if this is a new one
827 if (!array_key_exists($rec->userid, $users)) {
828 // User data includes all the optional fields, but not any of the
829 // stuff we added to get the role details
830 $userdata = clone($rec);
831 unset($userdata->roleid);
832 unset($userdata->roleshortname);
833 unset($userdata->rolename);
834 unset($userdata->userid);
835 $userdata->id = $rec->userid;
837 // Make an array to hold the list of roles for this user
838 $userdata->roles = array();
839 $users[$rec->userid] = $userdata;
841 // If user has a role...
842 if (!is_null($rec->roleid)) {
843 // Create information about role if this is a new one
844 if (!array_key_exists($rec->roleid, $roles)) {
845 $role = $allroles[$rec->roleid];
846 $roledata = new stdClass();
847 $roledata->id = $role->id;
848 $roledata->shortname = $role->shortname;
849 $roledata->name = $role->localname;
850 $roledata->users = array();
851 $roles[$roledata->id] = $roledata;
853 // Record that user has role
854 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
857 $rs->close();
859 // Return false if there weren't any users
860 if (count($users) == 0) {
861 return false;
864 // Add pseudo-role for multiple roles
865 $roledata = new stdClass();
866 $roledata->name = get_string('multipleroles','role');
867 $roledata->users = array();
868 $roles['*'] = $roledata;
870 $roledata = new stdClass();
871 $roledata->name = get_string('noroles','role');
872 $roledata->users = array();
873 $roles[0] = $roledata;
875 // Now we rearrange the data to store users by role
876 foreach ($users as $userid=>$userdata) {
877 $rolecount = count($userdata->roles);
878 if ($rolecount == 0) {
879 // does not have any roles
880 $roleid = 0;
881 } else if($rolecount > 1) {
882 $roleid = '*';
883 } else {
884 $userrole = reset($userdata->roles);
885 $roleid = $userrole->id;
887 $roles[$roleid]->users[$userid] = $userdata;
890 // Delete roles not used
891 foreach ($roles as $key=>$roledata) {
892 if (count($roledata->users)===0) {
893 unset($roles[$key]);
897 // Return list of roles containing their users
898 return $roles;