Merge branch 'MDL-79638-311' of https://github.com/andrewnicols/moodle into MOODLE_31...
[moodle.git] / group / lib.php
blobc898e3ea5b8473cd006278972821d061edd80d93
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 // Group conversation messaging.
111 if ($conversation = \core_message\api::get_conversation_by_area('core_group', 'groups', $groupid, $context->id)) {
112 \core_message\api::add_members_to_conversation([$userid], $conversation->id);
115 // Trigger group event.
116 $params = array(
117 'context' => $context,
118 'objectid' => $groupid,
119 'relateduserid' => $userid,
120 'other' => array(
121 'component' => $member->component,
122 'itemid' => $member->itemid
125 $event = \core\event\group_member_added::create($params);
126 $event->add_record_snapshot('groups', $group);
127 $event->trigger();
129 return true;
133 * Checks whether the current user is permitted (using the normal UI) to
134 * remove a specific group member, assuming that they have access to remove
135 * group members in general.
137 * For automatically-created group member entries, this checks with the
138 * relevant plugin to see whether it is permitted. The default, if the plugin
139 * doesn't provide a function, is true.
141 * For other entries (and any which have already been deleted/don't exist) it
142 * just returns true.
144 * @param mixed $grouporid The group id or group object
145 * @param mixed $userorid The user id or user object
146 * @return bool True if permitted, false otherwise
148 function groups_remove_member_allowed($grouporid, $userorid) {
149 global $DB;
151 if (is_object($userorid)) {
152 $userid = $userorid->id;
153 } else {
154 $userid = $userorid;
156 if (is_object($grouporid)) {
157 $groupid = $grouporid->id;
158 } else {
159 $groupid = $grouporid;
162 // Get entry
163 if (!($entry = $DB->get_record('groups_members',
164 array('groupid' => $groupid, 'userid' => $userid), '*', IGNORE_MISSING))) {
165 // If the entry does not exist, they are allowed to remove it (this
166 // is consistent with groups_remove_member below).
167 return true;
170 // If the entry does not have a component value, they can remove it
171 if (empty($entry->component)) {
172 return true;
175 // It has a component value, so we need to call a plugin function (if it
176 // exists); the default is to allow removal
177 return component_callback($entry->component, 'allow_group_member_remove',
178 array($entry->itemid, $entry->groupid, $entry->userid), true);
182 * Deletes the link between the specified user and group.
184 * @param mixed $grouporid The group id or group object
185 * @param mixed $userorid The user id or user object
186 * @return bool True if deletion was successful, false otherwise
188 function groups_remove_member($grouporid, $userorid) {
189 global $DB;
191 if (is_object($userorid)) {
192 $userid = $userorid->id;
193 } else {
194 $userid = $userorid;
197 if (is_object($grouporid)) {
198 $groupid = $grouporid->id;
199 $group = $grouporid;
200 } else {
201 $groupid = $grouporid;
202 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
205 if (!groups_is_member($groupid, $userid)) {
206 return true;
209 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
211 // Update group info.
212 $time = time();
213 $DB->set_field('groups', 'timemodified', $time, array('id' => $groupid));
214 $group->timemodified = $time;
216 // Invalidate the group and grouping cache for users.
217 cache_helper::invalidate_by_definition('core', 'user_group_groupings', array(), array($userid));
219 // Group conversation messaging.
220 $context = context_course::instance($group->courseid);
221 if ($conversation = \core_message\api::get_conversation_by_area('core_group', 'groups', $groupid, $context->id)) {
222 \core_message\api::remove_members_from_conversation([$userid], $conversation->id);
225 // Trigger group event.
226 $params = array(
227 'context' => context_course::instance($group->courseid),
228 'objectid' => $groupid,
229 'relateduserid' => $userid
231 $event = \core\event\group_member_removed::create($params);
232 $event->add_record_snapshot('groups', $group);
233 $event->trigger();
235 return true;
239 * Add a new group
241 * @param stdClass $data group properties
242 * @param stdClass $editform
243 * @param array $editoroptions
244 * @return id of group or false if error
246 function groups_create_group($data, $editform = false, $editoroptions = false) {
247 global $CFG, $DB, $USER;
249 //check that courseid exists
250 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
251 $context = context_course::instance($course->id);
253 $data->timecreated = time();
254 $data->timemodified = $data->timecreated;
255 $data->name = trim($data->name);
256 if (isset($data->idnumber)) {
257 $data->idnumber = trim($data->idnumber);
258 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
259 throw new moodle_exception('idnumbertaken');
263 if ($editform and $editoroptions) {
264 $data->description = $data->description_editor['text'];
265 $data->descriptionformat = $data->description_editor['format'];
268 $data->id = $DB->insert_record('groups', $data);
270 if ($editform and $editoroptions) {
271 // Update description from editor with fixed files
272 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
273 $upd = new stdClass();
274 $upd->id = $data->id;
275 $upd->description = $data->description;
276 $upd->descriptionformat = $data->descriptionformat;
277 $DB->update_record('groups', $upd);
280 $group = $DB->get_record('groups', array('id'=>$data->id));
282 if ($editform) {
283 groups_update_group_icon($group, $data, $editform);
286 // Invalidate the grouping cache for the course
287 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($course->id));
289 // Group conversation messaging.
290 if (\core_message\api::can_create_group_conversation($USER->id, $context)) {
291 if (!empty($data->enablemessaging)) {
292 \core_message\api::create_conversation(
293 \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
295 $group->name,
296 \core_message\api::MESSAGE_CONVERSATION_ENABLED,
297 'core_group',
298 'groups',
299 $group->id,
300 $context->id);
304 // Trigger group event.
305 $params = array(
306 'context' => $context,
307 'objectid' => $group->id
309 $event = \core\event\group_created::create($params);
310 $event->add_record_snapshot('groups', $group);
311 $event->trigger();
313 return $group->id;
317 * Add a new grouping
319 * @param stdClass $data grouping properties
320 * @param array $editoroptions
321 * @return id of grouping or false if error
323 function groups_create_grouping($data, $editoroptions=null) {
324 global $DB;
326 $data->timecreated = time();
327 $data->timemodified = $data->timecreated;
328 $data->name = trim($data->name);
329 if (isset($data->idnumber)) {
330 $data->idnumber = trim($data->idnumber);
331 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
332 throw new moodle_exception('idnumbertaken');
336 if ($editoroptions !== null) {
337 $data->description = $data->description_editor['text'];
338 $data->descriptionformat = $data->description_editor['format'];
341 $id = $DB->insert_record('groupings', $data);
342 $data->id = $id;
344 if ($editoroptions !== null) {
345 $description = new stdClass;
346 $description->id = $data->id;
347 $description->description_editor = $data->description_editor;
348 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
349 $DB->update_record('groupings', $description);
352 // Invalidate the grouping cache for the course
353 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
355 // Trigger group event.
356 $params = array(
357 'context' => context_course::instance($data->courseid),
358 'objectid' => $id
360 $event = \core\event\grouping_created::create($params);
361 $event->trigger();
363 return $id;
367 * Update the group icon from form data
369 * @param stdClass $group group information
370 * @param stdClass $data
371 * @param stdClass $editform
373 function groups_update_group_icon($group, $data, $editform) {
374 global $CFG, $DB;
375 require_once("$CFG->libdir/gdlib.php");
377 $fs = get_file_storage();
378 $context = context_course::instance($group->courseid, MUST_EXIST);
379 $newpicture = $group->picture;
381 if (!empty($data->deletepicture)) {
382 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
383 $newpicture = 0;
384 } else if ($iconfile = $editform->save_temp_file('imagefile')) {
385 if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
386 $newpicture = $rev;
387 } else {
388 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
389 $newpicture = 0;
391 @unlink($iconfile);
394 if ($newpicture != $group->picture) {
395 $DB->set_field('groups', 'picture', $newpicture, array('id' => $group->id));
396 $group->picture = $newpicture;
398 // Invalidate the group data as we've updated the group record.
399 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
404 * Update group
406 * @param stdClass $data group properties (with magic quotes)
407 * @param stdClass $editform
408 * @param array $editoroptions
409 * @return bool true or exception
411 function groups_update_group($data, $editform = false, $editoroptions = false) {
412 global $CFG, $DB, $USER;
414 $context = context_course::instance($data->courseid);
416 $data->timemodified = time();
417 if (isset($data->name)) {
418 $data->name = trim($data->name);
420 if (isset($data->idnumber)) {
421 $data->idnumber = trim($data->idnumber);
422 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
423 throw new moodle_exception('idnumbertaken');
427 if ($editform and $editoroptions) {
428 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
431 $DB->update_record('groups', $data);
433 // Invalidate the group data.
434 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
436 $group = $DB->get_record('groups', array('id'=>$data->id));
438 if ($editform) {
439 groups_update_group_icon($group, $data, $editform);
442 // Group conversation messaging.
443 if (\core_message\api::can_create_group_conversation($USER->id, $context)) {
444 if ($conversation = \core_message\api::get_conversation_by_area('core_group', 'groups', $group->id, $context->id)) {
445 if ($data->enablemessaging && $data->enablemessaging != $conversation->enabled) {
446 \core_message\api::enable_conversation($conversation->id);
448 if (!$data->enablemessaging && $data->enablemessaging != $conversation->enabled) {
449 \core_message\api::disable_conversation($conversation->id);
451 \core_message\api::update_conversation_name($conversation->id, $group->name);
452 } else {
453 if (!empty($data->enablemessaging)) {
454 $conversation = \core_message\api::create_conversation(
455 \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
457 $group->name,
458 \core_message\api::MESSAGE_CONVERSATION_ENABLED,
459 'core_group',
460 'groups',
461 $group->id,
462 $context->id
465 // Add members to conversation if they exists in the group.
466 if ($groupmemberroles = groups_get_members_by_role($group->id, $group->courseid, 'u.id')) {
467 $users = [];
468 foreach ($groupmemberroles as $roleid => $roledata) {
469 foreach ($roledata->users as $member) {
470 $users[] = $member->id;
473 \core_message\api::add_members_to_conversation($users, $conversation->id);
479 // Trigger group event.
480 $params = array(
481 'context' => $context,
482 'objectid' => $group->id
484 $event = \core\event\group_updated::create($params);
485 $event->add_record_snapshot('groups', $group);
486 $event->trigger();
488 return true;
492 * Update grouping
494 * @param stdClass $data grouping properties (with magic quotes)
495 * @param array $editoroptions
496 * @return bool true or exception
498 function groups_update_grouping($data, $editoroptions=null) {
499 global $DB;
500 $data->timemodified = time();
501 if (isset($data->name)) {
502 $data->name = trim($data->name);
504 if (isset($data->idnumber)) {
505 $data->idnumber = trim($data->idnumber);
506 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
507 throw new moodle_exception('idnumbertaken');
510 if ($editoroptions !== null) {
511 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
513 $DB->update_record('groupings', $data);
515 // Invalidate the group data.
516 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
518 // Trigger group event.
519 $params = array(
520 'context' => context_course::instance($data->courseid),
521 'objectid' => $data->id
523 $event = \core\event\grouping_updated::create($params);
524 $event->trigger();
526 return true;
530 * Delete a group best effort, first removing members and links with courses and groupings.
531 * Removes group avatar too.
533 * @param mixed $grouporid The id of group to delete or full group object
534 * @return bool True if deletion was successful, false otherwise
536 function groups_delete_group($grouporid) {
537 global $CFG, $DB;
538 require_once("$CFG->libdir/gdlib.php");
540 if (is_object($grouporid)) {
541 $groupid = $grouporid->id;
542 $group = $grouporid;
543 } else {
544 $groupid = $grouporid;
545 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
546 //silently ignore attempts to delete missing already deleted groups ;-)
547 return true;
551 $context = context_course::instance($group->courseid);
553 // delete group calendar events
554 $DB->delete_records('event', array('groupid'=>$groupid));
555 //first delete usage in groupings_groups
556 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
557 //delete members
558 $DB->delete_records('groups_members', array('groupid'=>$groupid));
560 // Delete any members in a conversation related to this group.
561 if ($conversation = \core_message\api::get_conversation_by_area('core_group', 'groups', $groupid, $context->id)) {
562 \core_message\api::delete_all_conversation_data($conversation->id);
565 //group itself last
566 $DB->delete_records('groups', array('id'=>$groupid));
568 // Delete all files associated with this group
569 $context = context_course::instance($group->courseid);
570 $fs = get_file_storage();
571 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
572 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
574 // Invalidate the grouping cache for the course
575 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
576 // Purge the group and grouping cache for users.
577 cache_helper::purge_by_definition('core', 'user_group_groupings');
579 // Trigger group event.
580 $params = array(
581 'context' => $context,
582 'objectid' => $groupid
584 $event = \core\event\group_deleted::create($params);
585 $event->add_record_snapshot('groups', $group);
586 $event->trigger();
588 return true;
592 * Delete grouping
594 * @param int $groupingorid
595 * @return bool success
597 function groups_delete_grouping($groupingorid) {
598 global $DB;
600 if (is_object($groupingorid)) {
601 $groupingid = $groupingorid->id;
602 $grouping = $groupingorid;
603 } else {
604 $groupingid = $groupingorid;
605 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
606 //silently ignore attempts to delete missing already deleted groupings ;-)
607 return true;
611 //first delete usage in groupings_groups
612 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
613 // remove the default groupingid from course
614 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
615 // remove the groupingid from all course modules
616 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
617 //group itself last
618 $DB->delete_records('groupings', array('id'=>$groupingid));
620 $context = context_course::instance($grouping->courseid);
621 $fs = get_file_storage();
622 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
623 foreach ($files as $file) {
624 $file->delete();
627 // Invalidate the grouping cache for the course
628 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
629 // Purge the group and grouping cache for users.
630 cache_helper::purge_by_definition('core', 'user_group_groupings');
632 // Trigger group event.
633 $params = array(
634 'context' => $context,
635 'objectid' => $groupingid
637 $event = \core\event\grouping_deleted::create($params);
638 $event->add_record_snapshot('groupings', $grouping);
639 $event->trigger();
641 return true;
645 * Remove all users (or one user) from all groups in course
647 * @param int $courseid
648 * @param int $userid 0 means all users
649 * @param bool $unused - formerly $showfeedback, is no longer used.
650 * @return bool success
652 function groups_delete_group_members($courseid, $userid=0, $unused=false) {
653 global $DB, $OUTPUT;
655 // Get the users in the course which are in a group.
656 $sql = "SELECT gm.id as gmid, gm.userid, g.*
657 FROM {groups_members} gm
658 INNER JOIN {groups} g
659 ON gm.groupid = g.id
660 WHERE g.courseid = :courseid";
661 $params = array();
662 $params['courseid'] = $courseid;
663 // Check if we want to delete a specific user.
664 if ($userid) {
665 $sql .= " AND gm.userid = :userid";
666 $params['userid'] = $userid;
668 $rs = $DB->get_recordset_sql($sql, $params);
669 foreach ($rs as $usergroup) {
670 groups_remove_member($usergroup, $usergroup->userid);
672 $rs->close();
674 return true;
678 * Remove all groups from all groupings in course
680 * @param int $courseid
681 * @param bool $showfeedback
682 * @return bool success
684 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
685 global $DB, $OUTPUT;
687 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
688 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
689 array($courseid), '', 'groupid, groupingid');
691 foreach ($results as $result) {
692 groups_unassign_grouping($result->groupingid, $result->groupid, false);
694 $results->close();
696 // Invalidate the grouping cache for the course
697 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
698 // Purge the group and grouping cache for users.
699 cache_helper::purge_by_definition('core', 'user_group_groupings');
701 // no need to show any feedback here - we delete usually first groupings and then groups
703 return true;
707 * Delete all groups from course
709 * @param int $courseid
710 * @param bool $showfeedback
711 * @return bool success
713 function groups_delete_groups($courseid, $showfeedback=false) {
714 global $CFG, $DB, $OUTPUT;
716 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
717 foreach ($groups as $group) {
718 groups_delete_group($group);
720 $groups->close();
722 // Invalidate the grouping cache for the course
723 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
724 // Purge the group and grouping cache for users.
725 cache_helper::purge_by_definition('core', 'user_group_groupings');
727 if ($showfeedback) {
728 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
731 return true;
735 * Delete all groupings from course
737 * @param int $courseid
738 * @param bool $showfeedback
739 * @return bool success
741 function groups_delete_groupings($courseid, $showfeedback=false) {
742 global $DB, $OUTPUT;
744 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
745 foreach ($groupings as $grouping) {
746 groups_delete_grouping($grouping);
748 $groupings->close();
750 // Invalidate the grouping cache for the course.
751 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
752 // Purge the group and grouping cache for users.
753 cache_helper::purge_by_definition('core', 'user_group_groupings');
755 if ($showfeedback) {
756 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
759 return true;
762 /* =================================== */
763 /* various functions used by groups UI */
764 /* =================================== */
767 * Obtains a list of the possible roles that group members might come from,
768 * on a course. Generally this includes only profile roles.
770 * @param context $context Context of course
771 * @return Array of role ID integers, or false if error/none.
773 function groups_get_possible_roles($context) {
774 $roles = get_profile_roles($context);
775 return array_keys($roles);
780 * Gets potential group members for grouping
782 * @param int $courseid The id of the course
783 * @param int $roleid The role to select users from
784 * @param mixed $source restrict to cohort, grouping or group id
785 * @param string $orderby The column to sort users by
786 * @param int $notingroup restrict to users not in existing groups
787 * @param bool $onlyactiveenrolments restrict to users who have an active enrolment in the course
788 * @param array $extrafields Extra user fields to return
789 * @return array An array of the users
791 function groups_get_potential_members($courseid, $roleid = null, $source = null,
792 $orderby = 'lastname ASC, firstname ASC',
793 $notingroup = null, $onlyactiveenrolments = false, $extrafields = []) {
794 global $DB;
796 $context = context_course::instance($courseid);
798 list($esql, $params) = get_enrolled_sql($context, '', 0, $onlyactiveenrolments);
800 $notingroupsql = "";
801 if ($notingroup) {
802 // We want to eliminate users that are already associated with a course group.
803 $notingroupsql = "u.id NOT IN (SELECT userid
804 FROM {groups_members}
805 WHERE groupid IN (SELECT id
806 FROM {groups}
807 WHERE courseid = :courseid))";
808 $params['courseid'] = $courseid;
811 if ($roleid) {
812 // We are looking for all users with this role assigned in this context or higher.
813 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
814 SQL_PARAMS_NAMED,
815 'relatedctx');
817 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
818 $where = "WHERE u.id IN (SELECT userid
819 FROM {role_assignments}
820 WHERE roleid = :roleid AND contextid $relatedctxsql)";
821 $where .= $notingroup ? "AND $notingroupsql" : "";
822 } else if ($notingroup) {
823 $where = "WHERE $notingroupsql";
824 } else {
825 $where = "";
828 $sourcejoin = "";
829 if (is_int($source)) {
830 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
831 $params['cohortid'] = $source;
832 } else {
833 // Auto-create groups from an existing cohort membership.
834 if (isset($source['cohortid'])) {
835 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
836 $params['cohortid'] = $source['cohortid'];
838 // Auto-create groups from an existing group membership.
839 if (isset($source['groupid'])) {
840 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
841 $params['groupid'] = $source['groupid'];
843 // Auto-create groups from an existing grouping membership.
844 if (isset($source['groupingid'])) {
845 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
846 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
847 $params['groupingid'] = $source['groupingid'];
851 $userfieldsapi = \core_user\fields::for_userpic()->including(...$extrafields);
852 $allusernamefields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
853 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
854 FROM {user} u
855 JOIN ($esql) e ON e.id = u.id
856 $sourcejoin
857 $where
858 ORDER BY $orderby";
860 return $DB->get_records_sql($sql, $params);
865 * Parse a group name for characters to replace
867 * @param string $format The format a group name will follow
868 * @param int $groupnumber The number of the group to be used in the parsed format string
869 * @return string the parsed format string
871 function groups_parse_name($format, $groupnumber) {
872 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
873 $letter = 'A';
874 for($i=0; $i<$groupnumber; $i++) {
875 $letter++;
877 $str = str_replace('@', $letter, $format);
878 } else {
879 $str = str_replace('#', $groupnumber+1, $format);
881 return($str);
885 * Assigns group into grouping
887 * @param int groupingid
888 * @param int groupid
889 * @param int $timeadded The time the group was added to the grouping.
890 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
891 * @return bool true or exception
893 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
894 global $DB;
896 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
897 return true;
899 $assign = new stdClass();
900 $assign->groupingid = $groupingid;
901 $assign->groupid = $groupid;
902 if ($timeadded != null) {
903 $assign->timeadded = (integer)$timeadded;
904 } else {
905 $assign->timeadded = time();
907 $DB->insert_record('groupings_groups', $assign);
909 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
910 if ($invalidatecache) {
911 // Invalidate the grouping cache for the course
912 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
913 // Purge the group and grouping cache for users.
914 cache_helper::purge_by_definition('core', 'user_group_groupings');
917 // Trigger event.
918 $params = array(
919 'context' => context_course::instance($courseid),
920 'objectid' => $groupingid,
921 'other' => array('groupid' => $groupid)
923 $event = \core\event\grouping_group_assigned::create($params);
924 $event->trigger();
926 return true;
930 * Unassigns group from grouping
932 * @param int groupingid
933 * @param int groupid
934 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
935 * @return bool success
937 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
938 global $DB;
939 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
941 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
942 if ($invalidatecache) {
943 // Invalidate the grouping cache for the course
944 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
945 // Purge the group and grouping cache for users.
946 cache_helper::purge_by_definition('core', 'user_group_groupings');
949 // Trigger event.
950 $params = array(
951 'context' => context_course::instance($courseid),
952 'objectid' => $groupingid,
953 'other' => array('groupid' => $groupid)
955 $event = \core\event\grouping_group_unassigned::create($params);
956 $event->trigger();
958 return true;
962 * Lists users in a group based on their role on the course.
963 * Returns false if there's an error or there are no users in the group.
964 * Otherwise returns an array of role ID => role data, where role data includes:
965 * (role) $id, $shortname, $name
966 * $users: array of objects for each user which include the specified fields
967 * Users who do not have a role are stored in the returned array with key '-'
968 * and pseudo-role details (including a name, 'No role'). Users with multiple
969 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
970 * which roles each has by looking in the $roles array of the user object.
972 * @param int $groupid
973 * @param int $courseid Course ID (should match the group's course)
974 * @param string $fields List of fields from user table (prefixed with u) and joined tables, default 'u.*'
975 * @param string|null $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
976 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
977 * @param array $whereorsortparams any parameters required by $extrawheretest or $joins (named parameters).
978 * @param string $joins any joins required to get the specified fields.
979 * @return array Complex array as described above
981 function groups_get_members_by_role(int $groupid, int $courseid, string $fields = 'u.*',
982 ?string $sort = null, string $extrawheretest = '', array $whereorsortparams = [], string $joins = '') {
983 global $DB;
985 // Retrieve information about all users and their roles on the course or
986 // parent ('related') contexts
987 $context = context_course::instance($courseid);
989 // We are looking for all users with this role assigned in this context or higher.
990 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
992 if ($extrawheretest) {
993 $extrawheretest = ' AND ' . $extrawheretest;
996 if (is_null($sort)) {
997 list($sort, $sortparams) = users_order_by_sql('u');
998 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
1001 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
1002 FROM {groups_members} gm
1003 JOIN {user} u ON u.id = gm.userid
1004 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
1005 LEFT JOIN {role} r ON r.id = ra.roleid
1006 $joins
1007 WHERE gm.groupid=:mgroupid
1008 ".$extrawheretest."
1009 ORDER BY r.sortorder, $sort";
1010 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
1011 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
1013 return groups_calculate_role_people($rs, $context);
1017 * Internal function used by groups_get_members_by_role to handle the
1018 * results of a database query that includes a list of users and possible
1019 * roles on a course.
1021 * @param moodle_recordset $rs The record set (may be false)
1022 * @param int $context ID of course context
1023 * @return array As described in groups_get_members_by_role
1025 function groups_calculate_role_people($rs, $context) {
1026 global $CFG, $DB;
1028 if (!$rs) {
1029 return array();
1032 $allroles = role_fix_names(get_all_roles($context), $context);
1033 $visibleroles = get_viewable_roles($context);
1035 // Array of all involved roles
1036 $roles = array();
1037 // Array of all retrieved users
1038 $users = array();
1039 // Fill arrays
1040 foreach ($rs as $rec) {
1041 // Create information about user if this is a new one
1042 if (!array_key_exists($rec->userid, $users)) {
1043 // User data includes all the optional fields, but not any of the
1044 // stuff we added to get the role details
1045 $userdata = clone($rec);
1046 unset($userdata->roleid);
1047 unset($userdata->roleshortname);
1048 unset($userdata->rolename);
1049 unset($userdata->userid);
1050 $userdata->id = $rec->userid;
1052 // Make an array to hold the list of roles for this user
1053 $userdata->roles = array();
1054 $users[$rec->userid] = $userdata;
1056 // If user has a role...
1057 if (!is_null($rec->roleid)) {
1058 // Create information about role if this is a new one
1059 if (!array_key_exists($rec->roleid, $roles)) {
1060 $role = $allroles[$rec->roleid];
1061 $roledata = new stdClass();
1062 $roledata->id = $role->id;
1063 $roledata->shortname = $role->shortname;
1064 $roledata->name = $role->localname;
1065 $roledata->users = array();
1066 $roles[$roledata->id] = $roledata;
1068 // Record that user has role
1069 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
1072 $rs->close();
1074 // Return false if there weren't any users
1075 if (count($users) == 0) {
1076 return false;
1079 // Add pseudo-role for multiple roles
1080 $roledata = new stdClass();
1081 $roledata->name = get_string('multipleroles','role');
1082 $roledata->users = array();
1083 $roles['*'] = $roledata;
1085 $roledata = new stdClass();
1086 $roledata->name = get_string('noroles','role');
1087 $roledata->users = array();
1088 $roles[0] = $roledata;
1090 // Now we rearrange the data to store users by role
1091 foreach ($users as $userid=>$userdata) {
1092 $visibleuserroles = array_intersect_key($userdata->roles, $visibleroles);
1093 $rolecount = count($visibleuserroles);
1094 if ($rolecount == 0) {
1095 // does not have any roles
1096 $roleid = 0;
1097 } else if($rolecount > 1) {
1098 $roleid = '*';
1099 } else {
1100 $userrole = reset($visibleuserroles);
1101 $roleid = $userrole->id;
1103 $roles[$roleid]->users[$userid] = $userdata;
1106 // Delete roles not used
1107 foreach ($roles as $key=>$roledata) {
1108 if (count($roledata->users)===0) {
1109 unset($roles[$key]);
1113 // Return list of roles containing their users
1114 return $roles;
1118 * Synchronises enrolments with the group membership
1120 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1121 * and group membership, such as enrol_cohort and enrol_meta .
1123 * @param string $enrolname name of enrolment method without prefix
1124 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1125 * @param string $gidfield name of the field in 'enrol' table that stores group id
1126 * @return array Returns the list of removed and added users. Each record contains fields:
1127 * userid, enrolid, courseid, groupid, groupname
1129 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1130 global $DB;
1131 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1132 $params = array(
1133 'enrolname' => $enrolname,
1134 'component' => 'enrol_'.$enrolname,
1135 'courseid' => $courseid
1138 $affectedusers = array(
1139 'removed' => array(),
1140 'added' => array()
1143 // Remove invalid.
1144 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1145 FROM {groups_members} gm
1146 JOIN {groups} g ON (g.id = gm.groupid)
1147 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1148 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1149 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1151 $rs = $DB->get_recordset_sql($sql, $params);
1152 foreach ($rs as $gm) {
1153 groups_remove_member($gm->groupid, $gm->userid);
1154 $affectedusers['removed'][] = $gm;
1156 $rs->close();
1158 // Add missing.
1159 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1160 FROM {user_enrolments} ue
1161 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1162 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1163 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1164 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1165 WHERE gm.id IS NULL";
1167 $rs = $DB->get_recordset_sql($sql, $params);
1168 foreach ($rs as $ue) {
1169 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1170 $affectedusers['added'][] = $ue;
1172 $rs->close();
1174 return $affectedusers;
1178 * Callback for inplace editable API.
1180 * @param string $itemtype - Only user_groups is supported.
1181 * @param string $itemid - Userid and groupid separated by a :
1182 * @param string $newvalue - json encoded list of groupids.
1183 * @return \core\output\inplace_editable
1185 function core_group_inplace_editable($itemtype, $itemid, $newvalue) {
1186 if ($itemtype === 'user_groups') {
1187 return \core_group\output\user_groups_editable::update($itemid, $newvalue);