MDL-61363 tag: unit tests for delete functions
[moodle.git] / group / lib.php
blobf9339b92029c394ae72d466f181fc91e33ec641b
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 // Trigger group event.
111 $params = array(
112 'context' => $context,
113 'objectid' => $groupid,
114 'relateduserid' => $userid,
115 'other' => array(
116 'component' => $member->component,
117 'itemid' => $member->itemid
120 $event = \core\event\group_member_added::create($params);
121 $event->add_record_snapshot('groups', $group);
122 $event->trigger();
124 return true;
128 * Checks whether the current user is permitted (using the normal UI) to
129 * remove a specific group member, assuming that they have access to remove
130 * group members in general.
132 * For automatically-created group member entries, this checks with the
133 * relevant plugin to see whether it is permitted. The default, if the plugin
134 * doesn't provide a function, is true.
136 * For other entries (and any which have already been deleted/don't exist) it
137 * just returns true.
139 * @param mixed $grouporid The group id or group object
140 * @param mixed $userorid The user id or user object
141 * @return bool True if permitted, false otherwise
143 function groups_remove_member_allowed($grouporid, $userorid) {
144 global $DB;
146 if (is_object($userorid)) {
147 $userid = $userorid->id;
148 } else {
149 $userid = $userorid;
151 if (is_object($grouporid)) {
152 $groupid = $grouporid->id;
153 } else {
154 $groupid = $grouporid;
157 // Get entry
158 if (!($entry = $DB->get_record('groups_members',
159 array('groupid' => $groupid, 'userid' => $userid), '*', IGNORE_MISSING))) {
160 // If the entry does not exist, they are allowed to remove it (this
161 // is consistent with groups_remove_member below).
162 return true;
165 // If the entry does not have a component value, they can remove it
166 if (empty($entry->component)) {
167 return true;
170 // It has a component value, so we need to call a plugin function (if it
171 // exists); the default is to allow removal
172 return component_callback($entry->component, 'allow_group_member_remove',
173 array($entry->itemid, $entry->groupid, $entry->userid), true);
177 * Deletes the link between the specified user and group.
179 * @param mixed $grouporid The group id or group object
180 * @param mixed $userorid The user id or user object
181 * @return bool True if deletion was successful, false otherwise
183 function groups_remove_member($grouporid, $userorid) {
184 global $DB;
186 if (is_object($userorid)) {
187 $userid = $userorid->id;
188 } else {
189 $userid = $userorid;
192 if (is_object($grouporid)) {
193 $groupid = $grouporid->id;
194 $group = $grouporid;
195 } else {
196 $groupid = $grouporid;
197 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
200 if (!groups_is_member($groupid, $userid)) {
201 return true;
204 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
206 // Update group info.
207 $time = time();
208 $DB->set_field('groups', 'timemodified', $time, array('id' => $groupid));
209 $group->timemodified = $time;
211 // Invalidate the group and grouping cache for users.
212 cache_helper::invalidate_by_definition('core', 'user_group_groupings', array(), array($userid));
214 // Trigger group event.
215 $params = array(
216 'context' => context_course::instance($group->courseid),
217 'objectid' => $groupid,
218 'relateduserid' => $userid
220 $event = \core\event\group_member_removed::create($params);
221 $event->add_record_snapshot('groups', $group);
222 $event->trigger();
224 return true;
228 * Add a new group
230 * @param stdClass $data group properties
231 * @param stdClass $editform
232 * @param array $editoroptions
233 * @return id of group or false if error
235 function groups_create_group($data, $editform = false, $editoroptions = false) {
236 global $CFG, $DB;
238 //check that courseid exists
239 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
240 $context = context_course::instance($course->id);
242 $data->timecreated = time();
243 $data->timemodified = $data->timecreated;
244 $data->name = trim($data->name);
245 if (isset($data->idnumber)) {
246 $data->idnumber = trim($data->idnumber);
247 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
248 throw new moodle_exception('idnumbertaken');
252 if ($editform and $editoroptions) {
253 $data->description = $data->description_editor['text'];
254 $data->descriptionformat = $data->description_editor['format'];
257 $data->id = $DB->insert_record('groups', $data);
259 if ($editform and $editoroptions) {
260 // Update description from editor with fixed files
261 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
262 $upd = new stdClass();
263 $upd->id = $data->id;
264 $upd->description = $data->description;
265 $upd->descriptionformat = $data->descriptionformat;
266 $DB->update_record('groups', $upd);
269 $group = $DB->get_record('groups', array('id'=>$data->id));
271 if ($editform) {
272 groups_update_group_icon($group, $data, $editform);
275 // Invalidate the grouping cache for the course
276 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($course->id));
278 // Trigger group event.
279 $params = array(
280 'context' => $context,
281 'objectid' => $group->id
283 $event = \core\event\group_created::create($params);
284 $event->add_record_snapshot('groups', $group);
285 $event->trigger();
287 return $group->id;
291 * Add a new grouping
293 * @param stdClass $data grouping properties
294 * @param array $editoroptions
295 * @return id of grouping or false if error
297 function groups_create_grouping($data, $editoroptions=null) {
298 global $DB;
300 $data->timecreated = time();
301 $data->timemodified = $data->timecreated;
302 $data->name = trim($data->name);
303 if (isset($data->idnumber)) {
304 $data->idnumber = trim($data->idnumber);
305 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
306 throw new moodle_exception('idnumbertaken');
310 if ($editoroptions !== null) {
311 $data->description = $data->description_editor['text'];
312 $data->descriptionformat = $data->description_editor['format'];
315 $id = $DB->insert_record('groupings', $data);
316 $data->id = $id;
318 if ($editoroptions !== null) {
319 $description = new stdClass;
320 $description->id = $data->id;
321 $description->description_editor = $data->description_editor;
322 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
323 $DB->update_record('groupings', $description);
326 // Invalidate the grouping cache for the course
327 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
329 // Trigger group event.
330 $params = array(
331 'context' => context_course::instance($data->courseid),
332 'objectid' => $id
334 $event = \core\event\grouping_created::create($params);
335 $event->trigger();
337 return $id;
341 * Update the group icon from form data
343 * @param stdClass $group group information
344 * @param stdClass $data
345 * @param stdClass $editform
347 function groups_update_group_icon($group, $data, $editform) {
348 global $CFG, $DB;
349 require_once("$CFG->libdir/gdlib.php");
351 $fs = get_file_storage();
352 $context = context_course::instance($group->courseid, MUST_EXIST);
353 $newpicture = $group->picture;
355 if (!empty($data->deletepicture)) {
356 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
357 $newpicture = 0;
358 } else if ($iconfile = $editform->save_temp_file('imagefile')) {
359 if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
360 $newpicture = $rev;
361 } else {
362 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
363 $newpicture = 0;
365 @unlink($iconfile);
368 if ($newpicture != $group->picture) {
369 $DB->set_field('groups', 'picture', $newpicture, array('id' => $group->id));
370 $group->picture = $newpicture;
372 // Invalidate the group data as we've updated the group record.
373 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
378 * Update group
380 * @param stdClass $data group properties (with magic quotes)
381 * @param stdClass $editform
382 * @param array $editoroptions
383 * @return bool true or exception
385 function groups_update_group($data, $editform = false, $editoroptions = false) {
386 global $CFG, $DB;
388 $context = context_course::instance($data->courseid);
390 $data->timemodified = time();
391 if (isset($data->name)) {
392 $data->name = trim($data->name);
394 if (isset($data->idnumber)) {
395 $data->idnumber = trim($data->idnumber);
396 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
397 throw new moodle_exception('idnumbertaken');
401 if ($editform and $editoroptions) {
402 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
405 $DB->update_record('groups', $data);
407 // Invalidate the group data.
408 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
410 $group = $DB->get_record('groups', array('id'=>$data->id));
412 if ($editform) {
413 groups_update_group_icon($group, $data, $editform);
416 // Trigger group event.
417 $params = array(
418 'context' => $context,
419 'objectid' => $group->id
421 $event = \core\event\group_updated::create($params);
422 $event->add_record_snapshot('groups', $group);
423 $event->trigger();
425 return true;
429 * Update grouping
431 * @param stdClass $data grouping properties (with magic quotes)
432 * @param array $editoroptions
433 * @return bool true or exception
435 function groups_update_grouping($data, $editoroptions=null) {
436 global $DB;
437 $data->timemodified = time();
438 if (isset($data->name)) {
439 $data->name = trim($data->name);
441 if (isset($data->idnumber)) {
442 $data->idnumber = trim($data->idnumber);
443 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
444 throw new moodle_exception('idnumbertaken');
447 if ($editoroptions !== null) {
448 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
450 $DB->update_record('groupings', $data);
452 // Invalidate the group data.
453 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
455 // Trigger group event.
456 $params = array(
457 'context' => context_course::instance($data->courseid),
458 'objectid' => $data->id
460 $event = \core\event\grouping_updated::create($params);
461 $event->trigger();
463 return true;
467 * Delete a group best effort, first removing members and links with courses and groupings.
468 * Removes group avatar too.
470 * @param mixed $grouporid The id of group to delete or full group object
471 * @return bool True if deletion was successful, false otherwise
473 function groups_delete_group($grouporid) {
474 global $CFG, $DB;
475 require_once("$CFG->libdir/gdlib.php");
477 if (is_object($grouporid)) {
478 $groupid = $grouporid->id;
479 $group = $grouporid;
480 } else {
481 $groupid = $grouporid;
482 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
483 //silently ignore attempts to delete missing already deleted groups ;-)
484 return true;
488 // delete group calendar events
489 $DB->delete_records('event', array('groupid'=>$groupid));
490 //first delete usage in groupings_groups
491 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
492 //delete members
493 $DB->delete_records('groups_members', array('groupid'=>$groupid));
494 //group itself last
495 $DB->delete_records('groups', array('id'=>$groupid));
497 // Delete all files associated with this group
498 $context = context_course::instance($group->courseid);
499 $fs = get_file_storage();
500 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
501 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
503 // Invalidate the grouping cache for the course
504 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
505 // Purge the group and grouping cache for users.
506 cache_helper::purge_by_definition('core', 'user_group_groupings');
508 // Trigger group event.
509 $params = array(
510 'context' => $context,
511 'objectid' => $groupid
513 $event = \core\event\group_deleted::create($params);
514 $event->add_record_snapshot('groups', $group);
515 $event->trigger();
517 return true;
521 * Delete grouping
523 * @param int $groupingorid
524 * @return bool success
526 function groups_delete_grouping($groupingorid) {
527 global $DB;
529 if (is_object($groupingorid)) {
530 $groupingid = $groupingorid->id;
531 $grouping = $groupingorid;
532 } else {
533 $groupingid = $groupingorid;
534 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
535 //silently ignore attempts to delete missing already deleted groupings ;-)
536 return true;
540 //first delete usage in groupings_groups
541 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
542 // remove the default groupingid from course
543 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
544 // remove the groupingid from all course modules
545 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
546 //group itself last
547 $DB->delete_records('groupings', array('id'=>$groupingid));
549 $context = context_course::instance($grouping->courseid);
550 $fs = get_file_storage();
551 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
552 foreach ($files as $file) {
553 $file->delete();
556 // Invalidate the grouping cache for the course
557 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
558 // Purge the group and grouping cache for users.
559 cache_helper::purge_by_definition('core', 'user_group_groupings');
561 // Trigger group event.
562 $params = array(
563 'context' => $context,
564 'objectid' => $groupingid
566 $event = \core\event\grouping_deleted::create($params);
567 $event->add_record_snapshot('groupings', $grouping);
568 $event->trigger();
570 return true;
574 * Remove all users (or one user) from all groups in course
576 * @param int $courseid
577 * @param int $userid 0 means all users
578 * @param bool $unused - formerly $showfeedback, is no longer used.
579 * @return bool success
581 function groups_delete_group_members($courseid, $userid=0, $unused=false) {
582 global $DB, $OUTPUT;
584 // Get the users in the course which are in a group.
585 $sql = "SELECT gm.id as gmid, gm.userid, g.*
586 FROM {groups_members} gm
587 INNER JOIN {groups} g
588 ON gm.groupid = g.id
589 WHERE g.courseid = :courseid";
590 $params = array();
591 $params['courseid'] = $courseid;
592 // Check if we want to delete a specific user.
593 if ($userid) {
594 $sql .= " AND gm.userid = :userid";
595 $params['userid'] = $userid;
597 $rs = $DB->get_recordset_sql($sql, $params);
598 foreach ($rs as $usergroup) {
599 groups_remove_member($usergroup, $usergroup->userid);
601 $rs->close();
603 return true;
607 * Remove all groups from all groupings in course
609 * @param int $courseid
610 * @param bool $showfeedback
611 * @return bool success
613 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
614 global $DB, $OUTPUT;
616 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
617 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
618 array($courseid), '', 'groupid, groupingid');
620 foreach ($results as $result) {
621 groups_unassign_grouping($result->groupingid, $result->groupid, false);
623 $results->close();
625 // Invalidate the grouping cache for the course
626 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
627 // Purge the group and grouping cache for users.
628 cache_helper::purge_by_definition('core', 'user_group_groupings');
630 // no need to show any feedback here - we delete usually first groupings and then groups
632 return true;
636 * Delete all groups from course
638 * @param int $courseid
639 * @param bool $showfeedback
640 * @return bool success
642 function groups_delete_groups($courseid, $showfeedback=false) {
643 global $CFG, $DB, $OUTPUT;
645 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
646 foreach ($groups as $group) {
647 groups_delete_group($group);
649 $groups->close();
651 // Invalidate the grouping cache for the course
652 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
653 // Purge the group and grouping cache for users.
654 cache_helper::purge_by_definition('core', 'user_group_groupings');
656 if ($showfeedback) {
657 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
660 return true;
664 * Delete all groupings from course
666 * @param int $courseid
667 * @param bool $showfeedback
668 * @return bool success
670 function groups_delete_groupings($courseid, $showfeedback=false) {
671 global $DB, $OUTPUT;
673 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
674 foreach ($groupings as $grouping) {
675 groups_delete_grouping($grouping);
677 $groupings->close();
679 // Invalidate the grouping cache for the course.
680 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
681 // Purge the group and grouping cache for users.
682 cache_helper::purge_by_definition('core', 'user_group_groupings');
684 if ($showfeedback) {
685 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
688 return true;
691 /* =================================== */
692 /* various functions used by groups UI */
693 /* =================================== */
696 * Obtains a list of the possible roles that group members might come from,
697 * on a course. Generally this includes only profile roles.
699 * @param context $context Context of course
700 * @return Array of role ID integers, or false if error/none.
702 function groups_get_possible_roles($context) {
703 $roles = get_profile_roles($context);
704 return array_keys($roles);
709 * Gets potential group members for grouping
711 * @param int $courseid The id of the course
712 * @param int $roleid The role to select users from
713 * @param mixed $source restrict to cohort, grouping or group id
714 * @param string $orderby The column to sort users by
715 * @param int $notingroup restrict to users not in existing groups
716 * @param bool $onlyactiveenrolments restrict to users who have an active enrolment in the course
717 * @return array An array of the users
719 function groups_get_potential_members($courseid, $roleid = null, $source = null,
720 $orderby = 'lastname ASC, firstname ASC',
721 $notingroup = null, $onlyactiveenrolments = false) {
722 global $DB;
724 $context = context_course::instance($courseid);
726 list($esql, $params) = get_enrolled_sql($context, '', 0, $onlyactiveenrolments);
728 $notingroupsql = "";
729 if ($notingroup) {
730 // We want to eliminate users that are already associated with a course group.
731 $notingroupsql = "u.id NOT IN (SELECT userid
732 FROM {groups_members}
733 WHERE groupid IN (SELECT id
734 FROM {groups}
735 WHERE courseid = :courseid))";
736 $params['courseid'] = $courseid;
739 if ($roleid) {
740 // We are looking for all users with this role assigned in this context or higher.
741 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
742 SQL_PARAMS_NAMED,
743 'relatedctx');
745 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
746 $where = "WHERE u.id IN (SELECT userid
747 FROM {role_assignments}
748 WHERE roleid = :roleid AND contextid $relatedctxsql)";
749 $where .= $notingroup ? "AND $notingroupsql" : "";
750 } else if ($notingroup) {
751 $where = "WHERE $notingroupsql";
752 } else {
753 $where = "";
756 $sourcejoin = "";
757 if (is_int($source)) {
758 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
759 $params['cohortid'] = $source;
760 } else {
761 // Auto-create groups from an existing cohort membership.
762 if (isset($source['cohortid'])) {
763 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
764 $params['cohortid'] = $source['cohortid'];
766 // Auto-create groups from an existing group membership.
767 if (isset($source['groupid'])) {
768 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
769 $params['groupid'] = $source['groupid'];
771 // Auto-create groups from an existing grouping membership.
772 if (isset($source['groupingid'])) {
773 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
774 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
775 $params['groupingid'] = $source['groupingid'];
779 $allusernamefields = get_all_user_name_fields(true, 'u');
780 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
781 FROM {user} u
782 JOIN ($esql) e ON e.id = u.id
783 $sourcejoin
784 $where
785 ORDER BY $orderby";
787 return $DB->get_records_sql($sql, $params);
792 * Parse a group name for characters to replace
794 * @param string $format The format a group name will follow
795 * @param int $groupnumber The number of the group to be used in the parsed format string
796 * @return string the parsed format string
798 function groups_parse_name($format, $groupnumber) {
799 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
800 $letter = 'A';
801 for($i=0; $i<$groupnumber; $i++) {
802 $letter++;
804 $str = str_replace('@', $letter, $format);
805 } else {
806 $str = str_replace('#', $groupnumber+1, $format);
808 return($str);
812 * Assigns group into grouping
814 * @param int groupingid
815 * @param int groupid
816 * @param int $timeadded The time the group was added to the grouping.
817 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
818 * @return bool true or exception
820 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
821 global $DB;
823 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
824 return true;
826 $assign = new stdClass();
827 $assign->groupingid = $groupingid;
828 $assign->groupid = $groupid;
829 if ($timeadded != null) {
830 $assign->timeadded = (integer)$timeadded;
831 } else {
832 $assign->timeadded = time();
834 $DB->insert_record('groupings_groups', $assign);
836 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
837 if ($invalidatecache) {
838 // Invalidate the grouping cache for the course
839 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
840 // Purge the group and grouping cache for users.
841 cache_helper::purge_by_definition('core', 'user_group_groupings');
844 // Trigger event.
845 $params = array(
846 'context' => context_course::instance($courseid),
847 'objectid' => $groupingid,
848 'other' => array('groupid' => $groupid)
850 $event = \core\event\grouping_group_assigned::create($params);
851 $event->trigger();
853 return true;
857 * Unassigns group from grouping
859 * @param int groupingid
860 * @param int groupid
861 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
862 * @return bool success
864 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
865 global $DB;
866 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
868 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
869 if ($invalidatecache) {
870 // Invalidate the grouping cache for the course
871 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
872 // Purge the group and grouping cache for users.
873 cache_helper::purge_by_definition('core', 'user_group_groupings');
876 // Trigger event.
877 $params = array(
878 'context' => context_course::instance($courseid),
879 'objectid' => $groupingid,
880 'other' => array('groupid' => $groupid)
882 $event = \core\event\grouping_group_unassigned::create($params);
883 $event->trigger();
885 return true;
889 * Lists users in a group based on their role on the course.
890 * Returns false if there's an error or there are no users in the group.
891 * Otherwise returns an array of role ID => role data, where role data includes:
892 * (role) $id, $shortname, $name
893 * $users: array of objects for each user which include the specified fields
894 * Users who do not have a role are stored in the returned array with key '-'
895 * and pseudo-role details (including a name, 'No role'). Users with multiple
896 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
897 * which roles each has by looking in the $roles array of the user object.
899 * @param int $groupid
900 * @param int $courseid Course ID (should match the group's course)
901 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
902 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
903 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
904 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
905 * @return array Complex array as described above
907 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
908 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
909 global $DB;
911 // Retrieve information about all users and their roles on the course or
912 // parent ('related') contexts
913 $context = context_course::instance($courseid);
915 // We are looking for all users with this role assigned in this context or higher.
916 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
918 if ($extrawheretest) {
919 $extrawheretest = ' AND ' . $extrawheretest;
922 if (is_null($sort)) {
923 list($sort, $sortparams) = users_order_by_sql('u');
924 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
927 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
928 FROM {groups_members} gm
929 JOIN {user} u ON u.id = gm.userid
930 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
931 LEFT JOIN {role} r ON r.id = ra.roleid
932 WHERE gm.groupid=:mgroupid
933 ".$extrawheretest."
934 ORDER BY r.sortorder, $sort";
935 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
936 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
938 return groups_calculate_role_people($rs, $context);
942 * Internal function used by groups_get_members_by_role to handle the
943 * results of a database query that includes a list of users and possible
944 * roles on a course.
946 * @param moodle_recordset $rs The record set (may be false)
947 * @param int $context ID of course context
948 * @return array As described in groups_get_members_by_role
950 function groups_calculate_role_people($rs, $context) {
951 global $CFG, $DB;
953 if (!$rs) {
954 return array();
957 $allroles = role_fix_names(get_all_roles($context), $context);
958 $visibleroles = get_viewable_roles($context);
960 // Array of all involved roles
961 $roles = array();
962 // Array of all retrieved users
963 $users = array();
964 // Fill arrays
965 foreach ($rs as $rec) {
966 // Create information about user if this is a new one
967 if (!array_key_exists($rec->userid, $users)) {
968 // User data includes all the optional fields, but not any of the
969 // stuff we added to get the role details
970 $userdata = clone($rec);
971 unset($userdata->roleid);
972 unset($userdata->roleshortname);
973 unset($userdata->rolename);
974 unset($userdata->userid);
975 $userdata->id = $rec->userid;
977 // Make an array to hold the list of roles for this user
978 $userdata->roles = array();
979 $users[$rec->userid] = $userdata;
981 // If user has a role...
982 if (!is_null($rec->roleid)) {
983 // Create information about role if this is a new one
984 if (!array_key_exists($rec->roleid, $roles)) {
985 $role = $allroles[$rec->roleid];
986 $roledata = new stdClass();
987 $roledata->id = $role->id;
988 $roledata->shortname = $role->shortname;
989 $roledata->name = $role->localname;
990 $roledata->users = array();
991 $roles[$roledata->id] = $roledata;
993 // Record that user has role
994 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
997 $rs->close();
999 // Return false if there weren't any users
1000 if (count($users) == 0) {
1001 return false;
1004 // Add pseudo-role for multiple roles
1005 $roledata = new stdClass();
1006 $roledata->name = get_string('multipleroles','role');
1007 $roledata->users = array();
1008 $roles['*'] = $roledata;
1010 $roledata = new stdClass();
1011 $roledata->name = get_string('noroles','role');
1012 $roledata->users = array();
1013 $roles[0] = $roledata;
1015 // Now we rearrange the data to store users by role
1016 foreach ($users as $userid=>$userdata) {
1017 $visibleuserroles = array_intersect_key($userdata->roles, $visibleroles);
1018 $rolecount = count($visibleuserroles);
1019 if ($rolecount == 0) {
1020 // does not have any roles
1021 $roleid = 0;
1022 } else if($rolecount > 1) {
1023 $roleid = '*';
1024 } else {
1025 $userrole = reset($visibleuserroles);
1026 $roleid = $userrole->id;
1028 $roles[$roleid]->users[$userid] = $userdata;
1031 // Delete roles not used
1032 foreach ($roles as $key=>$roledata) {
1033 if (count($roledata->users)===0) {
1034 unset($roles[$key]);
1038 // Return list of roles containing their users
1039 return $roles;
1043 * Synchronises enrolments with the group membership
1045 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1046 * and group membership, such as enrol_cohort and enrol_meta .
1048 * @param string $enrolname name of enrolment method without prefix
1049 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1050 * @param string $gidfield name of the field in 'enrol' table that stores group id
1051 * @return array Returns the list of removed and added users. Each record contains fields:
1052 * userid, enrolid, courseid, groupid, groupname
1054 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1055 global $DB;
1056 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1057 $params = array(
1058 'enrolname' => $enrolname,
1059 'component' => 'enrol_'.$enrolname,
1060 'courseid' => $courseid
1063 $affectedusers = array(
1064 'removed' => array(),
1065 'added' => array()
1068 // Remove invalid.
1069 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1070 FROM {groups_members} gm
1071 JOIN {groups} g ON (g.id = gm.groupid)
1072 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1073 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1074 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1076 $rs = $DB->get_recordset_sql($sql, $params);
1077 foreach ($rs as $gm) {
1078 groups_remove_member($gm->groupid, $gm->userid);
1079 $affectedusers['removed'][] = $gm;
1081 $rs->close();
1083 // Add missing.
1084 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1085 FROM {user_enrolments} ue
1086 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1087 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1088 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1089 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1090 WHERE gm.id IS NULL";
1092 $rs = $DB->get_recordset_sql($sql, $params);
1093 foreach ($rs as $ue) {
1094 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1095 $affectedusers['added'][] = $ue;
1097 $rs->close();
1099 return $affectedusers;
1103 * Callback for inplace editable API.
1105 * @param string $itemtype - Only user_groups is supported.
1106 * @param string $itemid - Userid and groupid separated by a :
1107 * @param string $newvalue - json encoded list of groupids.
1108 * @return \core\output\inplace_editable
1110 function core_group_inplace_editable($itemtype, $itemid, $newvalue) {
1111 if ($itemtype === 'user_groups') {
1112 return \core_group\output\user_groups_editable::update($itemid, $newvalue);