Merge branch 'MDL-69116-38' of git://github.com/rezaies/moodle into MOODLE_38_STABLE
[moodle.git] / group / lib.php
blob42e7fbec1cc1e0588a80a69e4a9ae2b12204c49d
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 * @return array An array of the users
790 function groups_get_potential_members($courseid, $roleid = null, $source = null,
791 $orderby = 'lastname ASC, firstname ASC',
792 $notingroup = null, $onlyactiveenrolments = false) {
793 global $DB;
795 $context = context_course::instance($courseid);
797 list($esql, $params) = get_enrolled_sql($context, '', 0, $onlyactiveenrolments);
799 $notingroupsql = "";
800 if ($notingroup) {
801 // We want to eliminate users that are already associated with a course group.
802 $notingroupsql = "u.id NOT IN (SELECT userid
803 FROM {groups_members}
804 WHERE groupid IN (SELECT id
805 FROM {groups}
806 WHERE courseid = :courseid))";
807 $params['courseid'] = $courseid;
810 if ($roleid) {
811 // We are looking for all users with this role assigned in this context or higher.
812 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
813 SQL_PARAMS_NAMED,
814 'relatedctx');
816 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
817 $where = "WHERE u.id IN (SELECT userid
818 FROM {role_assignments}
819 WHERE roleid = :roleid AND contextid $relatedctxsql)";
820 $where .= $notingroup ? "AND $notingroupsql" : "";
821 } else if ($notingroup) {
822 $where = "WHERE $notingroupsql";
823 } else {
824 $where = "";
827 $sourcejoin = "";
828 if (is_int($source)) {
829 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
830 $params['cohortid'] = $source;
831 } else {
832 // Auto-create groups from an existing cohort membership.
833 if (isset($source['cohortid'])) {
834 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
835 $params['cohortid'] = $source['cohortid'];
837 // Auto-create groups from an existing group membership.
838 if (isset($source['groupid'])) {
839 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
840 $params['groupid'] = $source['groupid'];
842 // Auto-create groups from an existing grouping membership.
843 if (isset($source['groupingid'])) {
844 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
845 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
846 $params['groupingid'] = $source['groupingid'];
850 $allusernamefields = get_all_user_name_fields(true, 'u');
851 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
852 FROM {user} u
853 JOIN ($esql) e ON e.id = u.id
854 $sourcejoin
855 $where
856 ORDER BY $orderby";
858 return $DB->get_records_sql($sql, $params);
863 * Parse a group name for characters to replace
865 * @param string $format The format a group name will follow
866 * @param int $groupnumber The number of the group to be used in the parsed format string
867 * @return string the parsed format string
869 function groups_parse_name($format, $groupnumber) {
870 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
871 $letter = 'A';
872 for($i=0; $i<$groupnumber; $i++) {
873 $letter++;
875 $str = str_replace('@', $letter, $format);
876 } else {
877 $str = str_replace('#', $groupnumber+1, $format);
879 return($str);
883 * Assigns group into grouping
885 * @param int groupingid
886 * @param int groupid
887 * @param int $timeadded The time the group was added to the grouping.
888 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
889 * @return bool true or exception
891 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
892 global $DB;
894 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
895 return true;
897 $assign = new stdClass();
898 $assign->groupingid = $groupingid;
899 $assign->groupid = $groupid;
900 if ($timeadded != null) {
901 $assign->timeadded = (integer)$timeadded;
902 } else {
903 $assign->timeadded = time();
905 $DB->insert_record('groupings_groups', $assign);
907 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
908 if ($invalidatecache) {
909 // Invalidate the grouping cache for the course
910 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
911 // Purge the group and grouping cache for users.
912 cache_helper::purge_by_definition('core', 'user_group_groupings');
915 // Trigger event.
916 $params = array(
917 'context' => context_course::instance($courseid),
918 'objectid' => $groupingid,
919 'other' => array('groupid' => $groupid)
921 $event = \core\event\grouping_group_assigned::create($params);
922 $event->trigger();
924 return true;
928 * Unassigns group from grouping
930 * @param int groupingid
931 * @param int groupid
932 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
933 * @return bool success
935 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
936 global $DB;
937 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
939 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
940 if ($invalidatecache) {
941 // Invalidate the grouping cache for the course
942 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
943 // Purge the group and grouping cache for users.
944 cache_helper::purge_by_definition('core', 'user_group_groupings');
947 // Trigger event.
948 $params = array(
949 'context' => context_course::instance($courseid),
950 'objectid' => $groupingid,
951 'other' => array('groupid' => $groupid)
953 $event = \core\event\grouping_group_unassigned::create($params);
954 $event->trigger();
956 return true;
960 * Lists users in a group based on their role on the course.
961 * Returns false if there's an error or there are no users in the group.
962 * Otherwise returns an array of role ID => role data, where role data includes:
963 * (role) $id, $shortname, $name
964 * $users: array of objects for each user which include the specified fields
965 * Users who do not have a role are stored in the returned array with key '-'
966 * and pseudo-role details (including a name, 'No role'). Users with multiple
967 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
968 * which roles each has by looking in the $roles array of the user object.
970 * @param int $groupid
971 * @param int $courseid Course ID (should match the group's course)
972 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
973 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
974 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
975 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
976 * @return array Complex array as described above
978 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
979 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
980 global $DB;
982 // Retrieve information about all users and their roles on the course or
983 // parent ('related') contexts
984 $context = context_course::instance($courseid);
986 // We are looking for all users with this role assigned in this context or higher.
987 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
989 if ($extrawheretest) {
990 $extrawheretest = ' AND ' . $extrawheretest;
993 if (is_null($sort)) {
994 list($sort, $sortparams) = users_order_by_sql('u');
995 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
998 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
999 FROM {groups_members} gm
1000 JOIN {user} u ON u.id = gm.userid
1001 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
1002 LEFT JOIN {role} r ON r.id = ra.roleid
1003 WHERE gm.groupid=:mgroupid
1004 ".$extrawheretest."
1005 ORDER BY r.sortorder, $sort";
1006 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
1007 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
1009 return groups_calculate_role_people($rs, $context);
1013 * Internal function used by groups_get_members_by_role to handle the
1014 * results of a database query that includes a list of users and possible
1015 * roles on a course.
1017 * @param moodle_recordset $rs The record set (may be false)
1018 * @param int $context ID of course context
1019 * @return array As described in groups_get_members_by_role
1021 function groups_calculate_role_people($rs, $context) {
1022 global $CFG, $DB;
1024 if (!$rs) {
1025 return array();
1028 $allroles = role_fix_names(get_all_roles($context), $context);
1029 $visibleroles = get_viewable_roles($context);
1031 // Array of all involved roles
1032 $roles = array();
1033 // Array of all retrieved users
1034 $users = array();
1035 // Fill arrays
1036 foreach ($rs as $rec) {
1037 // Create information about user if this is a new one
1038 if (!array_key_exists($rec->userid, $users)) {
1039 // User data includes all the optional fields, but not any of the
1040 // stuff we added to get the role details
1041 $userdata = clone($rec);
1042 unset($userdata->roleid);
1043 unset($userdata->roleshortname);
1044 unset($userdata->rolename);
1045 unset($userdata->userid);
1046 $userdata->id = $rec->userid;
1048 // Make an array to hold the list of roles for this user
1049 $userdata->roles = array();
1050 $users[$rec->userid] = $userdata;
1052 // If user has a role...
1053 if (!is_null($rec->roleid)) {
1054 // Create information about role if this is a new one
1055 if (!array_key_exists($rec->roleid, $roles)) {
1056 $role = $allroles[$rec->roleid];
1057 $roledata = new stdClass();
1058 $roledata->id = $role->id;
1059 $roledata->shortname = $role->shortname;
1060 $roledata->name = $role->localname;
1061 $roledata->users = array();
1062 $roles[$roledata->id] = $roledata;
1064 // Record that user has role
1065 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
1068 $rs->close();
1070 // Return false if there weren't any users
1071 if (count($users) == 0) {
1072 return false;
1075 // Add pseudo-role for multiple roles
1076 $roledata = new stdClass();
1077 $roledata->name = get_string('multipleroles','role');
1078 $roledata->users = array();
1079 $roles['*'] = $roledata;
1081 $roledata = new stdClass();
1082 $roledata->name = get_string('noroles','role');
1083 $roledata->users = array();
1084 $roles[0] = $roledata;
1086 // Now we rearrange the data to store users by role
1087 foreach ($users as $userid=>$userdata) {
1088 $visibleuserroles = array_intersect_key($userdata->roles, $visibleroles);
1089 $rolecount = count($visibleuserroles);
1090 if ($rolecount == 0) {
1091 // does not have any roles
1092 $roleid = 0;
1093 } else if($rolecount > 1) {
1094 $roleid = '*';
1095 } else {
1096 $userrole = reset($visibleuserroles);
1097 $roleid = $userrole->id;
1099 $roles[$roleid]->users[$userid] = $userdata;
1102 // Delete roles not used
1103 foreach ($roles as $key=>$roledata) {
1104 if (count($roledata->users)===0) {
1105 unset($roles[$key]);
1109 // Return list of roles containing their users
1110 return $roles;
1114 * Synchronises enrolments with the group membership
1116 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1117 * and group membership, such as enrol_cohort and enrol_meta .
1119 * @param string $enrolname name of enrolment method without prefix
1120 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1121 * @param string $gidfield name of the field in 'enrol' table that stores group id
1122 * @return array Returns the list of removed and added users. Each record contains fields:
1123 * userid, enrolid, courseid, groupid, groupname
1125 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1126 global $DB;
1127 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1128 $params = array(
1129 'enrolname' => $enrolname,
1130 'component' => 'enrol_'.$enrolname,
1131 'courseid' => $courseid
1134 $affectedusers = array(
1135 'removed' => array(),
1136 'added' => array()
1139 // Remove invalid.
1140 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1141 FROM {groups_members} gm
1142 JOIN {groups} g ON (g.id = gm.groupid)
1143 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1144 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1145 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1147 $rs = $DB->get_recordset_sql($sql, $params);
1148 foreach ($rs as $gm) {
1149 groups_remove_member($gm->groupid, $gm->userid);
1150 $affectedusers['removed'][] = $gm;
1152 $rs->close();
1154 // Add missing.
1155 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1156 FROM {user_enrolments} ue
1157 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1158 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1159 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1160 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1161 WHERE gm.id IS NULL";
1163 $rs = $DB->get_recordset_sql($sql, $params);
1164 foreach ($rs as $ue) {
1165 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1166 $affectedusers['added'][] = $ue;
1168 $rs->close();
1170 return $affectedusers;
1174 * Callback for inplace editable API.
1176 * @param string $itemtype - Only user_groups is supported.
1177 * @param string $itemid - Userid and groupid separated by a :
1178 * @param string $newvalue - json encoded list of groupids.
1179 * @return \core\output\inplace_editable
1181 function core_group_inplace_editable($itemtype, $itemid, $newvalue) {
1182 if ($itemtype === 'user_groups') {
1183 return \core_group\output\user_groups_editable::update($itemid, $newvalue);