Merge branch 'MDL-53279_master' of git://github.com/dmonllao/moodle
[moodle.git] / group / lib.php
blobe0c0e4b45746a225a3c2e2003c6f734525c6b802
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 // Trigger group event.
108 $params = array(
109 'context' => $context,
110 'objectid' => $groupid,
111 'relateduserid' => $userid,
112 'other' => array(
113 'component' => $member->component,
114 'itemid' => $member->itemid
117 $event = \core\event\group_member_added::create($params);
118 $event->add_record_snapshot('groups', $group);
119 $event->trigger();
121 return true;
125 * Checks whether the current user is permitted (using the normal UI) to
126 * remove a specific group member, assuming that they have access to remove
127 * group members in general.
129 * For automatically-created group member entries, this checks with the
130 * relevant plugin to see whether it is permitted. The default, if the plugin
131 * doesn't provide a function, is true.
133 * For other entries (and any which have already been deleted/don't exist) it
134 * just returns true.
136 * @param mixed $grouporid The group id or group object
137 * @param mixed $userorid The user id or user object
138 * @return bool True if permitted, false otherwise
140 function groups_remove_member_allowed($grouporid, $userorid) {
141 global $DB;
143 if (is_object($userorid)) {
144 $userid = $userorid->id;
145 } else {
146 $userid = $userorid;
148 if (is_object($grouporid)) {
149 $groupid = $grouporid->id;
150 } else {
151 $groupid = $grouporid;
154 // Get entry
155 if (!($entry = $DB->get_record('groups_members',
156 array('groupid' => $groupid, 'userid' => $userid), '*', IGNORE_MISSING))) {
157 // If the entry does not exist, they are allowed to remove it (this
158 // is consistent with groups_remove_member below).
159 return true;
162 // If the entry does not have a component value, they can remove it
163 if (empty($entry->component)) {
164 return true;
167 // It has a component value, so we need to call a plugin function (if it
168 // exists); the default is to allow removal
169 return component_callback($entry->component, 'allow_group_member_remove',
170 array($entry->itemid, $entry->groupid, $entry->userid), true);
174 * Deletes the link between the specified user and group.
176 * @param mixed $grouporid The group id or group object
177 * @param mixed $userorid The user id or user object
178 * @return bool True if deletion was successful, false otherwise
180 function groups_remove_member($grouporid, $userorid) {
181 global $DB;
183 if (is_object($userorid)) {
184 $userid = $userorid->id;
185 } else {
186 $userid = $userorid;
189 if (is_object($grouporid)) {
190 $groupid = $grouporid->id;
191 $group = $grouporid;
192 } else {
193 $groupid = $grouporid;
194 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
197 if (!groups_is_member($groupid, $userid)) {
198 return true;
201 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
203 // Update group info.
204 $time = time();
205 $DB->set_field('groups', 'timemodified', $time, array('id' => $groupid));
206 $group->timemodified = $time;
208 // Trigger group event.
209 $params = array(
210 'context' => context_course::instance($group->courseid),
211 'objectid' => $groupid,
212 'relateduserid' => $userid
214 $event = \core\event\group_member_removed::create($params);
215 $event->add_record_snapshot('groups', $group);
216 $event->trigger();
218 return true;
222 * Add a new group
224 * @param stdClass $data group properties
225 * @param stdClass $editform
226 * @param array $editoroptions
227 * @return id of group or false if error
229 function groups_create_group($data, $editform = false, $editoroptions = false) {
230 global $CFG, $DB;
232 //check that courseid exists
233 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
234 $context = context_course::instance($course->id);
236 $data->timecreated = time();
237 $data->timemodified = $data->timecreated;
238 $data->name = trim($data->name);
239 if (isset($data->idnumber)) {
240 $data->idnumber = trim($data->idnumber);
241 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
242 throw new moodle_exception('idnumbertaken');
246 if ($editform and $editoroptions) {
247 $data->description = $data->description_editor['text'];
248 $data->descriptionformat = $data->description_editor['format'];
251 $data->id = $DB->insert_record('groups', $data);
253 if ($editform and $editoroptions) {
254 // Update description from editor with fixed files
255 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
256 $upd = new stdClass();
257 $upd->id = $data->id;
258 $upd->description = $data->description;
259 $upd->descriptionformat = $data->descriptionformat;
260 $DB->update_record('groups', $upd);
263 $group = $DB->get_record('groups', array('id'=>$data->id));
265 if ($editform) {
266 groups_update_group_icon($group, $data, $editform);
269 // Invalidate the grouping cache for the course
270 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($course->id));
272 // Trigger group event.
273 $params = array(
274 'context' => $context,
275 'objectid' => $group->id
277 $event = \core\event\group_created::create($params);
278 $event->add_record_snapshot('groups', $group);
279 $event->trigger();
281 return $group->id;
285 * Add a new grouping
287 * @param stdClass $data grouping properties
288 * @param array $editoroptions
289 * @return id of grouping or false if error
291 function groups_create_grouping($data, $editoroptions=null) {
292 global $DB;
294 $data->timecreated = time();
295 $data->timemodified = $data->timecreated;
296 $data->name = trim($data->name);
297 if (isset($data->idnumber)) {
298 $data->idnumber = trim($data->idnumber);
299 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
300 throw new moodle_exception('idnumbertaken');
304 if ($editoroptions !== null) {
305 $data->description = $data->description_editor['text'];
306 $data->descriptionformat = $data->description_editor['format'];
309 $id = $DB->insert_record('groupings', $data);
310 $data->id = $id;
312 if ($editoroptions !== null) {
313 $description = new stdClass;
314 $description->id = $data->id;
315 $description->description_editor = $data->description_editor;
316 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
317 $DB->update_record('groupings', $description);
320 // Invalidate the grouping cache for the course
321 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
323 // Trigger group event.
324 $params = array(
325 'context' => context_course::instance($data->courseid),
326 'objectid' => $id
328 $event = \core\event\grouping_created::create($params);
329 $event->trigger();
331 return $id;
335 * Update the group icon from form data
337 * @param stdClass $group group information
338 * @param stdClass $data
339 * @param stdClass $editform
341 function groups_update_group_icon($group, $data, $editform) {
342 global $CFG, $DB;
343 require_once("$CFG->libdir/gdlib.php");
345 $fs = get_file_storage();
346 $context = context_course::instance($group->courseid, MUST_EXIST);
347 $newpicture = $group->picture;
349 if (!empty($data->deletepicture)) {
350 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
351 $newpicture = 0;
352 } else if ($iconfile = $editform->save_temp_file('imagefile')) {
353 if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
354 $newpicture = $rev;
355 } else {
356 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
357 $newpicture = 0;
359 @unlink($iconfile);
362 if ($newpicture != $group->picture) {
363 $DB->set_field('groups', 'picture', $newpicture, array('id' => $group->id));
364 $group->picture = $newpicture;
366 // Invalidate the group data as we've updated the group record.
367 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
372 * Update group
374 * @param stdClass $data group properties (with magic quotes)
375 * @param stdClass $editform
376 * @param array $editoroptions
377 * @return bool true or exception
379 function groups_update_group($data, $editform = false, $editoroptions = false) {
380 global $CFG, $DB;
382 $context = context_course::instance($data->courseid);
384 $data->timemodified = time();
385 if (isset($data->name)) {
386 $data->name = trim($data->name);
388 if (isset($data->idnumber)) {
389 $data->idnumber = trim($data->idnumber);
390 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
391 throw new moodle_exception('idnumbertaken');
395 if ($editform and $editoroptions) {
396 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
399 $DB->update_record('groups', $data);
401 // Invalidate the group data.
402 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
404 $group = $DB->get_record('groups', array('id'=>$data->id));
406 if ($editform) {
407 groups_update_group_icon($group, $data, $editform);
410 // Trigger group event.
411 $params = array(
412 'context' => $context,
413 'objectid' => $group->id
415 $event = \core\event\group_updated::create($params);
416 $event->add_record_snapshot('groups', $group);
417 $event->trigger();
419 return true;
423 * Update grouping
425 * @param stdClass $data grouping properties (with magic quotes)
426 * @param array $editoroptions
427 * @return bool true or exception
429 function groups_update_grouping($data, $editoroptions=null) {
430 global $DB;
431 $data->timemodified = time();
432 if (isset($data->name)) {
433 $data->name = trim($data->name);
435 if (isset($data->idnumber)) {
436 $data->idnumber = trim($data->idnumber);
437 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
438 throw new moodle_exception('idnumbertaken');
441 if ($editoroptions !== null) {
442 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
444 $DB->update_record('groupings', $data);
446 // Invalidate the group data.
447 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
449 // Trigger group event.
450 $params = array(
451 'context' => context_course::instance($data->courseid),
452 'objectid' => $data->id
454 $event = \core\event\grouping_updated::create($params);
455 $event->trigger();
457 return true;
461 * Delete a group best effort, first removing members and links with courses and groupings.
462 * Removes group avatar too.
464 * @param mixed $grouporid The id of group to delete or full group object
465 * @return bool True if deletion was successful, false otherwise
467 function groups_delete_group($grouporid) {
468 global $CFG, $DB;
469 require_once("$CFG->libdir/gdlib.php");
471 if (is_object($grouporid)) {
472 $groupid = $grouporid->id;
473 $group = $grouporid;
474 } else {
475 $groupid = $grouporid;
476 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
477 //silently ignore attempts to delete missing already deleted groups ;-)
478 return true;
482 // delete group calendar events
483 $DB->delete_records('event', array('groupid'=>$groupid));
484 //first delete usage in groupings_groups
485 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
486 //delete members
487 $DB->delete_records('groups_members', array('groupid'=>$groupid));
488 //group itself last
489 $DB->delete_records('groups', array('id'=>$groupid));
491 // Delete all files associated with this group
492 $context = context_course::instance($group->courseid);
493 $fs = get_file_storage();
494 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
495 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
497 // Invalidate the grouping cache for the course
498 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
500 // Trigger group event.
501 $params = array(
502 'context' => $context,
503 'objectid' => $groupid
505 $event = \core\event\group_deleted::create($params);
506 $event->add_record_snapshot('groups', $group);
507 $event->trigger();
509 return true;
513 * Delete grouping
515 * @param int $groupingorid
516 * @return bool success
518 function groups_delete_grouping($groupingorid) {
519 global $DB;
521 if (is_object($groupingorid)) {
522 $groupingid = $groupingorid->id;
523 $grouping = $groupingorid;
524 } else {
525 $groupingid = $groupingorid;
526 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
527 //silently ignore attempts to delete missing already deleted groupings ;-)
528 return true;
532 //first delete usage in groupings_groups
533 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
534 // remove the default groupingid from course
535 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
536 // remove the groupingid from all course modules
537 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
538 //group itself last
539 $DB->delete_records('groupings', array('id'=>$groupingid));
541 $context = context_course::instance($grouping->courseid);
542 $fs = get_file_storage();
543 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
544 foreach ($files as $file) {
545 $file->delete();
548 // Invalidate the grouping cache for the course
549 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
551 // Trigger group event.
552 $params = array(
553 'context' => $context,
554 'objectid' => $groupingid
556 $event = \core\event\grouping_deleted::create($params);
557 $event->add_record_snapshot('groupings', $grouping);
558 $event->trigger();
560 return true;
564 * Remove all users (or one user) from all groups in course
566 * @param int $courseid
567 * @param int $userid 0 means all users
568 * @param bool $unused - formerly $showfeedback, is no longer used.
569 * @return bool success
571 function groups_delete_group_members($courseid, $userid=0, $unused=false) {
572 global $DB, $OUTPUT;
574 // Get the users in the course which are in a group.
575 $sql = "SELECT gm.id as gmid, gm.userid, g.*
576 FROM {groups_members} gm
577 INNER JOIN {groups} g
578 ON gm.groupid = g.id
579 WHERE g.courseid = :courseid";
580 $params = array();
581 $params['courseid'] = $courseid;
582 // Check if we want to delete a specific user.
583 if ($userid) {
584 $sql .= " AND gm.userid = :userid";
585 $params['userid'] = $userid;
587 $rs = $DB->get_recordset_sql($sql, $params);
588 foreach ($rs as $usergroup) {
589 groups_remove_member($usergroup, $usergroup->userid);
591 $rs->close();
593 // TODO MDL-41312 Remove events_trigger_legacy('groups_members_removed').
594 // This event is kept here for backwards compatibility, because it cannot be
595 // translated to a new event as it is wrong.
596 $eventdata = new stdClass();
597 $eventdata->courseid = $courseid;
598 $eventdata->userid = $userid;
599 events_trigger_legacy('groups_members_removed', $eventdata);
601 return true;
605 * Remove all groups from all groupings in course
607 * @param int $courseid
608 * @param bool $showfeedback
609 * @return bool success
611 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
612 global $DB, $OUTPUT;
614 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
615 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
616 array($courseid), '', 'groupid, groupingid');
618 foreach ($results as $result) {
619 groups_unassign_grouping($result->groupingid, $result->groupid, false);
622 // Invalidate the grouping cache for the course
623 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
625 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_groups_removed').
626 // This event is kept here for backwards compatibility, because it cannot be
627 // translated to a new event as it is wrong.
628 events_trigger_legacy('groups_groupings_groups_removed', $courseid);
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);
650 // Invalidate the grouping cache for the course
651 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
653 // TODO MDL-41312 Remove events_trigger_legacy('groups_groups_deleted').
654 // This event is kept here for backwards compatibility, because it cannot be
655 // translated to a new event as it is wrong.
656 events_trigger_legacy('groups_groups_deleted', $courseid);
658 if ($showfeedback) {
659 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
662 return true;
666 * Delete all groupings from course
668 * @param int $courseid
669 * @param bool $showfeedback
670 * @return bool success
672 function groups_delete_groupings($courseid, $showfeedback=false) {
673 global $DB, $OUTPUT;
675 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
676 foreach ($groupings as $grouping) {
677 groups_delete_grouping($grouping);
680 // Invalidate the grouping cache for the course.
681 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
683 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_deleted').
684 // This event is kept here for backwards compatibility, because it cannot be
685 // translated to a new event as it is wrong.
686 events_trigger_legacy('groups_groupings_deleted', $courseid);
688 if ($showfeedback) {
689 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
692 return true;
695 /* =================================== */
696 /* various functions used by groups UI */
697 /* =================================== */
700 * Obtains a list of the possible roles that group members might come from,
701 * on a course. Generally this includes only profile roles.
703 * @param context $context Context of course
704 * @return Array of role ID integers, or false if error/none.
706 function groups_get_possible_roles($context) {
707 $roles = get_profile_roles($context);
708 return array_keys($roles);
713 * Gets potential group members for grouping
715 * @param int $courseid The id of the course
716 * @param int $roleid The role to select users from
717 * @param mixed $source restrict to cohort, grouping or group id
718 * @param string $orderby The column to sort users by
719 * @param int $notingroup restrict to users not in existing groups
720 * @param bool $onlyactiveenrolments restrict to users who have an active enrolment in the course
721 * @return array An array of the users
723 function groups_get_potential_members($courseid, $roleid = null, $source = null,
724 $orderby = 'lastname ASC, firstname ASC',
725 $notingroup = null, $onlyactiveenrolments = false) {
726 global $DB;
728 $context = context_course::instance($courseid);
730 list($esql, $params) = get_enrolled_sql($context, '', 0, $onlyactiveenrolments);
732 $notingroupsql = "";
733 if ($notingroup) {
734 // We want to eliminate users that are already associated with a course group.
735 $notingroupsql = "u.id NOT IN (SELECT userid
736 FROM {groups_members}
737 WHERE groupid IN (SELECT id
738 FROM {groups}
739 WHERE courseid = :courseid))";
740 $params['courseid'] = $courseid;
743 if ($roleid) {
744 // We are looking for all users with this role assigned in this context or higher.
745 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
746 SQL_PARAMS_NAMED,
747 'relatedctx');
749 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
750 $where = "WHERE u.id IN (SELECT userid
751 FROM {role_assignments}
752 WHERE roleid = :roleid AND contextid $relatedctxsql)";
753 $where .= $notingroup ? "AND $notingroupsql" : "";
754 } else if ($notingroup) {
755 $where = "WHERE $notingroupsql";
756 } else {
757 $where = "";
760 $sourcejoin = "";
761 if (is_int($source)) {
762 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
763 $params['cohortid'] = $source;
764 } else {
765 // Auto-create groups from an existing cohort membership.
766 if (isset($source['cohortid'])) {
767 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
768 $params['cohortid'] = $source['cohortid'];
770 // Auto-create groups from an existing group membership.
771 if (isset($source['groupid'])) {
772 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
773 $params['groupid'] = $source['groupid'];
775 // Auto-create groups from an existing grouping membership.
776 if (isset($source['groupingid'])) {
777 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
778 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
779 $params['groupingid'] = $source['groupingid'];
783 $allusernamefields = get_all_user_name_fields(true, 'u');
784 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
785 FROM {user} u
786 JOIN ($esql) e ON e.id = u.id
787 $sourcejoin
788 $where
789 ORDER BY $orderby";
791 return $DB->get_records_sql($sql, $params);
796 * Parse a group name for characters to replace
798 * @param string $format The format a group name will follow
799 * @param int $groupnumber The number of the group to be used in the parsed format string
800 * @return string the parsed format string
802 function groups_parse_name($format, $groupnumber) {
803 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
804 $letter = 'A';
805 for($i=0; $i<$groupnumber; $i++) {
806 $letter++;
808 $str = str_replace('@', $letter, $format);
809 } else {
810 $str = str_replace('#', $groupnumber+1, $format);
812 return($str);
816 * Assigns group into grouping
818 * @param int groupingid
819 * @param int groupid
820 * @param int $timeadded The time the group was added to the grouping.
821 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
822 * @return bool true or exception
824 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
825 global $DB;
827 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
828 return true;
830 $assign = new stdClass();
831 $assign->groupingid = $groupingid;
832 $assign->groupid = $groupid;
833 if ($timeadded != null) {
834 $assign->timeadded = (integer)$timeadded;
835 } else {
836 $assign->timeadded = time();
838 $DB->insert_record('groupings_groups', $assign);
840 if ($invalidatecache) {
841 // Invalidate the grouping cache for the course
842 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
843 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
846 return true;
850 * Unassigns group from grouping
852 * @param int groupingid
853 * @param int groupid
854 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
855 * @return bool success
857 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
858 global $DB;
859 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
861 if ($invalidatecache) {
862 // Invalidate the grouping cache for the course
863 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
864 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
867 return true;
871 * Lists users in a group based on their role on the course.
872 * Returns false if there's an error or there are no users in the group.
873 * Otherwise returns an array of role ID => role data, where role data includes:
874 * (role) $id, $shortname, $name
875 * $users: array of objects for each user which include the specified fields
876 * Users who do not have a role are stored in the returned array with key '-'
877 * and pseudo-role details (including a name, 'No role'). Users with multiple
878 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
879 * which roles each has by looking in the $roles array of the user object.
881 * @param int $groupid
882 * @param int $courseid Course ID (should match the group's course)
883 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
884 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
885 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
886 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
887 * @return array Complex array as described above
889 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
890 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
891 global $DB;
893 // Retrieve information about all users and their roles on the course or
894 // parent ('related') contexts
895 $context = context_course::instance($courseid);
897 // We are looking for all users with this role assigned in this context or higher.
898 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
900 if ($extrawheretest) {
901 $extrawheretest = ' AND ' . $extrawheretest;
904 if (is_null($sort)) {
905 list($sort, $sortparams) = users_order_by_sql('u');
906 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
909 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
910 FROM {groups_members} gm
911 JOIN {user} u ON u.id = gm.userid
912 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
913 LEFT JOIN {role} r ON r.id = ra.roleid
914 WHERE gm.groupid=:mgroupid
915 ".$extrawheretest."
916 ORDER BY r.sortorder, $sort";
917 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
918 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
920 return groups_calculate_role_people($rs, $context);
924 * Internal function used by groups_get_members_by_role to handle the
925 * results of a database query that includes a list of users and possible
926 * roles on a course.
928 * @param moodle_recordset $rs The record set (may be false)
929 * @param int $context ID of course context
930 * @return array As described in groups_get_members_by_role
932 function groups_calculate_role_people($rs, $context) {
933 global $CFG, $DB;
935 if (!$rs) {
936 return array();
939 $allroles = role_fix_names(get_all_roles($context), $context);
941 // Array of all involved roles
942 $roles = array();
943 // Array of all retrieved users
944 $users = array();
945 // Fill arrays
946 foreach ($rs as $rec) {
947 // Create information about user if this is a new one
948 if (!array_key_exists($rec->userid, $users)) {
949 // User data includes all the optional fields, but not any of the
950 // stuff we added to get the role details
951 $userdata = clone($rec);
952 unset($userdata->roleid);
953 unset($userdata->roleshortname);
954 unset($userdata->rolename);
955 unset($userdata->userid);
956 $userdata->id = $rec->userid;
958 // Make an array to hold the list of roles for this user
959 $userdata->roles = array();
960 $users[$rec->userid] = $userdata;
962 // If user has a role...
963 if (!is_null($rec->roleid)) {
964 // Create information about role if this is a new one
965 if (!array_key_exists($rec->roleid, $roles)) {
966 $role = $allroles[$rec->roleid];
967 $roledata = new stdClass();
968 $roledata->id = $role->id;
969 $roledata->shortname = $role->shortname;
970 $roledata->name = $role->localname;
971 $roledata->users = array();
972 $roles[$roledata->id] = $roledata;
974 // Record that user has role
975 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
978 $rs->close();
980 // Return false if there weren't any users
981 if (count($users) == 0) {
982 return false;
985 // Add pseudo-role for multiple roles
986 $roledata = new stdClass();
987 $roledata->name = get_string('multipleroles','role');
988 $roledata->users = array();
989 $roles['*'] = $roledata;
991 $roledata = new stdClass();
992 $roledata->name = get_string('noroles','role');
993 $roledata->users = array();
994 $roles[0] = $roledata;
996 // Now we rearrange the data to store users by role
997 foreach ($users as $userid=>$userdata) {
998 $rolecount = count($userdata->roles);
999 if ($rolecount == 0) {
1000 // does not have any roles
1001 $roleid = 0;
1002 } else if($rolecount > 1) {
1003 $roleid = '*';
1004 } else {
1005 $userrole = reset($userdata->roles);
1006 $roleid = $userrole->id;
1008 $roles[$roleid]->users[$userid] = $userdata;
1011 // Delete roles not used
1012 foreach ($roles as $key=>$roledata) {
1013 if (count($roledata->users)===0) {
1014 unset($roles[$key]);
1018 // Return list of roles containing their users
1019 return $roles;
1023 * Synchronises enrolments with the group membership
1025 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1026 * and group membership, such as enrol_cohort and enrol_meta .
1028 * @param string $enrolname name of enrolment method without prefix
1029 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1030 * @param string $gidfield name of the field in 'enrol' table that stores group id
1031 * @return array Returns the list of removed and added users. Each record contains fields:
1032 * userid, enrolid, courseid, groupid, groupname
1034 function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1035 global $DB;
1036 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1037 $params = array(
1038 'enrolname' => $enrolname,
1039 'component' => 'enrol_'.$enrolname,
1040 'courseid' => $courseid
1043 $affectedusers = array(
1044 'removed' => array(),
1045 'added' => array()
1048 // Remove invalid.
1049 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1050 FROM {groups_members} gm
1051 JOIN {groups} g ON (g.id = gm.groupid)
1052 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1053 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1054 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1056 $rs = $DB->get_recordset_sql($sql, $params);
1057 foreach ($rs as $gm) {
1058 groups_remove_member($gm->groupid, $gm->userid);
1059 $affectedusers['removed'][] = $gm;
1061 $rs->close();
1063 // Add missing.
1064 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1065 FROM {user_enrolments} ue
1066 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1067 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1068 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1069 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1070 WHERE gm.id IS NULL";
1072 $rs = $DB->get_recordset_sql($sql, $params);
1073 foreach ($rs as $ue) {
1074 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1075 $affectedusers['added'][] = $ue;
1077 $rs->close();
1079 return $affectedusers;