MDL-17929 groups: function to sync groups with enrolments
[moodle.git] / group / lib.php
blob27ee1c3c48d70ff7b088a1fdd9fcaad6bc34af77
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 $context = context_course::instance($group->courseid);
69 if (!is_enrolled($context, $userid)) {
70 return false;
73 if (groups_is_member($groupid, $userid)) {
74 return true;
77 $member = new stdClass();
78 $member->groupid = $groupid;
79 $member->userid = $userid;
80 $member->timeadded = time();
81 $member->component = '';
82 $member->itemid = 0;
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;
91 } else {
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.
108 $params = array(
109 'context' => $context,
110 'objectid' => $groupid,
111 'relateduserid' => $userid,
112 'other' => array(
113 'component' => $member->component,
114 'itemid' => $member->itemid
117 $event = \core\event\group_member_added::create($params);
118 $event->add_record_snapshot('groups', $group);
119 $event->trigger();
121 return true;
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
134 * just returns true.
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) {
141 global $DB;
143 if (is_object($userorid)) {
144 $userid = $userorid->id;
145 } else {
146 $userid = $userorid;
148 if (is_object($grouporid)) {
149 $groupid = $grouporid->id;
150 } else {
151 $groupid = $grouporid;
154 // Get entry
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).
159 return true;
162 // If the entry does not have a component value, they can remove it
163 if (empty($entry->component)) {
164 return true;
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) {
181 global $DB;
183 if (is_object($userorid)) {
184 $userid = $userorid->id;
185 } else {
186 $userid = $userorid;
189 if (is_object($grouporid)) {
190 $groupid = $grouporid->id;
191 $group = $grouporid;
192 } else {
193 $groupid = $grouporid;
194 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
197 if (!groups_is_member($groupid, $userid)) {
198 return true;
201 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
203 // Update group info.
204 $time = time();
205 $DB->set_field('groups', 'timemodified', $time, array('id' => $groupid));
206 $group->timemodified = $time;
208 // Trigger group event.
209 $params = array(
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);
216 $event->trigger();
218 return true;
222 * Add a new 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) {
230 global $CFG, $DB;
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));
265 if ($editform) {
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.
273 $params = array(
274 'context' => $context,
275 'objectid' => $group->id
277 $event = \core\event\group_created::create($params);
278 $event->add_record_snapshot('groups', $group);
279 $event->trigger();
281 return $group->id;
285 * Add a new grouping
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) {
292 global $DB;
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);
310 $data->id = $id;
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.
324 $params = array(
325 'context' => context_course::instance($data->courseid),
326 'objectid' => $id
328 $event = \core\event\grouping_created::create($params);
329 $event->trigger();
331 return $id;
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) {
342 global $CFG, $DB;
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);
351 $newpicture = 0;
352 } else if ($iconfile = $editform->save_temp_file('imagefile')) {
353 if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
354 $newpicture = $rev;
355 } else {
356 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
357 $newpicture = 0;
359 @unlink($iconfile);
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));
372 * Update group
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) {
380 global $CFG, $DB;
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));
406 if ($editform) {
407 groups_update_group_icon($group, $data, $editform);
410 // Trigger group event.
411 $params = array(
412 'context' => $context,
413 'objectid' => $group->id
415 $event = \core\event\group_updated::create($params);
416 $event->add_record_snapshot('groups', $group);
417 $event->trigger();
419 return true;
423 * Update grouping
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) {
430 global $DB;
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.
450 $params = array(
451 'context' => context_course::instance($data->courseid),
452 'objectid' => $data->id
454 $event = \core\event\grouping_updated::create($params);
455 $event->trigger();
457 return true;
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) {
468 global $CFG, $DB;
469 require_once("$CFG->libdir/gdlib.php");
471 if (is_object($grouporid)) {
472 $groupid = $grouporid->id;
473 $group = $grouporid;
474 } else {
475 $groupid = $grouporid;
476 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
477 //silently ignore attempts to delete missing already deleted groups ;-)
478 return true;
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));
486 //delete members
487 $DB->delete_records('groups_members', array('groupid'=>$groupid));
488 //group itself last
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.
501 $params = array(
502 'context' => $context,
503 'objectid' => $groupid
505 $event = \core\event\group_deleted::create($params);
506 $event->add_record_snapshot('groups', $group);
507 $event->trigger();
509 return true;
513 * Delete grouping
515 * @param int $groupingorid
516 * @return bool success
518 function groups_delete_grouping($groupingorid) {
519 global $DB;
521 if (is_object($groupingorid)) {
522 $groupingid = $groupingorid->id;
523 $grouping = $groupingorid;
524 } else {
525 $groupingid = $groupingorid;
526 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
527 //silently ignore attempts to delete missing already deleted groupings ;-)
528 return true;
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));
538 //group itself last
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) {
545 $file->delete();
548 // Invalidate the grouping cache for the course
549 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
551 // Trigger group event.
552 $params = array(
553 'context' => $context,
554 'objectid' => $groupingid
556 $event = \core\event\grouping_deleted::create($params);
557 $event->add_record_snapshot('groupings', $grouping);
558 $event->trigger();
560 return true;
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) {
572 global $DB, $OUTPUT;
574 if (is_bool($userid)) {
575 debugging('Incorrect userid function parameter');
576 return false;
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) {
582 if ($userid) {
583 $userids = array($userid);
584 } else {
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);
601 if ($showfeedback) {
602 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
605 return true;
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) {
616 global $DB, $OUTPUT;
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
636 return true;
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);
662 if ($showfeedback) {
663 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
666 return true;
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) {
677 global $DB, $OUTPUT;
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);
692 if ($showfeedback) {
693 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
696 return true;
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) {
729 global $DB;
731 $context = context_course::instance($courseid);
733 list($esql, $params) = get_enrolled_sql($context);
735 $notingroupsql = "";
736 if ($notingroup) {
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
741 FROM {groups}
742 WHERE courseid = :courseid))";
743 $params['courseid'] = $courseid;
746 if ($roleid) {
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),
749 SQL_PARAMS_NAMED,
750 'relatedctx');
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";
759 } else {
760 $where = "";
763 $sourcejoin = "";
764 if (is_int($source)) {
765 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
766 $params['cohortid'] = $source;
767 } else {
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
788 FROM {user} u
789 JOIN ($esql) e ON e.id = u.id
790 $sourcejoin
791 $where
792 ORDER BY $orderby";
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
807 $letter = 'A';
808 for($i=0; $i<$groupnumber; $i++) {
809 $letter++;
811 $str = str_replace('@', $letter, $format);
812 } else {
813 $str = str_replace('#', $groupnumber+1, $format);
815 return($str);
819 * Assigns group into grouping
821 * @param int groupingid
822 * @param int groupid
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) {
828 global $DB;
830 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
831 return true;
833 $assign = new stdClass();
834 $assign->groupingid = $groupingid;
835 $assign->groupid = $groupid;
836 if ($timeadded != null) {
837 $assign->timeadded = (integer)$timeadded;
838 } else {
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));
849 return true;
853 * Unassigns group from grouping
855 * @param int groupingid
856 * @param int groupid
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) {
861 global $DB;
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));
870 return true;
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()) {
894 global $DB;
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
918 ".$extrawheretest."
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
929 * roles on a course.
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) {
936 global $CFG, $DB;
938 if (!$rs) {
939 return array();
942 $allroles = role_fix_names(get_all_roles($context), $context);
944 // Array of all involved roles
945 $roles = array();
946 // Array of all retrieved users
947 $users = array();
948 // Fill arrays
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];
981 $rs->close();
983 // Return false if there weren't any users
984 if (count($users) == 0) {
985 return false;
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
1004 $roleid = 0;
1005 } else if($rolecount > 1) {
1006 $roleid = '*';
1007 } else {
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
1022 return $roles;
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') {
1038 global $DB;
1039 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1040 $params = array(
1041 'enrolname' => $enrolname,
1042 'component' => 'enrol_'.$enrolname,
1043 'courseid' => $courseid
1046 $affectedusers = array(
1047 'removed' => array(),
1048 'added' => array()
1051 // Remove invalid.
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;
1064 $rs->close();
1066 // Add missing.
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;
1080 $rs->close();
1082 return $affectedusers;