Merge branch 'MDL-79673' of https://github.com/paulholden/moodle
[moodle.git] / group / lib.php
blobed44961f48a498bed755d4efcb86ad2664489abb
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 int id of group or throws an exception on error
245 * @throws moodle_exception
247 function groups_create_group($data, $editform = false, $editoroptions = false) {
248 global $CFG, $DB, $USER;
250 //check that courseid exists
251 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
252 $context = context_course::instance($course->id);
254 $data->timecreated = time();
255 $data->timemodified = $data->timecreated;
256 $data->name = trim($data->name);
257 if (isset($data->idnumber)) {
258 $data->idnumber = trim($data->idnumber);
259 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
260 throw new moodle_exception('idnumbertaken');
264 $data->visibility ??= GROUPS_VISIBILITY_ALL;
266 if (!in_array($data->visibility, [GROUPS_VISIBILITY_ALL, GROUPS_VISIBILITY_MEMBERS])) {
267 $data->participation = false;
268 $data->enablemessaging = false;
271 if ($editform and $editoroptions) {
272 $data->description = $data->description_editor['text'];
273 $data->descriptionformat = $data->description_editor['format'];
276 $data->id = $DB->insert_record('groups', $data);
278 $handler = \core_group\customfield\group_handler::create();
279 $handler->instance_form_save($data, true);
281 if ($editform and $editoroptions) {
282 // Update description from editor with fixed files
283 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
284 $upd = new stdClass();
285 $upd->id = $data->id;
286 $upd->description = $data->description;
287 $upd->descriptionformat = $data->descriptionformat;
288 $DB->update_record('groups', $upd);
291 $group = $DB->get_record('groups', array('id'=>$data->id));
293 if ($editform) {
294 groups_update_group_icon($group, $data, $editform);
297 // Invalidate the grouping cache for the course
298 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($course->id));
299 // Rebuild the coursehiddengroups cache for the course.
300 \core_group\visibility::update_hiddengroups_cache($course->id);
302 // Group conversation messaging.
303 if (\core_message\api::can_create_group_conversation($USER->id, $context)) {
304 if (!empty($data->enablemessaging)) {
305 \core_message\api::create_conversation(
306 \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
308 $group->name,
309 \core_message\api::MESSAGE_CONVERSATION_ENABLED,
310 'core_group',
311 'groups',
312 $group->id,
313 $context->id);
317 // Trigger group event.
318 $params = array(
319 'context' => $context,
320 'objectid' => $group->id
322 $event = \core\event\group_created::create($params);
323 $event->add_record_snapshot('groups', $group);
324 $event->trigger();
326 return $group->id;
330 * Add a new grouping
332 * @param stdClass $data grouping properties
333 * @param array $editoroptions
334 * @return int id of grouping or throws an exception on error
335 * @throws moodle_exception
337 function groups_create_grouping($data, $editoroptions=null) {
338 global $DB;
340 $data->timecreated = time();
341 $data->timemodified = $data->timecreated;
342 $data->name = trim($data->name);
343 if (isset($data->idnumber)) {
344 $data->idnumber = trim($data->idnumber);
345 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
346 throw new moodle_exception('idnumbertaken');
350 if ($editoroptions !== null) {
351 $data->description = $data->description_editor['text'];
352 $data->descriptionformat = $data->description_editor['format'];
355 $id = $DB->insert_record('groupings', $data);
356 $data->id = $id;
358 $handler = \core_group\customfield\grouping_handler::create();
359 $handler->instance_form_save($data, true);
361 if ($editoroptions !== null) {
362 $description = new stdClass;
363 $description->id = $data->id;
364 $description->description_editor = $data->description_editor;
365 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
366 $DB->update_record('groupings', $description);
369 // Invalidate the grouping cache for the course
370 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
372 // Trigger group event.
373 $params = array(
374 'context' => context_course::instance($data->courseid),
375 'objectid' => $id
377 $event = \core\event\grouping_created::create($params);
378 $event->trigger();
380 return $id;
384 * Update the group icon from form data
386 * @param stdClass $group group information
387 * @param stdClass $data
388 * @param stdClass $editform
390 function groups_update_group_icon($group, $data, $editform) {
391 global $CFG, $DB;
392 require_once("$CFG->libdir/gdlib.php");
394 $fs = get_file_storage();
395 $context = context_course::instance($group->courseid, MUST_EXIST);
396 $newpicture = $group->picture;
398 if (!empty($data->deletepicture)) {
399 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
400 $newpicture = 0;
401 } else if ($iconfile = $editform->save_temp_file('imagefile')) {
402 if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
403 $newpicture = $rev;
404 } else {
405 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
406 $newpicture = 0;
408 @unlink($iconfile);
411 if ($newpicture != $group->picture) {
412 $DB->set_field('groups', 'picture', $newpicture, array('id' => $group->id));
413 $group->picture = $newpicture;
415 // Invalidate the group data as we've updated the group record.
416 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
421 * Update group
423 * @param stdClass $data group properties (with magic quotes)
424 * @param stdClass $editform
425 * @param array $editoroptions
426 * @return bool true or exception
428 function groups_update_group($data, $editform = false, $editoroptions = false) {
429 global $CFG, $DB, $USER;
431 $context = context_course::instance($data->courseid);
433 $data->timemodified = time();
434 if (isset($data->name)) {
435 $data->name = trim($data->name);
437 if (isset($data->idnumber)) {
438 $data->idnumber = trim($data->idnumber);
439 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
440 throw new moodle_exception('idnumbertaken');
443 if (isset($data->visibility) && !in_array($data->visibility, [GROUPS_VISIBILITY_ALL, GROUPS_VISIBILITY_MEMBERS])) {
444 $data->participation = false;
445 $data->enablemessaging = false;
448 if ($editform and $editoroptions) {
449 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
452 $DB->update_record('groups', $data);
454 $handler = \core_group\customfield\group_handler::create();
455 $handler->instance_form_save($data);
457 // Invalidate the group data.
458 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
459 // Rebuild the coursehiddengroups cache for the course.
460 \core_group\visibility::update_hiddengroups_cache($data->courseid);
462 $group = $DB->get_record('groups', array('id'=>$data->id));
464 if ($editform) {
465 groups_update_group_icon($group, $data, $editform);
468 // Group conversation messaging.
469 if (\core_message\api::can_create_group_conversation($USER->id, $context)) {
470 if ($conversation = \core_message\api::get_conversation_by_area('core_group', 'groups', $group->id, $context->id)) {
471 if ($data->enablemessaging && $data->enablemessaging != $conversation->enabled) {
472 \core_message\api::enable_conversation($conversation->id);
474 if (!$data->enablemessaging && $data->enablemessaging != $conversation->enabled) {
475 \core_message\api::disable_conversation($conversation->id);
477 \core_message\api::update_conversation_name($conversation->id, $group->name);
478 } else {
479 if (!empty($data->enablemessaging)) {
480 $conversation = \core_message\api::create_conversation(
481 \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP,
483 $group->name,
484 \core_message\api::MESSAGE_CONVERSATION_ENABLED,
485 'core_group',
486 'groups',
487 $group->id,
488 $context->id
491 // Add members to conversation if they exists in the group.
492 if ($groupmemberroles = groups_get_members_by_role($group->id, $group->courseid, 'u.id')) {
493 $users = [];
494 foreach ($groupmemberroles as $roleid => $roledata) {
495 foreach ($roledata->users as $member) {
496 $users[] = $member->id;
499 \core_message\api::add_members_to_conversation($users, $conversation->id);
505 // Trigger group event.
506 $params = array(
507 'context' => $context,
508 'objectid' => $group->id
510 $event = \core\event\group_updated::create($params);
511 $event->add_record_snapshot('groups', $group);
512 $event->trigger();
514 return true;
518 * Update grouping
520 * @param stdClass $data grouping properties (with magic quotes)
521 * @param array $editoroptions
522 * @return bool true or exception
524 function groups_update_grouping($data, $editoroptions=null) {
525 global $DB;
526 $data->timemodified = time();
527 if (isset($data->name)) {
528 $data->name = trim($data->name);
530 if (isset($data->idnumber)) {
531 $data->idnumber = trim($data->idnumber);
532 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
533 throw new moodle_exception('idnumbertaken');
536 if ($editoroptions !== null) {
537 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
539 $DB->update_record('groupings', $data);
541 $handler = \core_group\customfield\grouping_handler::create();
542 $handler->instance_form_save($data);
544 // Invalidate the group data.
545 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
547 // Trigger group event.
548 $params = array(
549 'context' => context_course::instance($data->courseid),
550 'objectid' => $data->id
552 $event = \core\event\grouping_updated::create($params);
553 $event->trigger();
555 return true;
559 * Delete a group best effort, first removing members and links with courses and groupings.
560 * Removes group avatar too.
562 * @param mixed $grouporid The id of group to delete or full group object
563 * @return bool True if deletion was successful, false otherwise
565 function groups_delete_group($grouporid) {
566 global $CFG, $DB;
567 require_once("$CFG->libdir/gdlib.php");
569 if (is_object($grouporid)) {
570 $groupid = $grouporid->id;
571 $group = $grouporid;
572 } else {
573 $groupid = $grouporid;
574 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
575 //silently ignore attempts to delete missing already deleted groups ;-)
576 return true;
580 $context = context_course::instance($group->courseid);
582 // delete group calendar events
583 $DB->delete_records('event', array('groupid'=>$groupid));
584 //first delete usage in groupings_groups
585 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
586 //delete members
587 $DB->delete_records('groups_members', array('groupid'=>$groupid));
589 // Delete any members in a conversation related to this group.
590 if ($conversation = \core_message\api::get_conversation_by_area('core_group', 'groups', $groupid, $context->id)) {
591 \core_message\api::delete_all_conversation_data($conversation->id);
594 //group itself last
595 $DB->delete_records('groups', array('id'=>$groupid));
597 // Delete all files associated with this group
598 $context = context_course::instance($group->courseid);
599 $fs = get_file_storage();
600 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
601 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
603 // Invalidate the grouping cache for the course
604 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
605 // Purge the group and grouping cache for users.
606 cache_helper::purge_by_definition('core', 'user_group_groupings');
607 // Rebuild the coursehiddengroups cache for the course.
608 \core_group\visibility::update_hiddengroups_cache($group->courseid);
610 // Trigger group event.
611 $params = array(
612 'context' => $context,
613 'objectid' => $groupid
615 $event = \core\event\group_deleted::create($params);
616 $event->add_record_snapshot('groups', $group);
617 $event->trigger();
619 return true;
623 * Delete grouping
625 * @param int $groupingorid
626 * @return bool success
628 function groups_delete_grouping($groupingorid) {
629 global $DB;
631 if (is_object($groupingorid)) {
632 $groupingid = $groupingorid->id;
633 $grouping = $groupingorid;
634 } else {
635 $groupingid = $groupingorid;
636 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
637 //silently ignore attempts to delete missing already deleted groupings ;-)
638 return true;
642 //first delete usage in groupings_groups
643 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
644 // remove the default groupingid from course
645 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
646 // remove the groupingid from all course modules
647 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
648 //group itself last
649 $DB->delete_records('groupings', array('id'=>$groupingid));
651 $context = context_course::instance($grouping->courseid);
652 $fs = get_file_storage();
653 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
654 foreach ($files as $file) {
655 $file->delete();
658 // Invalidate the grouping cache for the course
659 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
660 // Purge the group and grouping cache for users.
661 cache_helper::purge_by_definition('core', 'user_group_groupings');
663 // Trigger group event.
664 $params = array(
665 'context' => $context,
666 'objectid' => $groupingid
668 $event = \core\event\grouping_deleted::create($params);
669 $event->add_record_snapshot('groupings', $grouping);
670 $event->trigger();
672 return true;
676 * Remove all users (or one user) from all groups in course
678 * @param int $courseid
679 * @param int $userid 0 means all users
680 * @param bool $unused - formerly $showfeedback, is no longer used.
681 * @return bool success
683 function groups_delete_group_members($courseid, $userid=0, $unused=false) {
684 global $DB, $OUTPUT;
686 // Get the users in the course which are in a group.
687 $sql = "SELECT gm.id as gmid, gm.userid, g.*
688 FROM {groups_members} gm
689 INNER JOIN {groups} g
690 ON gm.groupid = g.id
691 WHERE g.courseid = :courseid";
692 $params = array();
693 $params['courseid'] = $courseid;
694 // Check if we want to delete a specific user.
695 if ($userid) {
696 $sql .= " AND gm.userid = :userid";
697 $params['userid'] = $userid;
699 $rs = $DB->get_recordset_sql($sql, $params);
700 foreach ($rs as $usergroup) {
701 groups_remove_member($usergroup, $usergroup->userid);
703 $rs->close();
705 return true;
709 * Remove all groups from all groupings in course
711 * @param int $courseid
712 * @param bool $showfeedback
713 * @return bool success
715 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
716 global $DB, $OUTPUT;
718 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
719 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
720 array($courseid), '', 'groupid, groupingid');
722 foreach ($results as $result) {
723 groups_unassign_grouping($result->groupingid, $result->groupid, false);
725 $results->close();
727 // Invalidate the grouping cache for the course
728 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
729 // Purge the group and grouping cache for users.
730 cache_helper::purge_by_definition('core', 'user_group_groupings');
732 // no need to show any feedback here - we delete usually first groupings and then groups
734 return true;
738 * Delete all groups from course
740 * @param int $courseid
741 * @param bool $showfeedback
742 * @return bool success
744 function groups_delete_groups($courseid, $showfeedback=false) {
745 global $CFG, $DB, $OUTPUT;
747 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
748 foreach ($groups as $group) {
749 groups_delete_group($group);
751 $groups->close();
753 // Invalidate the grouping cache for the course
754 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
755 // Purge the group and grouping cache for users.
756 cache_helper::purge_by_definition('core', 'user_group_groupings');
757 // Rebuild the coursehiddengroups cache for the course.
758 \core_group\visibility::update_hiddengroups_cache($courseid);
760 if ($showfeedback) {
761 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
764 return true;
768 * Delete all groupings from course
770 * @param int $courseid
771 * @param bool $showfeedback
772 * @return bool success
774 function groups_delete_groupings($courseid, $showfeedback=false) {
775 global $DB, $OUTPUT;
777 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
778 foreach ($groupings as $grouping) {
779 groups_delete_grouping($grouping);
781 $groupings->close();
783 // Invalidate the grouping cache for the course.
784 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
785 // Purge the group and grouping cache for users.
786 cache_helper::purge_by_definition('core', 'user_group_groupings');
788 if ($showfeedback) {
789 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
792 return true;
795 /* =================================== */
796 /* various functions used by groups UI */
797 /* =================================== */
800 * Obtains a list of the possible roles that group members might come from,
801 * on a course. Generally this includes only profile roles.
803 * @param context $context Context of course
804 * @return Array of role ID integers, or false if error/none.
806 function groups_get_possible_roles($context) {
807 $roles = get_profile_roles($context);
808 return array_keys($roles);
813 * Gets potential group members for grouping
815 * @param int $courseid The id of the course
816 * @param int $roleid The role to select users from
817 * @param mixed $source restrict to cohort, grouping or group id
818 * @param string $orderby The column to sort users by
819 * @param int $notingroup restrict to users not in existing groups
820 * @param bool $onlyactiveenrolments restrict to users who have an active enrolment in the course
821 * @param array $extrafields Extra user fields to return
822 * @return array An array of the users
824 function groups_get_potential_members($courseid, $roleid = null, $source = null,
825 $orderby = 'lastname ASC, firstname ASC',
826 $notingroup = null, $onlyactiveenrolments = false, $extrafields = []) {
827 global $DB;
829 $context = context_course::instance($courseid);
831 list($esql, $params) = get_enrolled_sql($context, '', 0, $onlyactiveenrolments);
833 $notingroupsql = "";
834 if ($notingroup) {
835 // We want to eliminate users that are already associated with a course group.
836 $notingroupsql = "u.id NOT IN (SELECT userid
837 FROM {groups_members}
838 WHERE groupid IN (SELECT id
839 FROM {groups}
840 WHERE courseid = :courseid))";
841 $params['courseid'] = $courseid;
844 if ($roleid) {
845 // We are looking for all users with this role assigned in this context or higher.
846 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
847 SQL_PARAMS_NAMED,
848 'relatedctx');
850 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
851 $where = "WHERE u.id IN (SELECT userid
852 FROM {role_assignments}
853 WHERE roleid = :roleid AND contextid $relatedctxsql)";
854 $where .= $notingroup ? "AND $notingroupsql" : "";
855 } else if ($notingroup) {
856 $where = "WHERE $notingroupsql";
857 } else {
858 $where = "";
861 $sourcejoin = "";
862 if (is_int($source)) {
863 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
864 $params['cohortid'] = $source;
865 } else {
866 // Auto-create groups from an existing cohort membership.
867 if (isset($source['cohortid'])) {
868 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
869 $params['cohortid'] = $source['cohortid'];
871 // Auto-create groups from an existing group membership.
872 if (isset($source['groupid'])) {
873 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
874 $params['groupid'] = $source['groupid'];
876 // Auto-create groups from an existing grouping membership.
877 if (isset($source['groupingid'])) {
878 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
879 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
880 $params['groupingid'] = $source['groupingid'];
884 $userfieldsapi = \core_user\fields::for_userpic()->including(...$extrafields);
885 $allusernamefields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
886 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
887 FROM {user} u
888 JOIN ($esql) e ON e.id = u.id
889 $sourcejoin
890 $where
891 ORDER BY $orderby";
893 return $DB->get_records_sql($sql, $params);
898 * Parse a group name for characters to replace
900 * @param string $format The format a group name will follow
901 * @param int $groupnumber The number of the group to be used in the parsed format string
902 * @return string the parsed format string
904 function groups_parse_name($format, $groupnumber) {
905 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
906 $letter = 'A';
907 for($i=0; $i<$groupnumber; $i++) {
908 $letter++;
910 $str = str_replace('@', $letter, $format);
911 } else {
912 $str = str_replace('#', $groupnumber+1, $format);
914 return($str);
918 * Assigns group into grouping
920 * @param int groupingid
921 * @param int groupid
922 * @param int $timeadded The time the group was added to the grouping.
923 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
924 * @return bool true or exception
926 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
927 global $DB;
929 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
930 return true;
932 $assign = new stdClass();
933 $assign->groupingid = $groupingid;
934 $assign->groupid = $groupid;
935 if ($timeadded != null) {
936 $assign->timeadded = (integer)$timeadded;
937 } else {
938 $assign->timeadded = time();
940 $DB->insert_record('groupings_groups', $assign);
942 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
943 if ($invalidatecache) {
944 // Invalidate the grouping cache for the course
945 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
946 // Purge the group and grouping cache for users.
947 cache_helper::purge_by_definition('core', 'user_group_groupings');
950 // Trigger event.
951 $params = array(
952 'context' => context_course::instance($courseid),
953 'objectid' => $groupingid,
954 'other' => array('groupid' => $groupid)
956 $event = \core\event\grouping_group_assigned::create($params);
957 $event->trigger();
959 return true;
963 * Unassigns group from grouping
965 * @param int groupingid
966 * @param int groupid
967 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
968 * @return bool success
970 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
971 global $DB;
972 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
974 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
975 if ($invalidatecache) {
976 // Invalidate the grouping cache for the course
977 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
978 // Purge the group and grouping cache for users.
979 cache_helper::purge_by_definition('core', 'user_group_groupings');
982 // Trigger event.
983 $params = array(
984 'context' => context_course::instance($courseid),
985 'objectid' => $groupingid,
986 'other' => array('groupid' => $groupid)
988 $event = \core\event\grouping_group_unassigned::create($params);
989 $event->trigger();
991 return true;
995 * Lists users in a group based on their role on the course.
996 * Returns false if there's an error or there are no users in the group.
997 * Otherwise returns an array of role ID => role data, where role data includes:
998 * (role) $id, $shortname, $name
999 * $users: array of objects for each user which include the specified fields
1000 * Users who do not have a role are stored in the returned array with key '-'
1001 * and pseudo-role details (including a name, 'No role'). Users with multiple
1002 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
1003 * which roles each has by looking in the $roles array of the user object.
1005 * @param int $groupid
1006 * @param int $courseid Course ID (should match the group's course)
1007 * @param string $fields List of fields from user table (prefixed with u) and joined tables, default 'u.*'
1008 * @param string|null $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
1009 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
1010 * @param array $whereorsortparams any parameters required by $extrawheretest or $joins (named parameters).
1011 * @param string $joins any joins required to get the specified fields.
1012 * @return array Complex array as described above
1014 function groups_get_members_by_role(int $groupid, int $courseid, string $fields = 'u.*',
1015 ?string $sort = null, string $extrawheretest = '', array $whereorsortparams = [], string $joins = '') {
1016 global $DB;
1018 // Retrieve information about all users and their roles on the course or
1019 // parent ('related') contexts
1020 $context = context_course::instance($courseid);
1022 // We are looking for all users with this role assigned in this context or higher.
1023 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
1025 if ($extrawheretest) {
1026 $extrawheretest = ' AND ' . $extrawheretest;
1029 if (is_null($sort)) {
1030 list($sort, $sortparams) = users_order_by_sql('u');
1031 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
1034 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
1035 FROM {groups_members} gm
1036 JOIN {user} u ON u.id = gm.userid
1037 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
1038 LEFT JOIN {role} r ON r.id = ra.roleid
1039 $joins
1040 WHERE gm.groupid=:mgroupid
1041 ".$extrawheretest."
1042 ORDER BY r.sortorder, $sort";
1043 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
1044 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
1046 return groups_calculate_role_people($rs, $context);
1050 * Internal function used by groups_get_members_by_role to handle the
1051 * results of a database query that includes a list of users and possible
1052 * roles on a course.
1054 * @param moodle_recordset $rs The record set (may be false)
1055 * @param int $context ID of course context
1056 * @return array As described in groups_get_members_by_role
1058 function groups_calculate_role_people($rs, $context) {
1059 global $CFG, $DB;
1061 if (!$rs) {
1062 return array();
1065 $allroles = role_fix_names(get_all_roles($context), $context);
1066 $visibleroles = get_viewable_roles($context);
1068 // Array of all involved roles
1069 $roles = array();
1070 // Array of all retrieved users
1071 $users = array();
1072 // Fill arrays
1073 foreach ($rs as $rec) {
1074 // Create information about user if this is a new one
1075 if (!array_key_exists($rec->userid, $users)) {
1076 // User data includes all the optional fields, but not any of the
1077 // stuff we added to get the role details
1078 $userdata = clone($rec);
1079 unset($userdata->roleid);
1080 unset($userdata->roleshortname);
1081 unset($userdata->rolename);
1082 unset($userdata->userid);
1083 $userdata->id = $rec->userid;
1085 // Make an array to hold the list of roles for this user
1086 $userdata->roles = array();
1087 $users[$rec->userid] = $userdata;
1089 // If user has a role...
1090 if (!is_null($rec->roleid)) {
1091 // Create information about role if this is a new one
1092 if (!array_key_exists($rec->roleid, $roles)) {
1093 $role = $allroles[$rec->roleid];
1094 $roledata = new stdClass();
1095 $roledata->id = $role->id;
1096 $roledata->shortname = $role->shortname;
1097 $roledata->name = $role->localname;
1098 $roledata->users = array();
1099 $roles[$roledata->id] = $roledata;
1101 // Record that user has role
1102 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
1105 $rs->close();
1107 // Return false if there weren't any users
1108 if (count($users) == 0) {
1109 return false;
1112 // Add pseudo-role for multiple roles
1113 $roledata = new stdClass();
1114 $roledata->name = get_string('multipleroles','role');
1115 $roledata->users = array();
1116 $roles['*'] = $roledata;
1118 $roledata = new stdClass();
1119 $roledata->name = get_string('noroles','role');
1120 $roledata->users = array();
1121 $roles[0] = $roledata;
1123 // Now we rearrange the data to store users by role
1124 foreach ($users as $userid=>$userdata) {
1125 $visibleuserroles = array_intersect_key($userdata->roles, $visibleroles);
1126 $rolecount = count($visibleuserroles);
1127 if ($rolecount == 0) {
1128 // does not have any roles
1129 $roleid = 0;
1130 } else if($rolecount > 1) {
1131 $roleid = '*';
1132 } else {
1133 $userrole = reset($visibleuserroles);
1134 $roleid = $userrole->id;
1136 $roles[$roleid]->users[$userid] = $userdata;
1139 // Delete roles not used
1140 foreach ($roles as $key=>$roledata) {
1141 if (count($roledata->users)===0) {
1142 unset($roles[$key]);
1146 // Return list of roles containing their users
1147 return $roles;
1151 * Synchronises enrolments with the group membership
1153 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1154 * and group membership, such as enrol_cohort and enrol_meta .
1156 * @param string $enrolname name of enrolment method without prefix
1157 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1158 * @param string $gidfield name of the field in 'enrol' table that stores group id
1159 * @return array Returns the list of removed and added users. Each record contains fields:
1160 * userid, enrolid, courseid, groupid, groupname
1162 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1163 global $DB;
1164 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1165 $params = array(
1166 'enrolname' => $enrolname,
1167 'component' => 'enrol_'.$enrolname,
1168 'courseid' => $courseid
1171 $affectedusers = array(
1172 'removed' => array(),
1173 'added' => array()
1176 // Remove invalid.
1177 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1178 FROM {groups_members} gm
1179 JOIN {groups} g ON (g.id = gm.groupid)
1180 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1181 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1182 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1184 $rs = $DB->get_recordset_sql($sql, $params);
1185 foreach ($rs as $gm) {
1186 groups_remove_member($gm->groupid, $gm->userid);
1187 $affectedusers['removed'][] = $gm;
1189 $rs->close();
1191 // Add missing.
1192 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1193 FROM {user_enrolments} ue
1194 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1195 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1196 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1197 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1198 WHERE gm.id IS NULL";
1200 $rs = $DB->get_recordset_sql($sql, $params);
1201 foreach ($rs as $ue) {
1202 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1203 $affectedusers['added'][] = $ue;
1205 $rs->close();
1207 return $affectedusers;
1211 * Callback for inplace editable API.
1213 * @param string $itemtype - Only user_groups is supported.
1214 * @param string $itemid - Userid and groupid separated by a :
1215 * @param string $newvalue - json encoded list of groupids.
1216 * @return \core\output\inplace_editable
1218 function core_group_inplace_editable($itemtype, $itemid, $newvalue) {
1219 if ($itemtype === 'user_groups') {
1220 return \core_group\output\user_groups_editable::update($itemid, $newvalue);
1225 * Updates group messaging to enable/disable in bulk.
1227 * @param array $groupids array of group id numbers.
1228 * @param bool $enabled if true, enables messaging else disables messaging
1230 function set_groups_messaging(array $groupids, bool $enabled): void {
1231 foreach ($groupids as $groupid) {
1232 $data = groups_get_group($groupid, '*', MUST_EXIST);
1233 $data->enablemessaging = $enabled;
1234 groups_update_group($data);
1239 * Returns custom fields data for provided groups.
1241 * @param array $groupids a list of group IDs to provide data for.
1242 * @return \core_customfield\data_controller[]
1244 function get_group_custom_fields_data(array $groupids): array {
1245 $result = [];
1247 if (!empty($groupids)) {
1248 $handler = \core_group\customfield\group_handler::create();
1249 $customfieldsdata = $handler->get_instances_data($groupids, true);
1251 foreach ($customfieldsdata as $groupid => $fieldcontrollers) {
1252 foreach ($fieldcontrollers as $fieldcontroller) {
1253 $result[$groupid][] = [
1254 'type' => $fieldcontroller->get_field()->get('type'),
1255 'value' => $fieldcontroller->export_value(),
1256 'valueraw' => $fieldcontroller->get_value(),
1257 'name' => $fieldcontroller->get_field()->get('name'),
1258 'shortname' => $fieldcontroller->get_field()->get('shortname'),
1264 return $result;
1268 * Returns custom fields data for provided groupings.
1270 * @param array $groupingids a list of group IDs to provide data for.
1271 * @return \core_customfield\data_controller[]
1273 function get_grouping_custom_fields_data(array $groupingids): array {
1274 $result = [];
1276 if (!empty($groupingids)) {
1277 $handler = \core_group\customfield\grouping_handler::create();
1278 $customfieldsdata = $handler->get_instances_data($groupingids, true);
1280 foreach ($customfieldsdata as $groupingid => $fieldcontrollers) {
1281 foreach ($fieldcontrollers as $fieldcontroller) {
1282 $result[$groupingid][] = [
1283 'type' => $fieldcontroller->get_field()->get('type'),
1284 'value' => $fieldcontroller->export_value(),
1285 'valueraw' => $fieldcontroller->get_value(),
1286 'name' => $fieldcontroller->get_field()->get('name'),
1287 'shortname' => $fieldcontroller->get_field()->get('shortname'),
1293 return $result;