Merge branch 'MDL-44612-33' of git://github.com/junpataleta/moodle into MOODLE_33_STABLE
[moodle.git] / group / lib.php
blob374925d18a8b678156a8cd916ddbbe2bd4c532fe
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 // TODO MDL-41312 Remove events_trigger_legacy('groups_members_removed').
604 // This event is kept here for backwards compatibility, because it cannot be
605 // translated to a new event as it is wrong.
606 $eventdata = new stdClass();
607 $eventdata->courseid = $courseid;
608 $eventdata->userid = $userid;
609 events_trigger_legacy('groups_members_removed', $eventdata);
611 return true;
615 * Remove all groups from all groupings in course
617 * @param int $courseid
618 * @param bool $showfeedback
619 * @return bool success
621 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
622 global $DB, $OUTPUT;
624 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
625 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
626 array($courseid), '', 'groupid, groupingid');
628 foreach ($results as $result) {
629 groups_unassign_grouping($result->groupingid, $result->groupid, false);
632 // Invalidate the grouping cache for the course
633 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
634 // Purge the group and grouping cache for users.
635 cache_helper::purge_by_definition('core', 'user_group_groupings');
637 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_groups_removed').
638 // This event is kept here for backwards compatibility, because it cannot be
639 // translated to a new event as it is wrong.
640 events_trigger_legacy('groups_groupings_groups_removed', $courseid);
642 // no need to show any feedback here - we delete usually first groupings and then groups
644 return true;
648 * Delete all groups from course
650 * @param int $courseid
651 * @param bool $showfeedback
652 * @return bool success
654 function groups_delete_groups($courseid, $showfeedback=false) {
655 global $CFG, $DB, $OUTPUT;
657 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
658 foreach ($groups as $group) {
659 groups_delete_group($group);
662 // Invalidate the grouping cache for the course
663 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
664 // Purge the group and grouping cache for users.
665 cache_helper::purge_by_definition('core', 'user_group_groupings');
667 // TODO MDL-41312 Remove events_trigger_legacy('groups_groups_deleted').
668 // This event is kept here for backwards compatibility, because it cannot be
669 // translated to a new event as it is wrong.
670 events_trigger_legacy('groups_groups_deleted', $courseid);
672 if ($showfeedback) {
673 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
676 return true;
680 * Delete all groupings from course
682 * @param int $courseid
683 * @param bool $showfeedback
684 * @return bool success
686 function groups_delete_groupings($courseid, $showfeedback=false) {
687 global $DB, $OUTPUT;
689 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
690 foreach ($groupings as $grouping) {
691 groups_delete_grouping($grouping);
694 // Invalidate the grouping cache for the course.
695 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
696 // Purge the group and grouping cache for users.
697 cache_helper::purge_by_definition('core', 'user_group_groupings');
699 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_deleted').
700 // This event is kept here for backwards compatibility, because it cannot be
701 // translated to a new event as it is wrong.
702 events_trigger_legacy('groups_groupings_deleted', $courseid);
704 if ($showfeedback) {
705 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
708 return true;
711 /* =================================== */
712 /* various functions used by groups UI */
713 /* =================================== */
716 * Obtains a list of the possible roles that group members might come from,
717 * on a course. Generally this includes only profile roles.
719 * @param context $context Context of course
720 * @return Array of role ID integers, or false if error/none.
722 function groups_get_possible_roles($context) {
723 $roles = get_profile_roles($context);
724 return array_keys($roles);
729 * Gets potential group members for grouping
731 * @param int $courseid The id of the course
732 * @param int $roleid The role to select users from
733 * @param mixed $source restrict to cohort, grouping or group id
734 * @param string $orderby The column to sort users by
735 * @param int $notingroup restrict to users not in existing groups
736 * @param bool $onlyactiveenrolments restrict to users who have an active enrolment in the course
737 * @return array An array of the users
739 function groups_get_potential_members($courseid, $roleid = null, $source = null,
740 $orderby = 'lastname ASC, firstname ASC',
741 $notingroup = null, $onlyactiveenrolments = false) {
742 global $DB;
744 $context = context_course::instance($courseid);
746 list($esql, $params) = get_enrolled_sql($context, '', 0, $onlyactiveenrolments);
748 $notingroupsql = "";
749 if ($notingroup) {
750 // We want to eliminate users that are already associated with a course group.
751 $notingroupsql = "u.id NOT IN (SELECT userid
752 FROM {groups_members}
753 WHERE groupid IN (SELECT id
754 FROM {groups}
755 WHERE courseid = :courseid))";
756 $params['courseid'] = $courseid;
759 if ($roleid) {
760 // We are looking for all users with this role assigned in this context or higher.
761 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
762 SQL_PARAMS_NAMED,
763 'relatedctx');
765 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
766 $where = "WHERE u.id IN (SELECT userid
767 FROM {role_assignments}
768 WHERE roleid = :roleid AND contextid $relatedctxsql)";
769 $where .= $notingroup ? "AND $notingroupsql" : "";
770 } else if ($notingroup) {
771 $where = "WHERE $notingroupsql";
772 } else {
773 $where = "";
776 $sourcejoin = "";
777 if (is_int($source)) {
778 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
779 $params['cohortid'] = $source;
780 } else {
781 // Auto-create groups from an existing cohort membership.
782 if (isset($source['cohortid'])) {
783 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
784 $params['cohortid'] = $source['cohortid'];
786 // Auto-create groups from an existing group membership.
787 if (isset($source['groupid'])) {
788 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
789 $params['groupid'] = $source['groupid'];
791 // Auto-create groups from an existing grouping membership.
792 if (isset($source['groupingid'])) {
793 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
794 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
795 $params['groupingid'] = $source['groupingid'];
799 $allusernamefields = get_all_user_name_fields(true, 'u');
800 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
801 FROM {user} u
802 JOIN ($esql) e ON e.id = u.id
803 $sourcejoin
804 $where
805 ORDER BY $orderby";
807 return $DB->get_records_sql($sql, $params);
812 * Parse a group name for characters to replace
814 * @param string $format The format a group name will follow
815 * @param int $groupnumber The number of the group to be used in the parsed format string
816 * @return string the parsed format string
818 function groups_parse_name($format, $groupnumber) {
819 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
820 $letter = 'A';
821 for($i=0; $i<$groupnumber; $i++) {
822 $letter++;
824 $str = str_replace('@', $letter, $format);
825 } else {
826 $str = str_replace('#', $groupnumber+1, $format);
828 return($str);
832 * Assigns group into grouping
834 * @param int groupingid
835 * @param int groupid
836 * @param int $timeadded The time the group was added to the grouping.
837 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
838 * @return bool true or exception
840 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
841 global $DB;
843 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
844 return true;
846 $assign = new stdClass();
847 $assign->groupingid = $groupingid;
848 $assign->groupid = $groupid;
849 if ($timeadded != null) {
850 $assign->timeadded = (integer)$timeadded;
851 } else {
852 $assign->timeadded = time();
854 $DB->insert_record('groupings_groups', $assign);
856 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
857 if ($invalidatecache) {
858 // Invalidate the grouping cache for the course
859 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
860 // Purge the group and grouping cache for users.
861 cache_helper::purge_by_definition('core', 'user_group_groupings');
864 // Trigger event.
865 $params = array(
866 'context' => context_course::instance($courseid),
867 'objectid' => $groupingid,
868 'other' => array('groupid' => $groupid)
870 $event = \core\event\grouping_group_assigned::create($params);
871 $event->trigger();
873 return true;
877 * Unassigns group from grouping
879 * @param int groupingid
880 * @param int groupid
881 * @param bool $invalidatecache If set to true the course group cache and the user group cache will be invalidated as well.
882 * @return bool success
884 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
885 global $DB;
886 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
888 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
889 if ($invalidatecache) {
890 // Invalidate the grouping cache for the course
891 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
892 // Purge the group and grouping cache for users.
893 cache_helper::purge_by_definition('core', 'user_group_groupings');
896 // Trigger event.
897 $params = array(
898 'context' => context_course::instance($courseid),
899 'objectid' => $groupingid,
900 'other' => array('groupid' => $groupid)
902 $event = \core\event\grouping_group_unassigned::create($params);
903 $event->trigger();
905 return true;
909 * Lists users in a group based on their role on the course.
910 * Returns false if there's an error or there are no users in the group.
911 * Otherwise returns an array of role ID => role data, where role data includes:
912 * (role) $id, $shortname, $name
913 * $users: array of objects for each user which include the specified fields
914 * Users who do not have a role are stored in the returned array with key '-'
915 * and pseudo-role details (including a name, 'No role'). Users with multiple
916 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
917 * which roles each has by looking in the $roles array of the user object.
919 * @param int $groupid
920 * @param int $courseid Course ID (should match the group's course)
921 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
922 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
923 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
924 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
925 * @return array Complex array as described above
927 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
928 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
929 global $DB;
931 // Retrieve information about all users and their roles on the course or
932 // parent ('related') contexts
933 $context = context_course::instance($courseid);
935 // We are looking for all users with this role assigned in this context or higher.
936 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
938 if ($extrawheretest) {
939 $extrawheretest = ' AND ' . $extrawheretest;
942 if (is_null($sort)) {
943 list($sort, $sortparams) = users_order_by_sql('u');
944 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
947 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
948 FROM {groups_members} gm
949 JOIN {user} u ON u.id = gm.userid
950 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
951 LEFT JOIN {role} r ON r.id = ra.roleid
952 WHERE gm.groupid=:mgroupid
953 ".$extrawheretest."
954 ORDER BY r.sortorder, $sort";
955 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
956 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
958 return groups_calculate_role_people($rs, $context);
962 * Internal function used by groups_get_members_by_role to handle the
963 * results of a database query that includes a list of users and possible
964 * roles on a course.
966 * @param moodle_recordset $rs The record set (may be false)
967 * @param int $context ID of course context
968 * @return array As described in groups_get_members_by_role
970 function groups_calculate_role_people($rs, $context) {
971 global $CFG, $DB;
973 if (!$rs) {
974 return array();
977 $allroles = role_fix_names(get_all_roles($context), $context);
979 // Array of all involved roles
980 $roles = array();
981 // Array of all retrieved users
982 $users = array();
983 // Fill arrays
984 foreach ($rs as $rec) {
985 // Create information about user if this is a new one
986 if (!array_key_exists($rec->userid, $users)) {
987 // User data includes all the optional fields, but not any of the
988 // stuff we added to get the role details
989 $userdata = clone($rec);
990 unset($userdata->roleid);
991 unset($userdata->roleshortname);
992 unset($userdata->rolename);
993 unset($userdata->userid);
994 $userdata->id = $rec->userid;
996 // Make an array to hold the list of roles for this user
997 $userdata->roles = array();
998 $users[$rec->userid] = $userdata;
1000 // If user has a role...
1001 if (!is_null($rec->roleid)) {
1002 // Create information about role if this is a new one
1003 if (!array_key_exists($rec->roleid, $roles)) {
1004 $role = $allroles[$rec->roleid];
1005 $roledata = new stdClass();
1006 $roledata->id = $role->id;
1007 $roledata->shortname = $role->shortname;
1008 $roledata->name = $role->localname;
1009 $roledata->users = array();
1010 $roles[$roledata->id] = $roledata;
1012 // Record that user has role
1013 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
1016 $rs->close();
1018 // Return false if there weren't any users
1019 if (count($users) == 0) {
1020 return false;
1023 // Add pseudo-role for multiple roles
1024 $roledata = new stdClass();
1025 $roledata->name = get_string('multipleroles','role');
1026 $roledata->users = array();
1027 $roles['*'] = $roledata;
1029 $roledata = new stdClass();
1030 $roledata->name = get_string('noroles','role');
1031 $roledata->users = array();
1032 $roles[0] = $roledata;
1034 // Now we rearrange the data to store users by role
1035 foreach ($users as $userid=>$userdata) {
1036 $rolecount = count($userdata->roles);
1037 if ($rolecount == 0) {
1038 // does not have any roles
1039 $roleid = 0;
1040 } else if($rolecount > 1) {
1041 $roleid = '*';
1042 } else {
1043 $userrole = reset($userdata->roles);
1044 $roleid = $userrole->id;
1046 $roles[$roleid]->users[$userid] = $userdata;
1049 // Delete roles not used
1050 foreach ($roles as $key=>$roledata) {
1051 if (count($roledata->users)===0) {
1052 unset($roles[$key]);
1056 // Return list of roles containing their users
1057 return $roles;
1061 * Synchronises enrolments with the group membership
1063 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1064 * and group membership, such as enrol_cohort and enrol_meta .
1066 * @param string $enrolname name of enrolment method without prefix
1067 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1068 * @param string $gidfield name of the field in 'enrol' table that stores group id
1069 * @return array Returns the list of removed and added users. Each record contains fields:
1070 * userid, enrolid, courseid, groupid, groupname
1072 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1073 global $DB;
1074 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1075 $params = array(
1076 'enrolname' => $enrolname,
1077 'component' => 'enrol_'.$enrolname,
1078 'courseid' => $courseid
1081 $affectedusers = array(
1082 'removed' => array(),
1083 'added' => array()
1086 // Remove invalid.
1087 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1088 FROM {groups_members} gm
1089 JOIN {groups} g ON (g.id = gm.groupid)
1090 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1091 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1092 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1094 $rs = $DB->get_recordset_sql($sql, $params);
1095 foreach ($rs as $gm) {
1096 groups_remove_member($gm->groupid, $gm->userid);
1097 $affectedusers['removed'][] = $gm;
1099 $rs->close();
1101 // Add missing.
1102 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1103 FROM {user_enrolments} ue
1104 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1105 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1106 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1107 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1108 WHERE gm.id IS NULL";
1110 $rs = $DB->get_recordset_sql($sql, $params);
1111 foreach ($rs as $ue) {
1112 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1113 $affectedusers['added'][] = $ue;
1115 $rs->close();
1117 return $affectedusers;