Merge branch 'MDL-25801' of git://github.com/timhunt/moodle
[moodle.git] / group / lib.php
blobc933fbfbc757d479deb0e7e835c534cfe340fd28
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 * @return bool True if user added successfully or the user is already a
37 * member of the group, false otherwise.
39 function groups_add_member($grouporid, $userorid) {
40 global $DB;
42 if (is_object($userorid)) {
43 $userid = $userorid->id;
44 $user = $userorid;
45 } else {
46 $userid = $userorid;
47 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
50 if (is_object($grouporid)) {
51 $groupid = $grouporid->id;
52 $group = $grouporid;
53 } else {
54 $groupid = $grouporid;
55 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
58 //check if the user a participant of the group course
59 if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $group->courseid), $userid)) {
60 return false;
63 if (groups_is_member($groupid, $userid)) {
64 return true;
67 $member = new stdClass();
68 $member->groupid = $groupid;
69 $member->userid = $userid;
70 $member->timeadded = time();
72 $DB->insert_record('groups_members', $member);
74 //update group info
75 $DB->set_field('groups', 'timemodified', $member->timeadded, array('id'=>$groupid));
77 //trigger groups events
78 $eventdata = new stdClass();
79 $eventdata->groupid = $groupid;
80 $eventdata->userid = $userid;
81 events_trigger('groups_member_added', $eventdata);
83 return true;
86 /**
87 * Deletes the link between the specified user and group.
89 * @param mixed $grouporid The group id or group object
90 * @param mixed $userorid The user id or user object
91 * @return bool True if deletion was successful, false otherwise
93 function groups_remove_member($grouporid, $userorid) {
94 global $DB;
96 if (is_object($userorid)) {
97 $userid = $userorid->id;
98 $user = $userorid;
99 } else {
100 $userid = $userorid;
101 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
104 if (is_object($grouporid)) {
105 $groupid = $grouporid->id;
106 $group = $grouporid;
107 } else {
108 $groupid = $grouporid;
109 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
112 if (!groups_is_member($groupid, $userid)) {
113 return true;
116 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
118 //update group info
119 $DB->set_field('groups', 'timemodified', time(), array('id'=>$groupid));
121 //trigger groups events
122 $eventdata = new stdClass();
123 $eventdata->groupid = $groupid;
124 $eventdata->userid = $userid;
125 events_trigger('groups_member_removed', $eventdata);
127 return true;
131 * Add a new group
133 * @param stdClass $data group properties
134 * @param stdClass $editform
135 * @param array $editoroptions
136 * @return id of group or false if error
138 function groups_create_group($data, $editform = false, $editoroptions = false) {
139 global $CFG, $DB;
141 //check that courseid exists
142 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
143 $context = get_context_instance(CONTEXT_COURSE, $course->id);
145 $data->timecreated = time();
146 $data->timemodified = $data->timecreated;
147 $data->name = trim($data->name);
149 if ($editform and $editoroptions) {
150 $data->description = $data->description_editor['text'];
151 $data->descriptionformat = $data->description_editor['format'];
154 $data->id = $DB->insert_record('groups', $data);
156 if ($editform and $editoroptions) {
157 // Update description from editor with fixed files
158 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
159 $upd = new stdClass();
160 $upd->id = $data->id;
161 $upd->description = $data->description;
162 $upd->descriptionformat = $data->descriptionformat;
163 $DB->update_record('groups', $upd);
166 $group = $DB->get_record('groups', array('id'=>$data->id));
168 if ($editform) {
169 groups_update_group_icon($group, $data, $editform);
172 //trigger groups events
173 events_trigger('groups_group_created', $group);
175 return $group->id;
179 * Add a new grouping
181 * @param stdClass $data grouping properties
182 * @param array $editoroptions
183 * @return id of grouping or false if error
185 function groups_create_grouping($data, $editoroptions=null) {
186 global $DB;
188 $data->timecreated = time();
189 $data->timemodified = $data->timecreated;
190 $data->name = trim($data->name);
192 if ($editoroptions !== null) {
193 $data->description = $data->description_editor['text'];
194 $data->descriptionformat = $data->description_editor['format'];
197 $id = $DB->insert_record('groupings', $data);
199 //trigger groups events
200 $data->id = $id;
202 if ($editoroptions !== null) {
203 $description = new stdClass;
204 $description->id = $data->id;
205 $description->description_editor = $data->description_editor;
206 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
207 $DB->update_record('groupings', $description);
210 events_trigger('groups_grouping_created', $data);
212 return $id;
216 * Update the group icon from form data
218 * @param stdClass $group group information
219 * @param stdClass $data
220 * @param stdClass $editform
222 function groups_update_group_icon($group, $data, $editform) {
223 global $CFG, $DB;
224 require_once("$CFG->libdir/gdlib.php");
226 $fs = get_file_storage();
227 $context = get_context_instance(CONTEXT_COURSE, $group->courseid, MUST_EXIST);
229 //TODO: it would make sense to allow picture deleting too (skodak)
231 if ($iconfile = $editform->save_temp_file('imagefile')) {
232 if (process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
233 $DB->set_field('groups', 'picture', 1, array('id'=>$group->id));
234 $group->picture = 1;
235 } else {
236 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
237 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id));
238 $group->picture = 0;
240 @unlink($iconfile);
245 * Update group
247 * @param stdClass $data group properties (with magic quotes)
248 * @param stdClass $editform
249 * @param array $editoroptions
250 * @return bool true or exception
252 function groups_update_group($data, $editform = false, $editoroptions = false) {
253 global $CFG, $DB;
255 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
257 $data->timemodified = time();
258 $data->name = trim($data->name);
260 if ($editform and $editoroptions) {
261 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
264 $DB->update_record('groups', $data);
266 $group = $DB->get_record('groups', array('id'=>$data->id));
268 if ($editform) {
269 groups_update_group_icon($group, $data, $editform);
272 //trigger groups events
273 events_trigger('groups_group_updated', $group);
276 return true;
280 * Update grouping
282 * @param stdClass $data grouping properties (with magic quotes)
283 * @param array $editoroptions
284 * @return bool true or exception
286 function groups_update_grouping($data, $editoroptions=null) {
287 global $DB;
288 $data->timemodified = time();
289 $data->name = trim($data->name);
290 if ($editoroptions !== null) {
291 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
293 $DB->update_record('groupings', $data);
294 //trigger groups events
295 events_trigger('groups_grouping_updated', $data);
297 return true;
301 * Delete a group best effort, first removing members and links with courses and groupings.
302 * Removes group avatar too.
304 * @param mixed $grouporid The id of group to delete or full group object
305 * @return bool True if deletion was successful, false otherwise
307 function groups_delete_group($grouporid) {
308 global $CFG, $DB;
309 require_once("$CFG->libdir/gdlib.php");
311 if (is_object($grouporid)) {
312 $groupid = $grouporid->id;
313 $group = $grouporid;
314 } else {
315 $groupid = $grouporid;
316 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
317 //silently ignore attempts to delete missing already deleted groups ;-)
318 return true;
322 // delete group calendar events
323 $DB->delete_records('event', array('groupid'=>$groupid));
324 //first delete usage in groupings_groups
325 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
326 //delete members
327 $DB->delete_records('groups_members', array('groupid'=>$groupid));
328 //group itself last
329 $DB->delete_records('groups', array('id'=>$groupid));
331 // Delete all files associated with this group
332 $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
333 $fs = get_file_storage();
334 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
335 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
337 //trigger groups events
338 events_trigger('groups_group_deleted', $group);
340 return true;
344 * Delete grouping
346 * @param int $groupingorid
347 * @return bool success
349 function groups_delete_grouping($groupingorid) {
350 global $DB;
352 if (is_object($groupingorid)) {
353 $groupingid = $groupingorid->id;
354 $grouping = $groupingorid;
355 } else {
356 $groupingid = $groupingorid;
357 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
358 //silently ignore attempts to delete missing already deleted groupings ;-)
359 return true;
363 //first delete usage in groupings_groups
364 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
365 // remove the default groupingid from course
366 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
367 // remove the groupingid from all course modules
368 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
369 //group itself last
370 $DB->delete_records('groupings', array('id'=>$groupingid));
372 $context = get_context_instance(CONTEXT_COURSE, $grouping->courseid);
373 $fs = get_file_storage();
374 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
375 foreach ($files as $file) {
376 $file->delete();
379 //trigger groups events
380 events_trigger('groups_grouping_deleted', $grouping);
382 return true;
386 * Remove all users (or one user) from all groups in course
388 * @param int $courseid
389 * @param int $userid 0 means all users
390 * @param bool $showfeedback
391 * @return bool success
393 function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
394 global $DB, $OUTPUT;
396 if (is_bool($userid)) {
397 debugging('Incorrect userid function parameter');
398 return false;
401 $params = array('courseid'=>$courseid);
403 if ($userid) {
404 $usersql = "AND userid = :userid";
405 $params['userid'] = $userid;
406 } else {
407 $usersql = "";
410 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = :courseid";
411 $DB->delete_records_select('groups_members', "groupid IN ($groupssql) $usersql", $params);
413 //trigger groups events
414 $eventdata = new stdClass();
415 $eventdata->courseid = $courseid;
416 $eventdata->userid = $userid;
417 events_trigger('groups_members_removed', $eventdata);
419 if ($showfeedback) {
420 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
423 return true;
427 * Remove all groups from all groupings in course
429 * @param int $courseid
430 * @param bool $showfeedback
431 * @return bool success
433 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
434 global $DB, $OUTPUT;
436 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
437 $DB->delete_records_select('groupings_groups', "groupid IN ($groupssql)", array($courseid));
439 //trigger groups events
440 events_trigger('groups_groupings_groups_removed', $courseid);
442 // no need to show any feedback here - we delete usually first groupings and then groups
444 return true;
448 * Delete all groups from course
450 * @param int $courseid
451 * @param bool $showfeedback
452 * @return bool success
454 function groups_delete_groups($courseid, $showfeedback=false) {
455 global $CFG, $DB, $OUTPUT;
457 // delete any uses of groups
458 // Any associated files are deleted as part of groups_delete_groupings_groups
459 groups_delete_groupings_groups($courseid, $showfeedback);
460 groups_delete_group_members($courseid, 0, $showfeedback);
462 // delete group pictures and descriptions
463 $context = get_context_instance(CONTEXT_COURSE, $courseid);
464 $fs = get_file_storage();
465 $fs->delete_area_files($context->id, 'group');
467 // delete group calendar events
468 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
469 $DB->delete_records_select('event', "groupid IN ($groupssql)", array($courseid));
471 $context = get_context_instance(CONTEXT_COURSE, $courseid);
472 $fs = get_file_storage();
473 $fs->delete_area_files($context->id, 'group');
475 $DB->delete_records('groups', array('courseid'=>$courseid));
477 // trigger groups events
478 events_trigger('groups_groups_deleted', $courseid);
480 if ($showfeedback) {
481 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
484 return true;
488 * Delete all groupings from course
490 * @param int $courseid
491 * @param bool $showfeedback
492 * @return bool success
494 function groups_delete_groupings($courseid, $showfeedback=false) {
495 global $DB, $OUTPUT;
497 // delete any uses of groupings
498 $sql = "DELETE FROM {groupings_groups}
499 WHERE groupingid in (SELECT id FROM {groupings} g WHERE g.courseid = ?)";
500 $DB->execute($sql, array($courseid));
502 // remove the default groupingid from course
503 $DB->set_field('course', 'defaultgroupingid', 0, array('id'=>$courseid));
504 // remove the groupingid from all course modules
505 $DB->set_field('course_modules', 'groupingid', 0, array('course'=>$courseid));
507 // Delete all files associated with groupings for this course
508 $context = get_context_instance(CONTEXT_COURSE, $courseid);
509 $fs = get_file_storage();
510 $fs->delete_area_files($context->id, 'grouping');
512 $DB->delete_records('groupings', array('courseid'=>$courseid));
514 // trigger groups events
515 events_trigger('groups_groupings_deleted', $courseid);
517 if ($showfeedback) {
518 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
521 return true;
524 /* =================================== */
525 /* various functions used by groups UI */
526 /* =================================== */
529 * Obtains a list of the possible roles that group members might come from,
530 * on a course. Generally this includes only profile roles.
532 * @param context $context Context of course
533 * @return Array of role ID integers, or false if error/none.
535 function groups_get_possible_roles($context) {
536 $roles = get_profile_roles($context);
537 return array_keys($roles);
542 * Gets potential group members for grouping
544 * @param int $courseid The id of the course
545 * @param int $roleid The role to select users from
546 * @param int $cohortid restrict to cohort id
547 * @param string $orderby The column to sort users by
548 * @return array An array of the users
550 function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
551 global $DB;
553 $context = get_context_instance(CONTEXT_COURSE, $courseid);
555 // we are looking for all users with this role assigned in this context or higher
556 $listofcontexts = get_related_contexts_string($context);
558 list($esql, $params) = get_enrolled_sql($context);
560 if ($roleid) {
561 $params['roleid'] = $roleid;
562 $where = "WHERE u.id IN (SELECT userid
563 FROM {role_assignments}
564 WHERE roleid = :roleid AND contextid $listofcontexts)";
565 } else {
566 $where = "";
569 if ($cohortid) {
570 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
571 $params['cohortid'] = $cohortid;
572 } else {
573 $cohortjoin = "";
576 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
577 FROM {user} u
578 JOIN ($esql) e ON e.id = u.id
579 $cohortjoin
580 $where
581 ORDER BY $orderby";
583 return $DB->get_records_sql($sql, $params);
588 * Parse a group name for characters to replace
590 * @param string $format The format a group name will follow
591 * @param int $groupnumber The number of the group to be used in the parsed format string
592 * @return string the parsed format string
594 function groups_parse_name($format, $groupnumber) {
595 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
596 $letter = 'A';
597 for($i=0; $i<$groupnumber; $i++) {
598 $letter++;
600 $str = str_replace('@', $letter, $format);
601 } else {
602 $str = str_replace('#', $groupnumber+1, $format);
604 return($str);
608 * Assigns group into grouping
610 * @param int groupingid
611 * @param int groupid
612 * @return bool true or exception
614 function groups_assign_grouping($groupingid, $groupid) {
615 global $DB;
617 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
618 return true;
620 $assign = new stdClass();
621 $assign->groupingid = $groupingid;
622 $assign->groupid = $groupid;
623 $assign->timeadded = time();
624 $DB->insert_record('groupings_groups', $assign);
626 return true;
630 * Unassigns group grom grouping
632 * @param int groupingid
633 * @param int groupid
634 * @return bool success
636 function groups_unassign_grouping($groupingid, $groupid) {
637 global $DB;
638 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
640 return true;
644 * Lists users in a group based on their role on the course.
645 * Returns false if there's an error or there are no users in the group.
646 * Otherwise returns an array of role ID => role data, where role data includes:
647 * (role) $id, $shortname, $name
648 * $users: array of objects for each user which include the specified fields
649 * Users who do not have a role are stored in the returned array with key '-'
650 * and pseudo-role details (including a name, 'No role'). Users with multiple
651 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
652 * which roles each has by looking in the $roles array of the user object.
654 * @param int $groupid
655 * @param int $courseid Course ID (should match the group's course)
656 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
657 * @param string $sort SQL ORDER BY clause, default 'u.lastname ASC'
658 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
659 * @param array $whereparams any parameters required by $extrawheretest (named parameters).
660 * @return array Complex array as described above
662 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
663 $sort='u.lastname ASC', $extrawheretest='', $whereparams=array()) {
664 global $CFG, $DB;
666 // Retrieve information about all users and their roles on the course or
667 // parent ('related') contexts
668 $context = get_context_instance(CONTEXT_COURSE, $courseid);
670 if ($extrawheretest) {
671 $extrawheretest = ' AND ' . $extrawheretest;
674 $sql = "SELECT r.id AS roleid, r.shortname AS roleshortname, r.name AS rolename,
675 u.id AS userid, $fields
676 FROM {groups_members} gm
677 JOIN {user} u ON u.id = gm.userid
678 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid ".get_related_contexts_string($context).")
679 LEFT JOIN {role} r ON r.id = ra.roleid
680 WHERE gm.groupid=:mgroupid
681 ".$extrawheretest."
682 ORDER BY r.sortorder, $sort";
683 $whereparams['mgroupid'] = $groupid;
684 $rs = $DB->get_recordset_sql($sql, $whereparams);
686 return groups_calculate_role_people($rs, $context);
690 * Internal function used by groups_get_members_by_role to handle the
691 * results of a database query that includes a list of users and possible
692 * roles on a course.
694 * @param moodle_recordset $rs The record set (may be false)
695 * @param int $context ID of course context
696 * @return array As described in groups_get_members_by_role
698 function groups_calculate_role_people($rs, $context) {
699 global $CFG, $DB;
701 if (!$rs) {
702 return array();
705 $roles = $DB->get_records_menu('role', null, 'name', 'id, name');
706 $aliasnames = role_fix_names($roles, $context);
708 // Array of all involved roles
709 $roles = array();
710 // Array of all retrieved users
711 $users = array();
712 // Fill arrays
713 foreach ($rs as $rec) {
714 // Create information about user if this is a new one
715 if (!array_key_exists($rec->userid, $users)) {
716 // User data includes all the optional fields, but not any of the
717 // stuff we added to get the role details
718 $userdata = clone($rec);
719 unset($userdata->roleid);
720 unset($userdata->roleshortname);
721 unset($userdata->rolename);
722 unset($userdata->userid);
723 $userdata->id = $rec->userid;
725 // Make an array to hold the list of roles for this user
726 $userdata->roles = array();
727 $users[$rec->userid] = $userdata;
729 // If user has a role...
730 if (!is_null($rec->roleid)) {
731 // Create information about role if this is a new one
732 if (!array_key_exists($rec->roleid,$roles)) {
733 $roledata = new stdClass();
734 $roledata->id = $rec->roleid;
735 $roledata->shortname = $rec->roleshortname;
736 if (array_key_exists($rec->roleid, $aliasnames)) {
737 $roledata->name = $aliasnames[$rec->roleid];
738 } else {
739 $roledata->name = $rec->rolename;
741 $roledata->users = array();
742 $roles[$roledata->id] = $roledata;
744 // Record that user has role
745 $users[$rec->userid]->roles[] = $roles[$rec->roleid];
748 $rs->close();
750 // Return false if there weren't any users
751 if (count($users) == 0) {
752 return false;
755 // Add pseudo-role for multiple roles
756 $roledata = new stdClass();
757 $roledata->name = get_string('multipleroles','role');
758 $roledata->users = array();
759 $roles['*'] = $roledata;
761 $roledata = new stdClass();
762 $roledata->name = get_string('noroles','role');
763 $roledata->users = array();
764 $roles[0] = $roledata;
766 // Now we rearrange the data to store users by role
767 foreach ($users as $userid=>$userdata) {
768 $rolecount = count($userdata->roles);
769 if ($rolecount == 0) {
770 // does not have any roles
771 $roleid = 0;
772 } else if($rolecount > 1) {
773 $roleid = '*';
774 } else {
775 $roleid = $userdata->roles[0]->id;
777 $roles[$roleid]->users[$userid] = $userdata;
780 // Delete roles not used
781 foreach ($roles as $key=>$roledata) {
782 if (count($roledata->users)===0) {
783 unset($roles[$key]);
787 // Return list of roles containing their users
788 return $roles;