MDL-63303 message: fix bugs in message drawer part 4
[moodle.git] / group / lib.php
blobc2edce9890d3c3871870035ca35b720112f36860
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 // delete group calendar events
552 $DB->delete_records('event', array('groupid'=>$groupid));
553 //first delete usage in groupings_groups
554 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
555 //delete members
556 $DB->delete_records('groups_members', array('groupid'=>$groupid));
557 //group itself last
558 $DB->delete_records('groups', array('id'=>$groupid));
560 // Delete all files associated with this group
561 $context = context_course::instance($group->courseid);
562 $fs = get_file_storage();
563 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
564 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
566 // Invalidate the grouping cache for the course
567 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
568 // Purge the group and grouping cache for users.
569 cache_helper::purge_by_definition('core', 'user_group_groupings');
571 // Trigger group event.
572 $params = array(
573 'context' => $context,
574 'objectid' => $groupid
576 $event = \core\event\group_deleted::create($params);
577 $event->add_record_snapshot('groups', $group);
578 $event->trigger();
580 return true;
584 * Delete grouping
586 * @param int $groupingorid
587 * @return bool success
589 function groups_delete_grouping($groupingorid) {
590 global $DB;
592 if (is_object($groupingorid)) {
593 $groupingid = $groupingorid->id;
594 $grouping = $groupingorid;
595 } else {
596 $groupingid = $groupingorid;
597 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
598 //silently ignore attempts to delete missing already deleted groupings ;-)
599 return true;
603 //first delete usage in groupings_groups
604 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
605 // remove the default groupingid from course
606 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
607 // remove the groupingid from all course modules
608 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
609 //group itself last
610 $DB->delete_records('groupings', array('id'=>$groupingid));
612 $context = context_course::instance($grouping->courseid);
613 $fs = get_file_storage();
614 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
615 foreach ($files as $file) {
616 $file->delete();
619 // Invalidate the grouping cache for the course
620 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
621 // Purge the group and grouping cache for users.
622 cache_helper::purge_by_definition('core', 'user_group_groupings');
624 // Trigger group event.
625 $params = array(
626 'context' => $context,
627 'objectid' => $groupingid
629 $event = \core\event\grouping_deleted::create($params);
630 $event->add_record_snapshot('groupings', $grouping);
631 $event->trigger();
633 return true;
637 * Remove all users (or one user) from all groups in course
639 * @param int $courseid
640 * @param int $userid 0 means all users
641 * @param bool $unused - formerly $showfeedback, is no longer used.
642 * @return bool success
644 function groups_delete_group_members($courseid, $userid=0, $unused=false) {
645 global $DB, $OUTPUT;
647 // Get the users in the course which are in a group.
648 $sql = "SELECT gm.id as gmid, gm.userid, g.*
649 FROM {groups_members} gm
650 INNER JOIN {groups} g
651 ON gm.groupid = g.id
652 WHERE g.courseid = :courseid";
653 $params = array();
654 $params['courseid'] = $courseid;
655 // Check if we want to delete a specific user.
656 if ($userid) {
657 $sql .= " AND gm.userid = :userid";
658 $params['userid'] = $userid;
660 $rs = $DB->get_recordset_sql($sql, $params);
661 foreach ($rs as $usergroup) {
662 groups_remove_member($usergroup, $usergroup->userid);
664 $rs->close();
666 return true;
670 * Remove all groups from all groupings in course
672 * @param int $courseid
673 * @param bool $showfeedback
674 * @return bool success
676 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
677 global $DB, $OUTPUT;
679 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
680 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
681 array($courseid), '', 'groupid, groupingid');
683 foreach ($results as $result) {
684 groups_unassign_grouping($result->groupingid, $result->groupid, false);
686 $results->close();
688 // Invalidate the grouping cache for the course
689 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
690 // Purge the group and grouping cache for users.
691 cache_helper::purge_by_definition('core', 'user_group_groupings');
693 // no need to show any feedback here - we delete usually first groupings and then groups
695 return true;
699 * Delete all groups from course
701 * @param int $courseid
702 * @param bool $showfeedback
703 * @return bool success
705 function groups_delete_groups($courseid, $showfeedback=false) {
706 global $CFG, $DB, $OUTPUT;
708 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
709 foreach ($groups as $group) {
710 groups_delete_group($group);
712 $groups->close();
714 // Invalidate the grouping cache for the course
715 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
716 // Purge the group and grouping cache for users.
717 cache_helper::purge_by_definition('core', 'user_group_groupings');
719 if ($showfeedback) {
720 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
723 return true;
727 * Delete all groupings from course
729 * @param int $courseid
730 * @param bool $showfeedback
731 * @return bool success
733 function groups_delete_groupings($courseid, $showfeedback=false) {
734 global $DB, $OUTPUT;
736 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
737 foreach ($groupings as $grouping) {
738 groups_delete_grouping($grouping);
740 $groupings->close();
742 // Invalidate the grouping cache for the course.
743 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
744 // Purge the group and grouping cache for users.
745 cache_helper::purge_by_definition('core', 'user_group_groupings');
747 if ($showfeedback) {
748 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
751 return true;
754 /* =================================== */
755 /* various functions used by groups UI */
756 /* =================================== */
759 * Obtains a list of the possible roles that group members might come from,
760 * on a course. Generally this includes only profile roles.
762 * @param context $context Context of course
763 * @return Array of role ID integers, or false if error/none.
765 function groups_get_possible_roles($context) {
766 $roles = get_profile_roles($context);
767 return array_keys($roles);
772 * Gets potential group members for grouping
774 * @param int $courseid The id of the course
775 * @param int $roleid The role to select users from
776 * @param mixed $source restrict to cohort, grouping or group id
777 * @param string $orderby The column to sort users by
778 * @param int $notingroup restrict to users not in existing groups
779 * @param bool $onlyactiveenrolments restrict to users who have an active enrolment in the course
780 * @return array An array of the users
782 function groups_get_potential_members($courseid, $roleid = null, $source = null,
783 $orderby = 'lastname ASC, firstname ASC',
784 $notingroup = null, $onlyactiveenrolments = false) {
785 global $DB;
787 $context = context_course::instance($courseid);
789 list($esql, $params) = get_enrolled_sql($context, '', 0, $onlyactiveenrolments);
791 $notingroupsql = "";
792 if ($notingroup) {
793 // We want to eliminate users that are already associated with a course group.
794 $notingroupsql = "u.id NOT IN (SELECT userid
795 FROM {groups_members}
796 WHERE groupid IN (SELECT id
797 FROM {groups}
798 WHERE courseid = :courseid))";
799 $params['courseid'] = $courseid;
802 if ($roleid) {
803 // We are looking for all users with this role assigned in this context or higher.
804 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
805 SQL_PARAMS_NAMED,
806 'relatedctx');
808 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
809 $where = "WHERE u.id IN (SELECT userid
810 FROM {role_assignments}
811 WHERE roleid = :roleid AND contextid $relatedctxsql)";
812 $where .= $notingroup ? "AND $notingroupsql" : "";
813 } else if ($notingroup) {
814 $where = "WHERE $notingroupsql";
815 } else {
816 $where = "";
819 $sourcejoin = "";
820 if (is_int($source)) {
821 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
822 $params['cohortid'] = $source;
823 } else {
824 // Auto-create groups from an existing cohort membership.
825 if (isset($source['cohortid'])) {
826 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
827 $params['cohortid'] = $source['cohortid'];
829 // Auto-create groups from an existing group membership.
830 if (isset($source['groupid'])) {
831 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
832 $params['groupid'] = $source['groupid'];
834 // Auto-create groups from an existing grouping membership.
835 if (isset($source['groupingid'])) {
836 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
837 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
838 $params['groupingid'] = $source['groupingid'];
842 $allusernamefields = get_all_user_name_fields(true, 'u');
843 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
844 FROM {user} u
845 JOIN ($esql) e ON e.id = u.id
846 $sourcejoin
847 $where
848 ORDER BY $orderby";
850 return $DB->get_records_sql($sql, $params);
855 * Parse a group name for characters to replace
857 * @param string $format The format a group name will follow
858 * @param int $groupnumber The number of the group to be used in the parsed format string
859 * @return string the parsed format string
861 function groups_parse_name($format, $groupnumber) {
862 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
863 $letter = 'A';
864 for($i=0; $i<$groupnumber; $i++) {
865 $letter++;
867 $str = str_replace('@', $letter, $format);
868 } else {
869 $str = str_replace('#', $groupnumber+1, $format);
871 return($str);
875 * Assigns group into grouping
877 * @param int groupingid
878 * @param int groupid
879 * @param int $timeadded The time the group was added to the grouping.
880 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
881 * @return bool true or exception
883 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
884 global $DB;
886 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
887 return true;
889 $assign = new stdClass();
890 $assign->groupingid = $groupingid;
891 $assign->groupid = $groupid;
892 if ($timeadded != null) {
893 $assign->timeadded = (integer)$timeadded;
894 } else {
895 $assign->timeadded = time();
897 $DB->insert_record('groupings_groups', $assign);
899 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
900 if ($invalidatecache) {
901 // Invalidate the grouping cache for the course
902 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
903 // Purge the group and grouping cache for users.
904 cache_helper::purge_by_definition('core', 'user_group_groupings');
907 // Trigger event.
908 $params = array(
909 'context' => context_course::instance($courseid),
910 'objectid' => $groupingid,
911 'other' => array('groupid' => $groupid)
913 $event = \core\event\grouping_group_assigned::create($params);
914 $event->trigger();
916 return true;
920 * Unassigns group from grouping
922 * @param int groupingid
923 * @param int groupid
924 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
925 * @return bool success
927 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
928 global $DB;
929 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
931 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
932 if ($invalidatecache) {
933 // Invalidate the grouping cache for the course
934 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
935 // Purge the group and grouping cache for users.
936 cache_helper::purge_by_definition('core', 'user_group_groupings');
939 // Trigger event.
940 $params = array(
941 'context' => context_course::instance($courseid),
942 'objectid' => $groupingid,
943 'other' => array('groupid' => $groupid)
945 $event = \core\event\grouping_group_unassigned::create($params);
946 $event->trigger();
948 return true;
952 * Lists users in a group based on their role on the course.
953 * Returns false if there's an error or there are no users in the group.
954 * Otherwise returns an array of role ID => role data, where role data includes:
955 * (role) $id, $shortname, $name
956 * $users: array of objects for each user which include the specified fields
957 * Users who do not have a role are stored in the returned array with key '-'
958 * and pseudo-role details (including a name, 'No role'). Users with multiple
959 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
960 * which roles each has by looking in the $roles array of the user object.
962 * @param int $groupid
963 * @param int $courseid Course ID (should match the group's course)
964 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
965 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
966 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
967 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
968 * @return array Complex array as described above
970 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
971 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
972 global $DB;
974 // Retrieve information about all users and their roles on the course or
975 // parent ('related') contexts
976 $context = context_course::instance($courseid);
978 // We are looking for all users with this role assigned in this context or higher.
979 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
981 if ($extrawheretest) {
982 $extrawheretest = ' AND ' . $extrawheretest;
985 if (is_null($sort)) {
986 list($sort, $sortparams) = users_order_by_sql('u');
987 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
990 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
991 FROM {groups_members} gm
992 JOIN {user} u ON u.id = gm.userid
993 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
994 LEFT JOIN {role} r ON r.id = ra.roleid
995 WHERE gm.groupid=:mgroupid
996 ".$extrawheretest."
997 ORDER BY r.sortorder, $sort";
998 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
999 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
1001 return groups_calculate_role_people($rs, $context);
1005 * Internal function used by groups_get_members_by_role to handle the
1006 * results of a database query that includes a list of users and possible
1007 * roles on a course.
1009 * @param moodle_recordset $rs The record set (may be false)
1010 * @param int $context ID of course context
1011 * @return array As described in groups_get_members_by_role
1013 function groups_calculate_role_people($rs, $context) {
1014 global $CFG, $DB;
1016 if (!$rs) {
1017 return array();
1020 $allroles = role_fix_names(get_all_roles($context), $context);
1021 $visibleroles = get_viewable_roles($context);
1023 // Array of all involved roles
1024 $roles = array();
1025 // Array of all retrieved users
1026 $users = array();
1027 // Fill arrays
1028 foreach ($rs as $rec) {
1029 // Create information about user if this is a new one
1030 if (!array_key_exists($rec->userid, $users)) {
1031 // User data includes all the optional fields, but not any of the
1032 // stuff we added to get the role details
1033 $userdata = clone($rec);
1034 unset($userdata->roleid);
1035 unset($userdata->roleshortname);
1036 unset($userdata->rolename);
1037 unset($userdata->userid);
1038 $userdata->id = $rec->userid;
1040 // Make an array to hold the list of roles for this user
1041 $userdata->roles = array();
1042 $users[$rec->userid] = $userdata;
1044 // If user has a role...
1045 if (!is_null($rec->roleid)) {
1046 // Create information about role if this is a new one
1047 if (!array_key_exists($rec->roleid, $roles)) {
1048 $role = $allroles[$rec->roleid];
1049 $roledata = new stdClass();
1050 $roledata->id = $role->id;
1051 $roledata->shortname = $role->shortname;
1052 $roledata->name = $role->localname;
1053 $roledata->users = array();
1054 $roles[$roledata->id] = $roledata;
1056 // Record that user has role
1057 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
1060 $rs->close();
1062 // Return false if there weren't any users
1063 if (count($users) == 0) {
1064 return false;
1067 // Add pseudo-role for multiple roles
1068 $roledata = new stdClass();
1069 $roledata->name = get_string('multipleroles','role');
1070 $roledata->users = array();
1071 $roles['*'] = $roledata;
1073 $roledata = new stdClass();
1074 $roledata->name = get_string('noroles','role');
1075 $roledata->users = array();
1076 $roles[0] = $roledata;
1078 // Now we rearrange the data to store users by role
1079 foreach ($users as $userid=>$userdata) {
1080 $visibleuserroles = array_intersect_key($userdata->roles, $visibleroles);
1081 $rolecount = count($visibleuserroles);
1082 if ($rolecount == 0) {
1083 // does not have any roles
1084 $roleid = 0;
1085 } else if($rolecount > 1) {
1086 $roleid = '*';
1087 } else {
1088 $userrole = reset($visibleuserroles);
1089 $roleid = $userrole->id;
1091 $roles[$roleid]->users[$userid] = $userdata;
1094 // Delete roles not used
1095 foreach ($roles as $key=>$roledata) {
1096 if (count($roledata->users)===0) {
1097 unset($roles[$key]);
1101 // Return list of roles containing their users
1102 return $roles;
1106 * Synchronises enrolments with the group membership
1108 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1109 * and group membership, such as enrol_cohort and enrol_meta .
1111 * @param string $enrolname name of enrolment method without prefix
1112 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1113 * @param string $gidfield name of the field in 'enrol' table that stores group id
1114 * @return array Returns the list of removed and added users. Each record contains fields:
1115 * userid, enrolid, courseid, groupid, groupname
1117 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1118 global $DB;
1119 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1120 $params = array(
1121 'enrolname' => $enrolname,
1122 'component' => 'enrol_'.$enrolname,
1123 'courseid' => $courseid
1126 $affectedusers = array(
1127 'removed' => array(),
1128 'added' => array()
1131 // Remove invalid.
1132 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1133 FROM {groups_members} gm
1134 JOIN {groups} g ON (g.id = gm.groupid)
1135 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1136 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1137 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1139 $rs = $DB->get_recordset_sql($sql, $params);
1140 foreach ($rs as $gm) {
1141 groups_remove_member($gm->groupid, $gm->userid);
1142 $affectedusers['removed'][] = $gm;
1144 $rs->close();
1146 // Add missing.
1147 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1148 FROM {user_enrolments} ue
1149 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1150 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1151 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1152 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1153 WHERE gm.id IS NULL";
1155 $rs = $DB->get_recordset_sql($sql, $params);
1156 foreach ($rs as $ue) {
1157 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1158 $affectedusers['added'][] = $ue;
1160 $rs->close();
1162 return $affectedusers;
1166 * Callback for inplace editable API.
1168 * @param string $itemtype - Only user_groups is supported.
1169 * @param string $itemid - Userid and groupid separated by a :
1170 * @param string $newvalue - json encoded list of groupids.
1171 * @return \core\output\inplace_editable
1173 function core_group_inplace_editable($itemtype, $itemid, $newvalue) {
1174 if ($itemtype === 'user_groups') {
1175 return \core_group\output\user_groups_editable::update($itemid, $newvalue);