Merge branch 'MDL-49247_27' of git://github.com/timhunt/moodle into MOODLE_27_STABLE
[moodle.git] / group / lib.php
blob83672a09cb7234e86827f2d30014c1918315477d
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);
348 //TODO: it would make sense to allow picture deleting too (skodak)
349 if ($iconfile = $editform->save_temp_file('imagefile')) {
350 if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
351 $DB->set_field('groups', 'picture', $rev, array('id'=>$group->id));
352 $group->picture = $rev;
353 } else {
354 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
355 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id));
356 $group->picture = 0;
358 @unlink($iconfile);
359 // Invalidate the group data as we've updated the group record.
360 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
365 * Update group
367 * @param stdClass $data group properties (with magic quotes)
368 * @param stdClass $editform
369 * @param array $editoroptions
370 * @return bool true or exception
372 function groups_update_group($data, $editform = false, $editoroptions = false) {
373 global $CFG, $DB;
375 $context = context_course::instance($data->courseid);
377 $data->timemodified = time();
378 $data->name = trim($data->name);
379 if (isset($data->idnumber)) {
380 $data->idnumber = trim($data->idnumber);
381 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
382 throw new moodle_exception('idnumbertaken');
386 if ($editform and $editoroptions) {
387 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
390 $DB->update_record('groups', $data);
392 // Invalidate the group data.
393 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
395 $group = $DB->get_record('groups', array('id'=>$data->id));
397 if ($editform) {
398 groups_update_group_icon($group, $data, $editform);
401 // Trigger group event.
402 $params = array(
403 'context' => $context,
404 'objectid' => $group->id
406 $event = \core\event\group_updated::create($params);
407 $event->add_record_snapshot('groups', $group);
408 $event->trigger();
410 return true;
414 * Update grouping
416 * @param stdClass $data grouping properties (with magic quotes)
417 * @param array $editoroptions
418 * @return bool true or exception
420 function groups_update_grouping($data, $editoroptions=null) {
421 global $DB;
422 $data->timemodified = time();
423 $data->name = trim($data->name);
424 if (isset($data->idnumber)) {
425 $data->idnumber = trim($data->idnumber);
426 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
427 throw new moodle_exception('idnumbertaken');
430 if ($editoroptions !== null) {
431 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
433 $DB->update_record('groupings', $data);
435 // Invalidate the group data.
436 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
438 // Trigger group event.
439 $params = array(
440 'context' => context_course::instance($data->courseid),
441 'objectid' => $data->id
443 $event = \core\event\grouping_updated::create($params);
444 $event->trigger();
446 return true;
450 * Delete a group best effort, first removing members and links with courses and groupings.
451 * Removes group avatar too.
453 * @param mixed $grouporid The id of group to delete or full group object
454 * @return bool True if deletion was successful, false otherwise
456 function groups_delete_group($grouporid) {
457 global $CFG, $DB;
458 require_once("$CFG->libdir/gdlib.php");
460 if (is_object($grouporid)) {
461 $groupid = $grouporid->id;
462 $group = $grouporid;
463 } else {
464 $groupid = $grouporid;
465 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
466 //silently ignore attempts to delete missing already deleted groups ;-)
467 return true;
471 // delete group calendar events
472 $DB->delete_records('event', array('groupid'=>$groupid));
473 //first delete usage in groupings_groups
474 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
475 //delete members
476 $DB->delete_records('groups_members', array('groupid'=>$groupid));
477 //group itself last
478 $DB->delete_records('groups', array('id'=>$groupid));
480 // Delete all files associated with this group
481 $context = context_course::instance($group->courseid);
482 $fs = get_file_storage();
483 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
484 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
486 // Invalidate the grouping cache for the course
487 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
489 // Trigger group event.
490 $params = array(
491 'context' => $context,
492 'objectid' => $groupid
494 $event = \core\event\group_deleted::create($params);
495 $event->add_record_snapshot('groups', $group);
496 $event->trigger();
498 return true;
502 * Delete grouping
504 * @param int $groupingorid
505 * @return bool success
507 function groups_delete_grouping($groupingorid) {
508 global $DB;
510 if (is_object($groupingorid)) {
511 $groupingid = $groupingorid->id;
512 $grouping = $groupingorid;
513 } else {
514 $groupingid = $groupingorid;
515 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
516 //silently ignore attempts to delete missing already deleted groupings ;-)
517 return true;
521 //first delete usage in groupings_groups
522 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
523 // remove the default groupingid from course
524 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
525 // remove the groupingid from all course modules
526 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
527 //group itself last
528 $DB->delete_records('groupings', array('id'=>$groupingid));
530 $context = context_course::instance($grouping->courseid);
531 $fs = get_file_storage();
532 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
533 foreach ($files as $file) {
534 $file->delete();
537 // Invalidate the grouping cache for the course
538 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
540 // Trigger group event.
541 $params = array(
542 'context' => $context,
543 'objectid' => $groupingid
545 $event = \core\event\grouping_deleted::create($params);
546 $event->add_record_snapshot('groupings', $grouping);
547 $event->trigger();
549 return true;
553 * Remove all users (or one user) from all groups in course
555 * @param int $courseid
556 * @param int $userid 0 means all users
557 * @param bool $showfeedback
558 * @return bool success
560 function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
561 global $DB, $OUTPUT;
563 if (is_bool($userid)) {
564 debugging('Incorrect userid function parameter');
565 return false;
568 // Select * so that the function groups_remove_member() gets the whole record.
569 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
570 foreach ($groups as $group) {
571 if ($userid) {
572 $userids = array($userid);
573 } else {
574 $userids = $DB->get_fieldset_select('groups_members', 'userid', 'groupid = :groupid', array('groupid' => $group->id));
577 foreach ($userids as $id) {
578 groups_remove_member($group, $id);
582 // TODO MDL-41312 Remove events_trigger_legacy('groups_members_removed').
583 // This event is kept here for backwards compatibility, because it cannot be
584 // translated to a new event as it is wrong.
585 $eventdata = new stdClass();
586 $eventdata->courseid = $courseid;
587 $eventdata->userid = $userid;
588 events_trigger_legacy('groups_members_removed', $eventdata);
590 if ($showfeedback) {
591 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
594 return true;
598 * Remove all groups from all groupings in course
600 * @param int $courseid
601 * @param bool $showfeedback
602 * @return bool success
604 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
605 global $DB, $OUTPUT;
607 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
608 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
609 array($courseid), '', 'groupid, groupingid');
611 foreach ($results as $result) {
612 groups_unassign_grouping($result->groupingid, $result->groupid, false);
615 // Invalidate the grouping cache for the course
616 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
618 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_groups_removed').
619 // This event is kept here for backwards compatibility, because it cannot be
620 // translated to a new event as it is wrong.
621 events_trigger_legacy('groups_groupings_groups_removed', $courseid);
623 // no need to show any feedback here - we delete usually first groupings and then groups
625 return true;
629 * Delete all groups from course
631 * @param int $courseid
632 * @param bool $showfeedback
633 * @return bool success
635 function groups_delete_groups($courseid, $showfeedback=false) {
636 global $CFG, $DB, $OUTPUT;
638 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
639 foreach ($groups as $group) {
640 groups_delete_group($group);
643 // Invalidate the grouping cache for the course
644 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
646 // TODO MDL-41312 Remove events_trigger_legacy('groups_groups_deleted').
647 // This event is kept here for backwards compatibility, because it cannot be
648 // translated to a new event as it is wrong.
649 events_trigger_legacy('groups_groups_deleted', $courseid);
651 if ($showfeedback) {
652 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
655 return true;
659 * Delete all groupings from course
661 * @param int $courseid
662 * @param bool $showfeedback
663 * @return bool success
665 function groups_delete_groupings($courseid, $showfeedback=false) {
666 global $DB, $OUTPUT;
668 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
669 foreach ($groupings as $grouping) {
670 groups_delete_grouping($grouping);
673 // Invalidate the grouping cache for the course.
674 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
676 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_deleted').
677 // This event is kept here for backwards compatibility, because it cannot be
678 // translated to a new event as it is wrong.
679 events_trigger_legacy('groups_groupings_deleted', $courseid);
681 if ($showfeedback) {
682 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
685 return true;
688 /* =================================== */
689 /* various functions used by groups UI */
690 /* =================================== */
693 * Obtains a list of the possible roles that group members might come from,
694 * on a course. Generally this includes only profile roles.
696 * @param context $context Context of course
697 * @return Array of role ID integers, or false if error/none.
699 function groups_get_possible_roles($context) {
700 $roles = get_profile_roles($context);
701 return array_keys($roles);
706 * Gets potential group members for grouping
708 * @param int $courseid The id of the course
709 * @param int $roleid The role to select users from
710 * @param int $cohortid restrict to cohort id
711 * @param string $orderby The column to sort users by
712 * @return array An array of the users
714 function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
715 global $DB;
717 $context = context_course::instance($courseid);
719 list($esql, $params) = get_enrolled_sql($context);
721 if ($roleid) {
722 // We are looking for all users with this role assigned in this context or higher.
723 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
725 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
726 $where = "WHERE u.id IN (SELECT userid
727 FROM {role_assignments}
728 WHERE roleid = :roleid AND contextid $relatedctxsql)";
729 } else {
730 $where = "";
733 if ($cohortid) {
734 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
735 $params['cohortid'] = $cohortid;
736 } else {
737 $cohortjoin = "";
740 $allusernamefields = get_all_user_name_fields(true, 'u');
741 $sql = "SELECT u.id, u.username, $allusernamefields, u.idnumber
742 FROM {user} u
743 JOIN ($esql) e ON e.id = u.id
744 $cohortjoin
745 $where
746 ORDER BY $orderby";
748 return $DB->get_records_sql($sql, $params);
753 * Parse a group name for characters to replace
755 * @param string $format The format a group name will follow
756 * @param int $groupnumber The number of the group to be used in the parsed format string
757 * @return string the parsed format string
759 function groups_parse_name($format, $groupnumber) {
760 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
761 $letter = 'A';
762 for($i=0; $i<$groupnumber; $i++) {
763 $letter++;
765 $str = str_replace('@', $letter, $format);
766 } else {
767 $str = str_replace('#', $groupnumber+1, $format);
769 return($str);
773 * Assigns group into grouping
775 * @param int groupingid
776 * @param int groupid
777 * @param int $timeadded The time the group was added to the grouping.
778 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
779 * @return bool true or exception
781 function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
782 global $DB;
784 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
785 return true;
787 $assign = new stdClass();
788 $assign->groupingid = $groupingid;
789 $assign->groupid = $groupid;
790 if ($timeadded != null) {
791 $assign->timeadded = (integer)$timeadded;
792 } else {
793 $assign->timeadded = time();
795 $DB->insert_record('groupings_groups', $assign);
797 if ($invalidatecache) {
798 // Invalidate the grouping cache for the course
799 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
800 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
803 return true;
807 * Unassigns group from grouping
809 * @param int groupingid
810 * @param int groupid
811 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
812 * @return bool success
814 function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
815 global $DB;
816 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
818 if ($invalidatecache) {
819 // Invalidate the grouping cache for the course
820 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
821 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
824 return true;
828 * Lists users in a group based on their role on the course.
829 * Returns false if there's an error or there are no users in the group.
830 * Otherwise returns an array of role ID => role data, where role data includes:
831 * (role) $id, $shortname, $name
832 * $users: array of objects for each user which include the specified fields
833 * Users who do not have a role are stored in the returned array with key '-'
834 * and pseudo-role details (including a name, 'No role'). Users with multiple
835 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
836 * which roles each has by looking in the $roles array of the user object.
838 * @param int $groupid
839 * @param int $courseid Course ID (should match the group's course)
840 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
841 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
842 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
843 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
844 * @return array Complex array as described above
846 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
847 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
848 global $DB;
850 // Retrieve information about all users and their roles on the course or
851 // parent ('related') contexts
852 $context = context_course::instance($courseid);
854 // We are looking for all users with this role assigned in this context or higher.
855 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
857 if ($extrawheretest) {
858 $extrawheretest = ' AND ' . $extrawheretest;
861 if (is_null($sort)) {
862 list($sort, $sortparams) = users_order_by_sql('u');
863 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
866 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
867 FROM {groups_members} gm
868 JOIN {user} u ON u.id = gm.userid
869 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
870 LEFT JOIN {role} r ON r.id = ra.roleid
871 WHERE gm.groupid=:mgroupid
872 ".$extrawheretest."
873 ORDER BY r.sortorder, $sort";
874 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
875 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
877 return groups_calculate_role_people($rs, $context);
881 * Internal function used by groups_get_members_by_role to handle the
882 * results of a database query that includes a list of users and possible
883 * roles on a course.
885 * @param moodle_recordset $rs The record set (may be false)
886 * @param int $context ID of course context
887 * @return array As described in groups_get_members_by_role
889 function groups_calculate_role_people($rs, $context) {
890 global $CFG, $DB;
892 if (!$rs) {
893 return array();
896 $allroles = role_fix_names(get_all_roles($context), $context);
898 // Array of all involved roles
899 $roles = array();
900 // Array of all retrieved users
901 $users = array();
902 // Fill arrays
903 foreach ($rs as $rec) {
904 // Create information about user if this is a new one
905 if (!array_key_exists($rec->userid, $users)) {
906 // User data includes all the optional fields, but not any of the
907 // stuff we added to get the role details
908 $userdata = clone($rec);
909 unset($userdata->roleid);
910 unset($userdata->roleshortname);
911 unset($userdata->rolename);
912 unset($userdata->userid);
913 $userdata->id = $rec->userid;
915 // Make an array to hold the list of roles for this user
916 $userdata->roles = array();
917 $users[$rec->userid] = $userdata;
919 // If user has a role...
920 if (!is_null($rec->roleid)) {
921 // Create information about role if this is a new one
922 if (!array_key_exists($rec->roleid, $roles)) {
923 $role = $allroles[$rec->roleid];
924 $roledata = new stdClass();
925 $roledata->id = $role->id;
926 $roledata->shortname = $role->shortname;
927 $roledata->name = $role->localname;
928 $roledata->users = array();
929 $roles[$roledata->id] = $roledata;
931 // Record that user has role
932 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
935 $rs->close();
937 // Return false if there weren't any users
938 if (count($users) == 0) {
939 return false;
942 // Add pseudo-role for multiple roles
943 $roledata = new stdClass();
944 $roledata->name = get_string('multipleroles','role');
945 $roledata->users = array();
946 $roles['*'] = $roledata;
948 $roledata = new stdClass();
949 $roledata->name = get_string('noroles','role');
950 $roledata->users = array();
951 $roles[0] = $roledata;
953 // Now we rearrange the data to store users by role
954 foreach ($users as $userid=>$userdata) {
955 $rolecount = count($userdata->roles);
956 if ($rolecount == 0) {
957 // does not have any roles
958 $roleid = 0;
959 } else if($rolecount > 1) {
960 $roleid = '*';
961 } else {
962 $userrole = reset($userdata->roles);
963 $roleid = $userrole->id;
965 $roles[$roleid]->users[$userid] = $userdata;
968 // Delete roles not used
969 foreach ($roles as $key=>$roledata) {
970 if (count($roledata->users)===0) {
971 unset($roles[$key]);
975 // Return list of roles containing their users
976 return $roles;