Moodle release 3.4.7
[moodle.git] / group / lib.php
blob57bd61610dacd80e0e446339d3f79acf0081b183
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 // Invalidate the group and grouping cache for users.
108 cache_helper::invalidate_by_definition('core', 'user_group_groupings', array(), array($userid));
110 // Trigger group event.
111 $params = array(
112 'context' => $context,
113 'objectid' => $groupid,
114 'relateduserid' => $userid,
115 'other' => array(
116 'component' => $member->component,
117 'itemid' => $member->itemid
120 $event = \core\event\group_member_added::create($params);
121 $event->add_record_snapshot('groups', $group);
122 $event->trigger();
124 return true;
128 * Checks whether the current user is permitted (using the normal UI) to
129 * remove a specific group member, assuming that they have access to remove
130 * group members in general.
132 * For automatically-created group member entries, this checks with the
133 * relevant plugin to see whether it is permitted. The default, if the plugin
134 * doesn't provide a function, is true.
136 * For other entries (and any which have already been deleted/don't exist) it
137 * just returns true.
139 * @param mixed $grouporid The group id or group object
140 * @param mixed $userorid The user id or user object
141 * @return bool True if permitted, false otherwise
143 function groups_remove_member_allowed($grouporid, $userorid) {
144 global $DB;
146 if (is_object($userorid)) {
147 $userid = $userorid->id;
148 } else {
149 $userid = $userorid;
151 if (is_object($grouporid)) {
152 $groupid = $grouporid->id;
153 } else {
154 $groupid = $grouporid;
157 // Get entry
158 if (!($entry = $DB->get_record('groups_members',
159 array('groupid' => $groupid, 'userid' => $userid), '*', IGNORE_MISSING))) {
160 // If the entry does not exist, they are allowed to remove it (this
161 // is consistent with groups_remove_member below).
162 return true;
165 // If the entry does not have a component value, they can remove it
166 if (empty($entry->component)) {
167 return true;
170 // It has a component value, so we need to call a plugin function (if it
171 // exists); the default is to allow removal
172 return component_callback($entry->component, 'allow_group_member_remove',
173 array($entry->itemid, $entry->groupid, $entry->userid), true);
177 * Deletes the link between the specified user and group.
179 * @param mixed $grouporid The group id or group object
180 * @param mixed $userorid The user id or user object
181 * @return bool True if deletion was successful, false otherwise
183 function groups_remove_member($grouporid, $userorid) {
184 global $DB;
186 if (is_object($userorid)) {
187 $userid = $userorid->id;
188 } else {
189 $userid = $userorid;
192 if (is_object($grouporid)) {
193 $groupid = $grouporid->id;
194 $group = $grouporid;
195 } else {
196 $groupid = $grouporid;
197 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
200 if (!groups_is_member($groupid, $userid)) {
201 return true;
204 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
206 // Update group info.
207 $time = time();
208 $DB->set_field('groups', 'timemodified', $time, array('id' => $groupid));
209 $group->timemodified = $time;
211 // Invalidate the group and grouping cache for users.
212 cache_helper::invalidate_by_definition('core', 'user_group_groupings', array(), array($userid));
214 // Trigger group event.
215 $params = array(
216 'context' => context_course::instance($group->courseid),
217 'objectid' => $groupid,
218 'relateduserid' => $userid
220 $event = \core\event\group_member_removed::create($params);
221 $event->add_record_snapshot('groups', $group);
222 $event->trigger();
224 return true;
228 * Add a new group
230 * @param stdClass $data group properties
231 * @param stdClass $editform
232 * @param array $editoroptions
233 * @return id of group or false if error
235 function groups_create_group($data, $editform = false, $editoroptions = false) {
236 global $CFG, $DB;
238 //check that courseid exists
239 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
240 $context = context_course::instance($course->id);
242 $data->timecreated = time();
243 $data->timemodified = $data->timecreated;
244 $data->name = trim($data->name);
245 if (isset($data->idnumber)) {
246 $data->idnumber = trim($data->idnumber);
247 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
248 throw new moodle_exception('idnumbertaken');
252 if ($editform and $editoroptions) {
253 $data->description = $data->description_editor['text'];
254 $data->descriptionformat = $data->description_editor['format'];
257 $data->id = $DB->insert_record('groups', $data);
259 if ($editform and $editoroptions) {
260 // Update description from editor with fixed files
261 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
262 $upd = new stdClass();
263 $upd->id = $data->id;
264 $upd->description = $data->description;
265 $upd->descriptionformat = $data->descriptionformat;
266 $DB->update_record('groups', $upd);
269 $group = $DB->get_record('groups', array('id'=>$data->id));
271 if ($editform) {
272 groups_update_group_icon($group, $data, $editform);
275 // Invalidate the grouping cache for the course
276 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($course->id));
278 // Trigger group event.
279 $params = array(
280 'context' => $context,
281 'objectid' => $group->id
283 $event = \core\event\group_created::create($params);
284 $event->add_record_snapshot('groups', $group);
285 $event->trigger();
287 return $group->id;
291 * Add a new grouping
293 * @param stdClass $data grouping properties
294 * @param array $editoroptions
295 * @return id of grouping or false if error
297 function groups_create_grouping($data, $editoroptions=null) {
298 global $DB;
300 $data->timecreated = time();
301 $data->timemodified = $data->timecreated;
302 $data->name = trim($data->name);
303 if (isset($data->idnumber)) {
304 $data->idnumber = trim($data->idnumber);
305 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
306 throw new moodle_exception('idnumbertaken');
310 if ($editoroptions !== null) {
311 $data->description = $data->description_editor['text'];
312 $data->descriptionformat = $data->description_editor['format'];
315 $id = $DB->insert_record('groupings', $data);
316 $data->id = $id;
318 if ($editoroptions !== null) {
319 $description = new stdClass;
320 $description->id = $data->id;
321 $description->description_editor = $data->description_editor;
322 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
323 $DB->update_record('groupings', $description);
326 // Invalidate the grouping cache for the course
327 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
329 // Trigger group event.
330 $params = array(
331 'context' => context_course::instance($data->courseid),
332 'objectid' => $id
334 $event = \core\event\grouping_created::create($params);
335 $event->trigger();
337 return $id;
341 * Update the group icon from form data
343 * @param stdClass $group group information
344 * @param stdClass $data
345 * @param stdClass $editform
347 function groups_update_group_icon($group, $data, $editform) {
348 global $CFG, $DB;
349 require_once("$CFG->libdir/gdlib.php");
351 $fs = get_file_storage();
352 $context = context_course::instance($group->courseid, MUST_EXIST);
353 $newpicture = $group->picture;
355 if (!empty($data->deletepicture)) {
356 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
357 $newpicture = 0;
358 } else if ($iconfile = $editform->save_temp_file('imagefile')) {
359 if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
360 $newpicture = $rev;
361 } else {
362 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
363 $newpicture = 0;
365 @unlink($iconfile);
368 if ($newpicture != $group->picture) {
369 $DB->set_field('groups', 'picture', $newpicture, array('id' => $group->id));
370 $group->picture = $newpicture;
372 // Invalidate the group data as we've updated the group record.
373 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
378 * Update group
380 * @param stdClass $data group properties (with magic quotes)
381 * @param stdClass $editform
382 * @param array $editoroptions
383 * @return bool true or exception
385 function groups_update_group($data, $editform = false, $editoroptions = false) {
386 global $CFG, $DB;
388 $context = context_course::instance($data->courseid);
390 $data->timemodified = time();
391 if (isset($data->name)) {
392 $data->name = trim($data->name);
394 if (isset($data->idnumber)) {
395 $data->idnumber = trim($data->idnumber);
396 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
397 throw new moodle_exception('idnumbertaken');
401 if ($editform and $editoroptions) {
402 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
405 $DB->update_record('groups', $data);
407 // Invalidate the group data.
408 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
410 $group = $DB->get_record('groups', array('id'=>$data->id));
412 if ($editform) {
413 groups_update_group_icon($group, $data, $editform);
416 // Trigger group event.
417 $params = array(
418 'context' => $context,
419 'objectid' => $group->id
421 $event = \core\event\group_updated::create($params);
422 $event->add_record_snapshot('groups', $group);
423 $event->trigger();
425 return true;
429 * Update grouping
431 * @param stdClass $data grouping properties (with magic quotes)
432 * @param array $editoroptions
433 * @return bool true or exception
435 function groups_update_grouping($data, $editoroptions=null) {
436 global $DB;
437 $data->timemodified = time();
438 if (isset($data->name)) {
439 $data->name = trim($data->name);
441 if (isset($data->idnumber)) {
442 $data->idnumber = trim($data->idnumber);
443 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
444 throw new moodle_exception('idnumbertaken');
447 if ($editoroptions !== null) {
448 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
450 $DB->update_record('groupings', $data);
452 // Invalidate the group data.
453 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
455 // Trigger group event.
456 $params = array(
457 'context' => context_course::instance($data->courseid),
458 'objectid' => $data->id
460 $event = \core\event\grouping_updated::create($params);
461 $event->trigger();
463 return true;
467 * Delete a group best effort, first removing members and links with courses and groupings.
468 * Removes group avatar too.
470 * @param mixed $grouporid The id of group to delete or full group object
471 * @return bool True if deletion was successful, false otherwise
473 function groups_delete_group($grouporid) {
474 global $CFG, $DB;
475 require_once("$CFG->libdir/gdlib.php");
477 if (is_object($grouporid)) {
478 $groupid = $grouporid->id;
479 $group = $grouporid;
480 } else {
481 $groupid = $grouporid;
482 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
483 //silently ignore attempts to delete missing already deleted groups ;-)
484 return true;
488 // delete group calendar events
489 $DB->delete_records('event', array('groupid'=>$groupid));
490 //first delete usage in groupings_groups
491 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
492 //delete members
493 $DB->delete_records('groups_members', array('groupid'=>$groupid));
494 //group itself last
495 $DB->delete_records('groups', array('id'=>$groupid));
497 // Delete all files associated with this group
498 $context = context_course::instance($group->courseid);
499 $fs = get_file_storage();
500 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
501 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
503 // Invalidate the grouping cache for the course
504 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
505 // Purge the group and grouping cache for users.
506 cache_helper::purge_by_definition('core', 'user_group_groupings');
508 // Trigger group event.
509 $params = array(
510 'context' => $context,
511 'objectid' => $groupid
513 $event = \core\event\group_deleted::create($params);
514 $event->add_record_snapshot('groups', $group);
515 $event->trigger();
517 return true;
521 * Delete grouping
523 * @param int $groupingorid
524 * @return bool success
526 function groups_delete_grouping($groupingorid) {
527 global $DB;
529 if (is_object($groupingorid)) {
530 $groupingid = $groupingorid->id;
531 $grouping = $groupingorid;
532 } else {
533 $groupingid = $groupingorid;
534 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
535 //silently ignore attempts to delete missing already deleted groupings ;-)
536 return true;
540 //first delete usage in groupings_groups
541 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
542 // remove the default groupingid from course
543 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
544 // remove the groupingid from all course modules
545 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
546 //group itself last
547 $DB->delete_records('groupings', array('id'=>$groupingid));
549 $context = context_course::instance($grouping->courseid);
550 $fs = get_file_storage();
551 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
552 foreach ($files as $file) {
553 $file->delete();
556 // Invalidate the grouping cache for the course
557 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
558 // Purge the group and grouping cache for users.
559 cache_helper::purge_by_definition('core', 'user_group_groupings');
561 // Trigger group event.
562 $params = array(
563 'context' => $context,
564 'objectid' => $groupingid
566 $event = \core\event\grouping_deleted::create($params);
567 $event->add_record_snapshot('groupings', $grouping);
568 $event->trigger();
570 return true;
574 * Remove all users (or one user) from all groups in course
576 * @param int $courseid
577 * @param int $userid 0 means all users
578 * @param bool $unused - formerly $showfeedback, is no longer used.
579 * @return bool success
581 function groups_delete_group_members($courseid, $userid=0, $unused=false) {
582 global $DB, $OUTPUT;
584 // Get the users in the course which are in a group.
585 $sql = "SELECT gm.id as gmid, gm.userid, g.*
586 FROM {groups_members} gm
587 INNER JOIN {groups} g
588 ON gm.groupid = g.id
589 WHERE g.courseid = :courseid";
590 $params = array();
591 $params['courseid'] = $courseid;
592 // Check if we want to delete a specific user.
593 if ($userid) {
594 $sql .= " AND gm.userid = :userid";
595 $params['userid'] = $userid;
597 $rs = $DB->get_recordset_sql($sql, $params);
598 foreach ($rs as $usergroup) {
599 groups_remove_member($usergroup, $usergroup->userid);
601 $rs->close();
603 // TODO MDL-41312 Remove events_trigger_legacy('groups_members_removed').
604 // This event is kept here for backwards compatibility, because it cannot be
605 // translated to a new event as it is wrong.
606 $eventdata = new stdClass();
607 $eventdata->courseid = $courseid;
608 $eventdata->userid = $userid;
609 events_trigger_legacy('groups_members_removed', $eventdata);
611 return true;
615 * Remove all groups from all groupings in course
617 * @param int $courseid
618 * @param bool $showfeedback
619 * @return bool success
621 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
622 global $DB, $OUTPUT;
624 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
625 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
626 array($courseid), '', 'groupid, groupingid');
628 foreach ($results as $result) {
629 groups_unassign_grouping($result->groupingid, $result->groupid, false);
631 $results->close();
633 // Invalidate the grouping cache for the course
634 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
635 // Purge the group and grouping cache for users.
636 cache_helper::purge_by_definition('core', 'user_group_groupings');
638 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_groups_removed').
639 // This event is kept here for backwards compatibility, because it cannot be
640 // translated to a new event as it is wrong.
641 events_trigger_legacy('groups_groupings_groups_removed', $courseid);
643 // no need to show any feedback here - we delete usually first groupings and then groups
645 return true;
649 * Delete all groups from course
651 * @param int $courseid
652 * @param bool $showfeedback
653 * @return bool success
655 function groups_delete_groups($courseid, $showfeedback=false) {
656 global $CFG, $DB, $OUTPUT;
658 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
659 foreach ($groups as $group) {
660 groups_delete_group($group);
662 $groups->close();
664 // Invalidate the grouping cache for the course
665 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
666 // Purge the group and grouping cache for users.
667 cache_helper::purge_by_definition('core', 'user_group_groupings');
669 // TODO MDL-41312 Remove events_trigger_legacy('groups_groups_deleted').
670 // This event is kept here for backwards compatibility, because it cannot be
671 // translated to a new event as it is wrong.
672 events_trigger_legacy('groups_groups_deleted', $courseid);
674 if ($showfeedback) {
675 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
678 return true;
682 * Delete all groupings from course
684 * @param int $courseid
685 * @param bool $showfeedback
686 * @return bool success
688 function groups_delete_groupings($courseid, $showfeedback=false) {
689 global $DB, $OUTPUT;
691 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
692 foreach ($groupings as $grouping) {
693 groups_delete_grouping($grouping);
695 $groupings->close();
697 // Invalidate the grouping cache for the course.
698 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
699 // Purge the group and grouping cache for users.
700 cache_helper::purge_by_definition('core', 'user_group_groupings');
702 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_deleted').
703 // This event is kept here for backwards compatibility, because it cannot be
704 // translated to a new event as it is wrong.
705 events_trigger_legacy('groups_groupings_deleted', $courseid);
707 if ($showfeedback) {
708 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
711 return true;
714 /* =================================== */
715 /* various functions used by groups UI */
716 /* =================================== */
719 * Obtains a list of the possible roles that group members might come from,
720 * on a course. Generally this includes only profile roles.
722 * @param context $context Context of course
723 * @return Array of role ID integers, or false if error/none.
725 function groups_get_possible_roles($context) {
726 $roles = get_profile_roles($context);
727 return array_keys($roles);
732 * Gets potential group members for grouping
734 * @param int $courseid The id of the course
735 * @param int $roleid The role to select users from
736 * @param mixed $source restrict to cohort, grouping or group id
737 * @param string $orderby The column to sort users by
738 * @param int $notingroup restrict to users not in existing groups
739 * @param bool $onlyactiveenrolments restrict to users who have an active enrolment in the course
740 * @return array An array of the users
742 function groups_get_potential_members($courseid, $roleid = null, $source = null,
743 $orderby = 'lastname ASC, firstname ASC',
744 $notingroup = null, $onlyactiveenrolments = false) {
745 global $DB;
747 $context = context_course::instance($courseid);
749 list($esql, $params) = get_enrolled_sql($context, '', 0, $onlyactiveenrolments);
751 $notingroupsql = "";
752 if ($notingroup) {
753 // We want to eliminate users that are already associated with a course group.
754 $notingroupsql = "u.id NOT IN (SELECT userid
755 FROM {groups_members}
756 WHERE groupid IN (SELECT id
757 FROM {groups}
758 WHERE courseid = :courseid))";
759 $params['courseid'] = $courseid;
762 if ($roleid) {
763 // We are looking for all users with this role assigned in this context or higher.
764 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
765 SQL_PARAMS_NAMED,
766 'relatedctx');
768 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
769 $where = "WHERE u.id IN (SELECT userid
770 FROM {role_assignments}
771 WHERE roleid = :roleid AND contextid $relatedctxsql)";
772 $where .= $notingroup ? "AND $notingroupsql" : "";
773 } else if ($notingroup) {
774 $where = "WHERE $notingroupsql";
775 } else {
776 $where = "";
779 $sourcejoin = "";
780 if (is_int($source)) {
781 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
782 $params['cohortid'] = $source;
783 } else {
784 // Auto-create groups from an existing cohort membership.
785 if (isset($source['cohortid'])) {
786 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
787 $params['cohortid'] = $source['cohortid'];
789 // Auto-create groups from an existing group membership.
790 if (isset($source['groupid'])) {
791 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
792 $params['groupid'] = $source['groupid'];
794 // Auto-create groups from an existing grouping membership.
795 if (isset($source['groupingid'])) {
796 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
797 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
798 $params['groupingid'] = $source['groupingid'];
802 $allusernamefields = get_all_user_name_fields(true, 'u');
803 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
804 FROM {user} u
805 JOIN ($esql) e ON e.id = u.id
806 $sourcejoin
807 $where
808 ORDER BY $orderby";
810 return $DB->get_records_sql($sql, $params);
815 * Parse a group name for characters to replace
817 * @param string $format The format a group name will follow
818 * @param int $groupnumber The number of the group to be used in the parsed format string
819 * @return string the parsed format string
821 function groups_parse_name($format, $groupnumber) {
822 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
823 $letter = 'A';
824 for($i=0; $i<$groupnumber; $i++) {
825 $letter++;
827 $str = str_replace('@', $letter, $format);
828 } else {
829 $str = str_replace('#', $groupnumber+1, $format);
831 return($str);
835 * Assigns group into grouping
837 * @param int groupingid
838 * @param int groupid
839 * @param int $timeadded The time the group was added to the grouping.
840 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
841 * @return bool true or exception
843 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
844 global $DB;
846 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
847 return true;
849 $assign = new stdClass();
850 $assign->groupingid = $groupingid;
851 $assign->groupid = $groupid;
852 if ($timeadded != null) {
853 $assign->timeadded = (integer)$timeadded;
854 } else {
855 $assign->timeadded = time();
857 $DB->insert_record('groupings_groups', $assign);
859 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
860 if ($invalidatecache) {
861 // Invalidate the grouping cache for the course
862 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
863 // Purge the group and grouping cache for users.
864 cache_helper::purge_by_definition('core', 'user_group_groupings');
867 // Trigger event.
868 $params = array(
869 'context' => context_course::instance($courseid),
870 'objectid' => $groupingid,
871 'other' => array('groupid' => $groupid)
873 $event = \core\event\grouping_group_assigned::create($params);
874 $event->trigger();
876 return true;
880 * Unassigns group from grouping
882 * @param int groupingid
883 * @param int groupid
884 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
885 * @return bool success
887 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
888 global $DB;
889 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
891 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
892 if ($invalidatecache) {
893 // Invalidate the grouping cache for the course
894 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
895 // Purge the group and grouping cache for users.
896 cache_helper::purge_by_definition('core', 'user_group_groupings');
899 // Trigger event.
900 $params = array(
901 'context' => context_course::instance($courseid),
902 'objectid' => $groupingid,
903 'other' => array('groupid' => $groupid)
905 $event = \core\event\grouping_group_unassigned::create($params);
906 $event->trigger();
908 return true;
912 * Lists users in a group based on their role on the course.
913 * Returns false if there's an error or there are no users in the group.
914 * Otherwise returns an array of role ID => role data, where role data includes:
915 * (role) $id, $shortname, $name
916 * $users: array of objects for each user which include the specified fields
917 * Users who do not have a role are stored in the returned array with key '-'
918 * and pseudo-role details (including a name, 'No role'). Users with multiple
919 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
920 * which roles each has by looking in the $roles array of the user object.
922 * @param int $groupid
923 * @param int $courseid Course ID (should match the group's course)
924 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
925 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
926 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
927 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
928 * @return array Complex array as described above
930 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
931 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
932 global $DB;
934 // Retrieve information about all users and their roles on the course or
935 // parent ('related') contexts
936 $context = context_course::instance($courseid);
938 // We are looking for all users with this role assigned in this context or higher.
939 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
941 if ($extrawheretest) {
942 $extrawheretest = ' AND ' . $extrawheretest;
945 if (is_null($sort)) {
946 list($sort, $sortparams) = users_order_by_sql('u');
947 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
950 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
951 FROM {groups_members} gm
952 JOIN {user} u ON u.id = gm.userid
953 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
954 LEFT JOIN {role} r ON r.id = ra.roleid
955 WHERE gm.groupid=:mgroupid
956 ".$extrawheretest."
957 ORDER BY r.sortorder, $sort";
958 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
959 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
961 return groups_calculate_role_people($rs, $context);
965 * Internal function used by groups_get_members_by_role to handle the
966 * results of a database query that includes a list of users and possible
967 * roles on a course.
969 * @param moodle_recordset $rs The record set (may be false)
970 * @param int $context ID of course context
971 * @return array As described in groups_get_members_by_role
973 function groups_calculate_role_people($rs, $context) {
974 global $CFG, $DB;
976 if (!$rs) {
977 return array();
980 $allroles = role_fix_names(get_all_roles($context), $context);
982 // Array of all involved roles
983 $roles = array();
984 // Array of all retrieved users
985 $users = array();
986 // Fill arrays
987 foreach ($rs as $rec) {
988 // Create information about user if this is a new one
989 if (!array_key_exists($rec->userid, $users)) {
990 // User data includes all the optional fields, but not any of the
991 // stuff we added to get the role details
992 $userdata = clone($rec);
993 unset($userdata->roleid);
994 unset($userdata->roleshortname);
995 unset($userdata->rolename);
996 unset($userdata->userid);
997 $userdata->id = $rec->userid;
999 // Make an array to hold the list of roles for this user
1000 $userdata->roles = array();
1001 $users[$rec->userid] = $userdata;
1003 // If user has a role...
1004 if (!is_null($rec->roleid)) {
1005 // Create information about role if this is a new one
1006 if (!array_key_exists($rec->roleid, $roles)) {
1007 $role = $allroles[$rec->roleid];
1008 $roledata = new stdClass();
1009 $roledata->id = $role->id;
1010 $roledata->shortname = $role->shortname;
1011 $roledata->name = $role->localname;
1012 $roledata->users = array();
1013 $roles[$roledata->id] = $roledata;
1015 // Record that user has role
1016 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
1019 $rs->close();
1021 // Return false if there weren't any users
1022 if (count($users) == 0) {
1023 return false;
1026 // Add pseudo-role for multiple roles
1027 $roledata = new stdClass();
1028 $roledata->name = get_string('multipleroles','role');
1029 $roledata->users = array();
1030 $roles['*'] = $roledata;
1032 $roledata = new stdClass();
1033 $roledata->name = get_string('noroles','role');
1034 $roledata->users = array();
1035 $roles[0] = $roledata;
1037 // Now we rearrange the data to store users by role
1038 foreach ($users as $userid=>$userdata) {
1039 $rolecount = count($userdata->roles);
1040 if ($rolecount == 0) {
1041 // does not have any roles
1042 $roleid = 0;
1043 } else if($rolecount > 1) {
1044 $roleid = '*';
1045 } else {
1046 $userrole = reset($userdata->roles);
1047 $roleid = $userrole->id;
1049 $roles[$roleid]->users[$userid] = $userdata;
1052 // Delete roles not used
1053 foreach ($roles as $key=>$roledata) {
1054 if (count($roledata->users)===0) {
1055 unset($roles[$key]);
1059 // Return list of roles containing their users
1060 return $roles;
1064 * Synchronises enrolments with the group membership
1066 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1067 * and group membership, such as enrol_cohort and enrol_meta .
1069 * @param string $enrolname name of enrolment method without prefix
1070 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1071 * @param string $gidfield name of the field in 'enrol' table that stores group id
1072 * @return array Returns the list of removed and added users. Each record contains fields:
1073 * userid, enrolid, courseid, groupid, groupname
1075 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1076 global $DB;
1077 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1078 $params = array(
1079 'enrolname' => $enrolname,
1080 'component' => 'enrol_'.$enrolname,
1081 'courseid' => $courseid
1084 $affectedusers = array(
1085 'removed' => array(),
1086 'added' => array()
1089 // Remove invalid.
1090 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1091 FROM {groups_members} gm
1092 JOIN {groups} g ON (g.id = gm.groupid)
1093 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1094 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1095 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1097 $rs = $DB->get_recordset_sql($sql, $params);
1098 foreach ($rs as $gm) {
1099 groups_remove_member($gm->groupid, $gm->userid);
1100 $affectedusers['removed'][] = $gm;
1102 $rs->close();
1104 // Add missing.
1105 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1106 FROM {user_enrolments} ue
1107 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1108 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1109 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1110 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1111 WHERE gm.id IS NULL";
1113 $rs = $DB->get_recordset_sql($sql, $params);
1114 foreach ($rs as $ue) {
1115 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1116 $affectedusers['added'][] = $ue;
1118 $rs->close();
1120 return $affectedusers;
1124 * Callback for inplace editable API.
1126 * @param string $itemtype - Only user_groups is supported.
1127 * @param string $itemid - Userid and groupid separated by a :
1128 * @param string $newvalue - json encoded list of groupids.
1129 * @return \core\output\inplace_editable
1131 function core_group_inplace_editable($itemtype, $itemid, $newvalue) {
1132 if ($itemtype === 'user_groups') {
1133 return \core_group\output\user_groups_editable::update($itemid, $newvalue);