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);
335 * Update the group icon from form data
337 * @param stdClass $group group information
338 * @param stdClass $data
339 * @param stdClass $editform
341 function groups_update_group_icon($group, $data, $editform) {
343 require_once("$CFG->libdir/gdlib.php");
345 $fs = get_file_storage();
346 $context = context_course
::instance($group->courseid
, MUST_EXIST
);
347 $newpicture = $group->picture
;
349 if (!empty($data->deletepicture
)) {
350 $fs->delete_area_files($context->id
, 'group', 'icon', $group->id
);
352 } else if ($iconfile = $editform->save_temp_file('imagefile')) {
353 if ($rev = process_new_icon($context, 'group', 'icon', $group->id
, $iconfile)) {
356 $fs->delete_area_files($context->id
, 'group', 'icon', $group->id
);
362 if ($newpicture != $group->picture
) {
363 $DB->set_field('groups', 'picture', $newpicture, array('id' => $group->id
));
364 $group->picture
= $newpicture;
366 // Invalidate the group data as we've updated the group record.
367 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid
));
374 * @param stdClass $data group properties (with magic quotes)
375 * @param stdClass $editform
376 * @param array $editoroptions
377 * @return bool true or exception
379 function groups_update_group($data, $editform = false, $editoroptions = false) {
382 $context = context_course
::instance($data->courseid
);
384 $data->timemodified
= time();
385 if (isset($data->name
)) {
386 $data->name
= trim($data->name
);
388 if (isset($data->idnumber
)) {
389 $data->idnumber
= trim($data->idnumber
);
390 if (($existing = groups_get_group_by_idnumber($data->courseid
, $data->idnumber
)) && $existing->id
!= $data->id
) {
391 throw new moodle_exception('idnumbertaken');
395 if ($editform and $editoroptions) {
396 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id
);
399 $DB->update_record('groups', $data);
401 // Invalidate the group data.
402 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid
));
404 $group = $DB->get_record('groups', array('id'=>$data->id
));
407 groups_update_group_icon($group, $data, $editform);
410 // Trigger group event.
412 'context' => $context,
413 'objectid' => $group->id
415 $event = \core\event\group_updated
::create($params);
416 $event->add_record_snapshot('groups', $group);
425 * @param stdClass $data grouping properties (with magic quotes)
426 * @param array $editoroptions
427 * @return bool true or exception
429 function groups_update_grouping($data, $editoroptions=null) {
431 $data->timemodified
= time();
432 if (isset($data->name
)) {
433 $data->name
= trim($data->name
);
435 if (isset($data->idnumber
)) {
436 $data->idnumber
= trim($data->idnumber
);
437 if (($existing = groups_get_grouping_by_idnumber($data->courseid
, $data->idnumber
)) && $existing->id
!= $data->id
) {
438 throw new moodle_exception('idnumbertaken');
441 if ($editoroptions !== null) {
442 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id
);
444 $DB->update_record('groupings', $data);
446 // Invalidate the group data.
447 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid
));
449 // Trigger group event.
451 'context' => context_course
::instance($data->courseid
),
452 'objectid' => $data->id
454 $event = \core\event\grouping_updated
::create($params);
461 * Delete a group best effort, first removing members and links with courses and groupings.
462 * Removes group avatar too.
464 * @param mixed $grouporid The id of group to delete or full group object
465 * @return bool True if deletion was successful, false otherwise
467 function groups_delete_group($grouporid) {
469 require_once("$CFG->libdir/gdlib.php");
471 if (is_object($grouporid)) {
472 $groupid = $grouporid->id
;
475 $groupid = $grouporid;
476 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
477 //silently ignore attempts to delete missing already deleted groups ;-)
482 // delete group calendar events
483 $DB->delete_records('event', array('groupid'=>$groupid));
484 //first delete usage in groupings_groups
485 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
487 $DB->delete_records('groups_members', array('groupid'=>$groupid));
489 $DB->delete_records('groups', array('id'=>$groupid));
491 // Delete all files associated with this group
492 $context = context_course
::instance($group->courseid
);
493 $fs = get_file_storage();
494 $fs->delete_area_files($context->id
, 'group', 'description', $groupid);
495 $fs->delete_area_files($context->id
, 'group', 'icon', $groupid);
497 // Invalidate the grouping cache for the course
498 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid
));
500 // Trigger group event.
502 'context' => $context,
503 'objectid' => $groupid
505 $event = \core\event\group_deleted
::create($params);
506 $event->add_record_snapshot('groups', $group);
515 * @param int $groupingorid
516 * @return bool success
518 function groups_delete_grouping($groupingorid) {
521 if (is_object($groupingorid)) {
522 $groupingid = $groupingorid->id
;
523 $grouping = $groupingorid;
525 $groupingid = $groupingorid;
526 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
527 //silently ignore attempts to delete missing already deleted groupings ;-)
532 //first delete usage in groupings_groups
533 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
534 // remove the default groupingid from course
535 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
536 // remove the groupingid from all course modules
537 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
539 $DB->delete_records('groupings', array('id'=>$groupingid));
541 $context = context_course
::instance($grouping->courseid
);
542 $fs = get_file_storage();
543 $files = $fs->get_area_files($context->id
, 'grouping', 'description', $groupingid);
544 foreach ($files as $file) {
548 // Invalidate the grouping cache for the course
549 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid
));
551 // Trigger group event.
553 'context' => $context,
554 'objectid' => $groupingid
556 $event = \core\event\grouping_deleted
::create($params);
557 $event->add_record_snapshot('groupings', $grouping);
564 * Remove all users (or one user) from all groups in course
566 * @param int $courseid
567 * @param int $userid 0 means all users
568 * @param bool $showfeedback
569 * @return bool success
571 function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
574 if (is_bool($userid)) {
575 debugging('Incorrect userid function parameter');
579 // Select * so that the function groups_remove_member() gets the whole record.
580 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
581 foreach ($groups as $group) {
583 $userids = array($userid);
585 $userids = $DB->get_fieldset_select('groups_members', 'userid', 'groupid = :groupid', array('groupid' => $group->id
));
588 foreach ($userids as $id) {
589 groups_remove_member($group, $id);
593 // TODO MDL-41312 Remove events_trigger_legacy('groups_members_removed').
594 // This event is kept here for backwards compatibility, because it cannot be
595 // translated to a new event as it is wrong.
596 $eventdata = new stdClass();
597 $eventdata->courseid
= $courseid;
598 $eventdata->userid
= $userid;
599 events_trigger_legacy('groups_members_removed', $eventdata);
602 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
609 * Remove all groups from all groupings in course
611 * @param int $courseid
612 * @param bool $showfeedback
613 * @return bool success
615 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
618 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
619 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
620 array($courseid), '', 'groupid, groupingid');
622 foreach ($results as $result) {
623 groups_unassign_grouping($result->groupingid
, $result->groupid
, false);
626 // Invalidate the grouping cache for the course
627 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
629 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_groups_removed').
630 // This event is kept here for backwards compatibility, because it cannot be
631 // translated to a new event as it is wrong.
632 events_trigger_legacy('groups_groupings_groups_removed', $courseid);
634 // no need to show any feedback here - we delete usually first groupings and then groups
640 * Delete all groups from course
642 * @param int $courseid
643 * @param bool $showfeedback
644 * @return bool success
646 function groups_delete_groups($courseid, $showfeedback=false) {
647 global $CFG, $DB, $OUTPUT;
649 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
650 foreach ($groups as $group) {
651 groups_delete_group($group);
654 // Invalidate the grouping cache for the course
655 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
657 // TODO MDL-41312 Remove events_trigger_legacy('groups_groups_deleted').
658 // This event is kept here for backwards compatibility, because it cannot be
659 // translated to a new event as it is wrong.
660 events_trigger_legacy('groups_groups_deleted', $courseid);
663 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
670 * Delete all groupings from course
672 * @param int $courseid
673 * @param bool $showfeedback
674 * @return bool success
676 function groups_delete_groupings($courseid, $showfeedback=false) {
679 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
680 foreach ($groupings as $grouping) {
681 groups_delete_grouping($grouping);
684 // Invalidate the grouping cache for the course.
685 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
687 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_deleted').
688 // This event is kept here for backwards compatibility, because it cannot be
689 // translated to a new event as it is wrong.
690 events_trigger_legacy('groups_groupings_deleted', $courseid);
693 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
699 /* =================================== */
700 /* various functions used by groups UI */
701 /* =================================== */
704 * Obtains a list of the possible roles that group members might come from,
705 * on a course. Generally this includes only profile roles.
707 * @param context $context Context of course
708 * @return Array of role ID integers, or false if error/none.
710 function groups_get_possible_roles($context) {
711 $roles = get_profile_roles($context);
712 return array_keys($roles);
717 * Gets potential group members for grouping
719 * @param int $courseid The id of the course
720 * @param int $roleid The role to select users from
721 * @param mixed $source restrict to cohort, grouping or group id
722 * @param string $orderby The column to sort users by
723 * @param int $notingroup restrict to users not in existing groups
724 * @return array An array of the users
726 function groups_get_potential_members($courseid, $roleid = null, $source = null,
727 $orderby = 'lastname ASC, firstname ASC',
728 $notingroup = null) {
731 $context = context_course
::instance($courseid);
733 list($esql, $params) = get_enrolled_sql($context);
737 // We want to eliminate users that are already associated with a course group.
738 $notingroupsql = "u.id NOT IN (SELECT userid
739 FROM {groups_members}
740 WHERE groupid IN (SELECT id
742 WHERE courseid = :courseid))";
743 $params['courseid'] = $courseid;
747 // We are looking for all users with this role assigned in this context or higher.
748 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
752 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
753 $where = "WHERE u.id IN (SELECT userid
754 FROM {role_assignments}
755 WHERE roleid = :roleid AND contextid $relatedctxsql)";
756 $where .= $notingroup ?
"AND $notingroupsql" : "";
757 } else if ($notingroup) {
758 $where = "WHERE $notingroupsql";
764 if (is_int($source)) {
765 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
766 $params['cohortid'] = $source;
768 // Auto-create groups from an existing cohort membership.
769 if (isset($source['cohortid'])) {
770 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
771 $params['cohortid'] = $source['cohortid'];
773 // Auto-create groups from an existing group membership.
774 if (isset($source['groupid'])) {
775 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
776 $params['groupid'] = $source['groupid'];
778 // Auto-create groups from an existing grouping membership.
779 if (isset($source['groupingid'])) {
780 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
781 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
782 $params['groupingid'] = $source['groupingid'];
786 $allusernamefields = get_all_user_name_fields(true, 'u');
787 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
789 JOIN ($esql) e ON e.id = u.id
794 return $DB->get_records_sql($sql, $params);
799 * Parse a group name for characters to replace
801 * @param string $format The format a group name will follow
802 * @param int $groupnumber The number of the group to be used in the parsed format string
803 * @return string the parsed format string
805 function groups_parse_name($format, $groupnumber) {
806 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
808 for($i=0; $i<$groupnumber; $i++
) {
811 $str = str_replace('@', $letter, $format);
813 $str = str_replace('#', $groupnumber+
1, $format);
819 * Assigns group into grouping
821 * @param int groupingid
823 * @param int $timeadded The time the group was added to the grouping.
824 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
825 * @return bool true or exception
827 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
830 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
833 $assign = new stdClass();
834 $assign->groupingid
= $groupingid;
835 $assign->groupid
= $groupid;
836 if ($timeadded != null) {
837 $assign->timeadded
= (integer)$timeadded;
839 $assign->timeadded
= time();
841 $DB->insert_record('groupings_groups', $assign);
843 if ($invalidatecache) {
844 // Invalidate the grouping cache for the course
845 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
846 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
853 * Unassigns group from grouping
855 * @param int groupingid
857 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
858 * @return bool success
860 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
862 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
864 if ($invalidatecache) {
865 // Invalidate the grouping cache for the course
866 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
867 cache_helper
::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
874 * Lists users in a group based on their role on the course.
875 * Returns false if there's an error or there are no users in the group.
876 * Otherwise returns an array of role ID => role data, where role data includes:
877 * (role) $id, $shortname, $name
878 * $users: array of objects for each user which include the specified fields
879 * Users who do not have a role are stored in the returned array with key '-'
880 * and pseudo-role details (including a name, 'No role'). Users with multiple
881 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
882 * which roles each has by looking in the $roles array of the user object.
884 * @param int $groupid
885 * @param int $courseid Course ID (should match the group's course)
886 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
887 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
888 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
889 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
890 * @return array Complex array as described above
892 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
893 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
896 // Retrieve information about all users and their roles on the course or
897 // parent ('related') contexts
898 $context = context_course
::instance($courseid);
900 // We are looking for all users with this role assigned in this context or higher.
901 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'relatedctx');
903 if ($extrawheretest) {
904 $extrawheretest = ' AND ' . $extrawheretest;
907 if (is_null($sort)) {
908 list($sort, $sortparams) = users_order_by_sql('u');
909 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
912 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
913 FROM {groups_members} gm
914 JOIN {user} u ON u.id = gm.userid
915 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
916 LEFT JOIN {role} r ON r.id = ra.roleid
917 WHERE gm.groupid=:mgroupid
919 ORDER BY r.sortorder, $sort";
920 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
921 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
923 return groups_calculate_role_people($rs, $context);
927 * Internal function used by groups_get_members_by_role to handle the
928 * results of a database query that includes a list of users and possible
931 * @param moodle_recordset $rs The record set (may be false)
932 * @param int $context ID of course context
933 * @return array As described in groups_get_members_by_role
935 function groups_calculate_role_people($rs, $context) {
942 $allroles = role_fix_names(get_all_roles($context), $context);
944 // Array of all involved roles
946 // Array of all retrieved users
949 foreach ($rs as $rec) {
950 // Create information about user if this is a new one
951 if (!array_key_exists($rec->userid
, $users)) {
952 // User data includes all the optional fields, but not any of the
953 // stuff we added to get the role details
954 $userdata = clone($rec);
955 unset($userdata->roleid
);
956 unset($userdata->roleshortname
);
957 unset($userdata->rolename
);
958 unset($userdata->userid
);
959 $userdata->id
= $rec->userid
;
961 // Make an array to hold the list of roles for this user
962 $userdata->roles
= array();
963 $users[$rec->userid
] = $userdata;
965 // If user has a role...
966 if (!is_null($rec->roleid
)) {
967 // Create information about role if this is a new one
968 if (!array_key_exists($rec->roleid
, $roles)) {
969 $role = $allroles[$rec->roleid
];
970 $roledata = new stdClass();
971 $roledata->id
= $role->id
;
972 $roledata->shortname
= $role->shortname
;
973 $roledata->name
= $role->localname
;
974 $roledata->users
= array();
975 $roles[$roledata->id
] = $roledata;
977 // Record that user has role
978 $users[$rec->userid
]->roles
[$rec->roleid
] = $roles[$rec->roleid
];
983 // Return false if there weren't any users
984 if (count($users) == 0) {
988 // Add pseudo-role for multiple roles
989 $roledata = new stdClass();
990 $roledata->name
= get_string('multipleroles','role');
991 $roledata->users
= array();
992 $roles['*'] = $roledata;
994 $roledata = new stdClass();
995 $roledata->name
= get_string('noroles','role');
996 $roledata->users
= array();
997 $roles[0] = $roledata;
999 // Now we rearrange the data to store users by role
1000 foreach ($users as $userid=>$userdata) {
1001 $rolecount = count($userdata->roles
);
1002 if ($rolecount == 0) {
1003 // does not have any roles
1005 } else if($rolecount > 1) {
1008 $userrole = reset($userdata->roles
);
1009 $roleid = $userrole->id
;
1011 $roles[$roleid]->users
[$userid] = $userdata;
1014 // Delete roles not used
1015 foreach ($roles as $key=>$roledata) {
1016 if (count($roledata->users
)===0) {
1017 unset($roles[$key]);
1021 // Return list of roles containing their users
1026 * Synchronises enrolments with the group membership
1028 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1029 * and group membership, such as enrol_cohort and enrol_meta .
1031 * @param string $enrolname name of enrolment method without prefix
1032 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1033 * @param string $gidfield name of the field in 'enrol' table that stores group id
1034 * @return array Returns the list of removed and added users. Each record contains fields:
1035 * userid, enrolid, courseid, groupid, groupname
1037 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1039 $onecourse = $courseid ?
"AND e.courseid = :courseid" : "";
1041 'enrolname' => $enrolname,
1042 'component' => 'enrol_'.$enrolname,
1043 'courseid' => $courseid
1046 $affectedusers = array(
1047 'removed' => array(),
1052 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1053 FROM {groups_members} gm
1054 JOIN {groups} g ON (g.id = gm.groupid)
1055 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1056 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1057 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1059 $rs = $DB->get_recordset_sql($sql, $params);
1060 foreach ($rs as $gm) {
1061 groups_remove_member($gm->groupid
, $gm->userid
);
1062 $affectedusers['removed'][] = $gm;
1067 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1068 FROM {user_enrolments} ue
1069 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1070 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1071 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1072 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1073 WHERE gm.id IS NULL";
1075 $rs = $DB->get_recordset_sql($sql, $params);
1076 foreach ($rs as $ue) {
1077 groups_add_member($ue->groupid
, $ue->userid
, 'enrol_'.$enrolname, $ue->enrolid
);
1078 $affectedusers['added'][] = $ue;
1082 return $affectedusers;