Merge branch 'MDL-69086-master' of git://github.com/andrewnicols/moodle
[moodle.git] / group / lib.php
blob98330166fe5eb78e07533109f55ccb09da89e071
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 $allusernamefields = user_picture::fields('u', $extrafields);
852 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
853 FROM {user} u
854 JOIN ($esql) e ON e.id = u.id
855 $sourcejoin
856 $where
857 ORDER BY $orderby";
859 return $DB->get_records_sql($sql, $params);
864 * Parse a group name for characters to replace
866 * @param string $format The format a group name will follow
867 * @param int $groupnumber The number of the group to be used in the parsed format string
868 * @return string the parsed format string
870 function groups_parse_name($format, $groupnumber) {
871 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
872 $letter = 'A';
873 for($i=0; $i<$groupnumber; $i++) {
874 $letter++;
876 $str = str_replace('@', $letter, $format);
877 } else {
878 $str = str_replace('#', $groupnumber+1, $format);
880 return($str);
884 * Assigns group into grouping
886 * @param int groupingid
887 * @param int groupid
888 * @param int $timeadded The time the group was added to the grouping.
889 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
890 * @return bool true or exception
892 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
893 global $DB;
895 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
896 return true;
898 $assign = new stdClass();
899 $assign->groupingid = $groupingid;
900 $assign->groupid = $groupid;
901 if ($timeadded != null) {
902 $assign->timeadded = (integer)$timeadded;
903 } else {
904 $assign->timeadded = time();
906 $DB->insert_record('groupings_groups', $assign);
908 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
909 if ($invalidatecache) {
910 // Invalidate the grouping cache for the course
911 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
912 // Purge the group and grouping cache for users.
913 cache_helper::purge_by_definition('core', 'user_group_groupings');
916 // Trigger event.
917 $params = array(
918 'context' => context_course::instance($courseid),
919 'objectid' => $groupingid,
920 'other' => array('groupid' => $groupid)
922 $event = \core\event\grouping_group_assigned::create($params);
923 $event->trigger();
925 return true;
929 * Unassigns group from grouping
931 * @param int groupingid
932 * @param int groupid
933 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
934 * @return bool success
936 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
937 global $DB;
938 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
940 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
941 if ($invalidatecache) {
942 // Invalidate the grouping cache for the course
943 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
944 // Purge the group and grouping cache for users.
945 cache_helper::purge_by_definition('core', 'user_group_groupings');
948 // Trigger event.
949 $params = array(
950 'context' => context_course::instance($courseid),
951 'objectid' => $groupingid,
952 'other' => array('groupid' => $groupid)
954 $event = \core\event\grouping_group_unassigned::create($params);
955 $event->trigger();
957 return true;
961 * Lists users in a group based on their role on the course.
962 * Returns false if there's an error or there are no users in the group.
963 * Otherwise returns an array of role ID => role data, where role data includes:
964 * (role) $id, $shortname, $name
965 * $users: array of objects for each user which include the specified fields
966 * Users who do not have a role are stored in the returned array with key '-'
967 * and pseudo-role details (including a name, 'No role'). Users with multiple
968 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
969 * which roles each has by looking in the $roles array of the user object.
971 * @param int $groupid
972 * @param int $courseid Course ID (should match the group's course)
973 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
974 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
975 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
976 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
977 * @return array Complex array as described above
979 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
980 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
981 global $DB;
983 // Retrieve information about all users and their roles on the course or
984 // parent ('related') contexts
985 $context = context_course::instance($courseid);
987 // We are looking for all users with this role assigned in this context or higher.
988 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
990 if ($extrawheretest) {
991 $extrawheretest = ' AND ' . $extrawheretest;
994 if (is_null($sort)) {
995 list($sort, $sortparams) = users_order_by_sql('u');
996 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
999 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
1000 FROM {groups_members} gm
1001 JOIN {user} u ON u.id = gm.userid
1002 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
1003 LEFT JOIN {role} r ON r.id = ra.roleid
1004 WHERE gm.groupid=:mgroupid
1005 ".$extrawheretest."
1006 ORDER BY r.sortorder, $sort";
1007 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
1008 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
1010 return groups_calculate_role_people($rs, $context);
1014 * Internal function used by groups_get_members_by_role to handle the
1015 * results of a database query that includes a list of users and possible
1016 * roles on a course.
1018 * @param moodle_recordset $rs The record set (may be false)
1019 * @param int $context ID of course context
1020 * @return array As described in groups_get_members_by_role
1022 function groups_calculate_role_people($rs, $context) {
1023 global $CFG, $DB;
1025 if (!$rs) {
1026 return array();
1029 $allroles = role_fix_names(get_all_roles($context), $context);
1030 $visibleroles = get_viewable_roles($context);
1032 // Array of all involved roles
1033 $roles = array();
1034 // Array of all retrieved users
1035 $users = array();
1036 // Fill arrays
1037 foreach ($rs as $rec) {
1038 // Create information about user if this is a new one
1039 if (!array_key_exists($rec->userid, $users)) {
1040 // User data includes all the optional fields, but not any of the
1041 // stuff we added to get the role details
1042 $userdata = clone($rec);
1043 unset($userdata->roleid);
1044 unset($userdata->roleshortname);
1045 unset($userdata->rolename);
1046 unset($userdata->userid);
1047 $userdata->id = $rec->userid;
1049 // Make an array to hold the list of roles for this user
1050 $userdata->roles = array();
1051 $users[$rec->userid] = $userdata;
1053 // If user has a role...
1054 if (!is_null($rec->roleid)) {
1055 // Create information about role if this is a new one
1056 if (!array_key_exists($rec->roleid, $roles)) {
1057 $role = $allroles[$rec->roleid];
1058 $roledata = new stdClass();
1059 $roledata->id = $role->id;
1060 $roledata->shortname = $role->shortname;
1061 $roledata->name = $role->localname;
1062 $roledata->users = array();
1063 $roles[$roledata->id] = $roledata;
1065 // Record that user has role
1066 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
1069 $rs->close();
1071 // Return false if there weren't any users
1072 if (count($users) == 0) {
1073 return false;
1076 // Add pseudo-role for multiple roles
1077 $roledata = new stdClass();
1078 $roledata->name = get_string('multipleroles','role');
1079 $roledata->users = array();
1080 $roles['*'] = $roledata;
1082 $roledata = new stdClass();
1083 $roledata->name = get_string('noroles','role');
1084 $roledata->users = array();
1085 $roles[0] = $roledata;
1087 // Now we rearrange the data to store users by role
1088 foreach ($users as $userid=>$userdata) {
1089 $visibleuserroles = array_intersect_key($userdata->roles, $visibleroles);
1090 $rolecount = count($visibleuserroles);
1091 if ($rolecount == 0) {
1092 // does not have any roles
1093 $roleid = 0;
1094 } else if($rolecount > 1) {
1095 $roleid = '*';
1096 } else {
1097 $userrole = reset($visibleuserroles);
1098 $roleid = $userrole->id;
1100 $roles[$roleid]->users[$userid] = $userdata;
1103 // Delete roles not used
1104 foreach ($roles as $key=>$roledata) {
1105 if (count($roledata->users)===0) {
1106 unset($roles[$key]);
1110 // Return list of roles containing their users
1111 return $roles;
1115 * Synchronises enrolments with the group membership
1117 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1118 * and group membership, such as enrol_cohort and enrol_meta .
1120 * @param string $enrolname name of enrolment method without prefix
1121 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1122 * @param string $gidfield name of the field in 'enrol' table that stores group id
1123 * @return array Returns the list of removed and added users. Each record contains fields:
1124 * userid, enrolid, courseid, groupid, groupname
1126 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1127 global $DB;
1128 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1129 $params = array(
1130 'enrolname' => $enrolname,
1131 'component' => 'enrol_'.$enrolname,
1132 'courseid' => $courseid
1135 $affectedusers = array(
1136 'removed' => array(),
1137 'added' => array()
1140 // Remove invalid.
1141 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1142 FROM {groups_members} gm
1143 JOIN {groups} g ON (g.id = gm.groupid)
1144 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1145 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1146 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1148 $rs = $DB->get_recordset_sql($sql, $params);
1149 foreach ($rs as $gm) {
1150 groups_remove_member($gm->groupid, $gm->userid);
1151 $affectedusers['removed'][] = $gm;
1153 $rs->close();
1155 // Add missing.
1156 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1157 FROM {user_enrolments} ue
1158 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1159 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1160 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1161 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1162 WHERE gm.id IS NULL";
1164 $rs = $DB->get_recordset_sql($sql, $params);
1165 foreach ($rs as $ue) {
1166 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1167 $affectedusers['added'][] = $ue;
1169 $rs->close();
1171 return $affectedusers;
1175 * Callback for inplace editable API.
1177 * @param string $itemtype - Only user_groups is supported.
1178 * @param string $itemid - Userid and groupid separated by a :
1179 * @param string $newvalue - json encoded list of groupids.
1180 * @return \core\output\inplace_editable
1182 function core_group_inplace_editable($itemtype, $itemid, $newvalue) {
1183 if ($itemtype === 'user_groups') {
1184 return \core_group\output\user_groups_editable::update($itemid, $newvalue);