3 * Extra library for groups and groupings.
5 * @copyright © 2006 The Open University
6 * @author J.White AT open.ac.uk, Petr Skoda (skodak)
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
12 * INTERNAL FUNCTIONS - to be used by moodle core only
13 * require_once $CFG->dirroot.'/group/lib.php' must be used
17 * Adds a specified user to a group
18 * @param mixed $groupid The group id or group object
19 * @param mixed $userid The user id or user object
20 * @return boolean True if user added successfully or the user is already a
21 * member of the group, false otherwise.
23 function groups_add_member($grouporid, $userorid) {
26 if (is_object($userorid)) {
27 $userid = $userorid->id
;
31 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
34 if (is_object($grouporid)) {
35 $groupid = $grouporid->id
;
38 $groupid = $grouporid;
39 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST
);
42 //check if the user a participant of the group course
43 if (!is_enrolled(get_context_instance(CONTEXT_COURSE
, $group->courseid
), $userid)) {
47 if (groups_is_member($groupid, $userid)) {
51 $member = new stdClass();
52 $member->groupid
= $groupid;
53 $member->userid
= $userid;
54 $member->timeadded
= time();
56 $DB->insert_record('groups_members', $member);
59 $DB->set_field('groups', 'timemodified', $member->timeadded
, array('id'=>$groupid));
61 //trigger groups events
62 $eventdata = new stdClass();
63 $eventdata->groupid
= $groupid;
64 $eventdata->userid
= $userid;
65 events_trigger('groups_member_added', $eventdata);
71 * Deletes the link between the specified user and group.
72 * @param mixed $groupid The group id or group object
73 * @param mixed $userid The user id or user object
74 * @return boolean True if deletion was successful, false otherwise
76 function groups_remove_member($grouporid, $userorid) {
79 if (is_object($userorid)) {
80 $userid = $userorid->id
;
84 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
87 if (is_object($grouporid)) {
88 $groupid = $grouporid->id
;
91 $groupid = $grouporid;
92 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST
);
95 if (!groups_is_member($groupid, $userid)) {
99 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
102 $DB->set_field('groups', 'timemodified', time(), array('id'=>$groupid));
104 //trigger groups events
105 $eventdata = new stdClass();
106 $eventdata->groupid
= $groupid;
107 $eventdata->userid
= $userid;
108 events_trigger('groups_member_removed', $eventdata);
115 * @param object $data group properties
116 * @param object $um upload manager with group picture
117 * @return id of group or false if error
119 function groups_create_group($data, $editform = false, $editoroptions = false) {
122 //check that courseid exists
123 $course = $DB->get_record('course', array('id' => $data->courseid
), '*', MUST_EXIST
);
124 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
126 $data->timecreated
= time();
127 $data->timemodified
= $data->timecreated
;
128 $data->name
= trim($data->name
);
130 if ($editform and $editoroptions) {
131 $data->description
= $data->description_editor
['text'];
132 $data->descriptionformat
= $data->description_editor
['format'];
135 $data->id
= $DB->insert_record('groups', $data);
137 if ($editform and $editoroptions) {
138 // Update description from editor with fixed files
139 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id
);
140 $upd = new stdClass();
141 $upd->id
= $data->id
;
142 $upd->description
= $data->description
;
143 $upd->descriptionformat
= $data->descriptionformat
;
144 $DB->update_record('groups', $upd);
147 $group = $DB->get_record('groups', array('id'=>$data->id
));
150 groups_update_group_icon($group, $data, $editform);
153 //trigger groups events
154 events_trigger('groups_group_created', $group);
161 * @param object $data grouping properties
162 * @return id of grouping or false if error
164 function groups_create_grouping($data, $editoroptions=null) {
167 $data->timecreated
= time();
168 $data->timemodified
= $data->timecreated
;
169 $data->name
= trim($data->name
);
171 if ($editoroptions !== null) {
172 $data->description
= $data->description_editor
['text'];
173 $data->descriptionformat
= $data->description_editor
['format'];
176 $id = $DB->insert_record('groupings', $data);
178 //trigger groups events
181 if ($editoroptions !== null) {
182 $description = new stdClass
;
183 $description->id
= $data->id
;
184 $description->description_editor
= $data->description_editor
;
185 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id
);
186 $DB->update_record('groupings', $description);
189 events_trigger('groups_grouping_created', $data);
195 * Update the group icon from form data
200 function groups_update_group_icon($group, $data, $editform) {
202 require_once("$CFG->libdir/gdlib.php");
204 $fs = get_file_storage();
205 $context = get_context_instance(CONTEXT_COURSE
, $group->courseid
, MUST_EXIST
);
207 //TODO: it would make sense to allow picture deleting too (skodak)
209 if ($iconfile = $editform->save_temp_file('imagefile')) {
210 if (process_new_icon($context, 'group', 'icon', $group->id
, $iconfile)) {
211 $DB->set_field('groups', 'picture', 1, array('id'=>$group->id
));
214 $fs->delete_area_files($context->id
, 'group', 'icon', $group->id
);
215 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id
));
224 * @param object $data group properties (with magic quotes)
225 * @param object $editform
226 * @param array $editoroptions
227 * @return boolean true or exception
229 function groups_update_group($data, $editform = false, $editoroptions = false) {
232 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
234 $data->timemodified
= time();
235 $data->name
= trim($data->name
);
237 if ($editform and $editoroptions) {
238 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id
);
241 $DB->update_record('groups', $data);
243 $group = $DB->get_record('groups', array('id'=>$data->id
));
246 groups_update_group_icon($group, $data, $editform);
249 //trigger groups events
250 events_trigger('groups_group_updated', $group);
258 * @param object $data grouping properties (with magic quotes)
259 * @return boolean true or exception
261 function groups_update_grouping($data, $editoroptions=null) {
263 $data->timemodified
= time();
264 $data->name
= trim($data->name
);
265 if ($editoroptions !== null) {
266 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id
);
268 $DB->update_record('groupings', $data);
269 //trigger groups events
270 events_trigger('groups_grouping_updated', $data);
276 * Delete a group best effort, first removing members and links with courses and groupings.
277 * Removes group avatar too.
278 * @param mixed $grouporid The id of group to delete or full group object
279 * @return boolean True if deletion was successful, false otherwise
281 function groups_delete_group($grouporid) {
283 require_once("$CFG->libdir/gdlib.php");
285 if (is_object($grouporid)) {
286 $groupid = $grouporid->id
;
289 $groupid = $grouporid;
290 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
291 //silently ignore attempts to delete missing already deleted groups ;-)
296 // delete group calendar events
297 $DB->delete_records('event', array('groupid'=>$groupid));
298 //first delete usage in groupings_groups
299 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
301 $DB->delete_records('groups_members', array('groupid'=>$groupid));
303 $DB->delete_records('groups', array('id'=>$groupid));
305 // Delete all files associated with this group
306 $context = get_context_instance(CONTEXT_COURSE
, $group->courseid
);
307 $fs = get_file_storage();
308 $fs->delete_area_files($context->id
, 'group', 'description', $groupid);
309 $fs->delete_area_files($context->id
, 'group', 'icon', $groupid);
311 //trigger groups events
312 events_trigger('groups_group_deleted', $group);
319 * @param int $groupingorid
320 * @return bool success
322 function groups_delete_grouping($groupingorid) {
325 if (is_object($groupingorid)) {
326 $groupingid = $groupingorid->id
;
327 $grouping = $groupingorid;
329 $groupingid = $groupingorid;
330 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
331 //silently ignore attempts to delete missing already deleted groupings ;-)
336 //first delete usage in groupings_groups
337 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
338 // remove the default groupingid from course
339 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
340 // remove the groupingid from all course modules
341 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
343 $DB->delete_records('groupings', array('id'=>$groupingid));
345 $context = get_context_instance(CONTEXT_COURSE
, $grouping->courseid
);
346 $fs = get_file_storage();
347 $files = $fs->get_area_files($context->id
, 'grouping', 'description', $groupingid);
348 foreach ($files as $file) {
352 //trigger groups events
353 events_trigger('groups_grouping_deleted', $grouping);
359 * Remove all users (or one user) from all groups in course
360 * @param int $courseid
361 * @param int $userid 0 means all users
362 * @param bool $showfeedback
363 * @return bool success
365 function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
368 if (is_bool($userid)) {
369 debugging('Incorrect userid function parameter');
373 $params = array('courseid'=>$courseid);
376 $usersql = "AND userid = :userid";
377 $params['userid'] = $userid;
382 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = :courseid";
383 $DB->delete_records_select('groups_members', "groupid IN ($groupssql) $usersql", $params);
385 //trigger groups events
386 $eventdata = new stdClass();
387 $eventdata->courseid
= $courseid;
388 $eventdata->userid
= $userid;
389 events_trigger('groups_members_removed', $eventdata);
392 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
399 * Remove all groups from all groupings in course
400 * @param int $courseid
401 * @param bool $showfeedback
402 * @return bool success
404 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
407 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
408 $DB->delete_records_select('groupings_groups', "groupid IN ($groupssql)", array($courseid));
410 //trigger groups events
411 events_trigger('groups_groupings_groups_removed', $courseid);
413 // no need to show any feedback here - we delete usually first groupings and then groups
419 * Delete all groups from course
420 * @param int $courseid
421 * @param bool $showfeedback
422 * @return bool success
424 function groups_delete_groups($courseid, $showfeedback=false) {
425 global $CFG, $DB, $OUTPUT;
427 // delete any uses of groups
428 // Any associated files are deleted as part of groups_delete_groupings_groups
429 groups_delete_groupings_groups($courseid, $showfeedback);
430 groups_delete_group_members($courseid, 0, $showfeedback);
432 // delete group pictures and descriptions
433 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
434 $fs = get_file_storage();
435 $fs->delete_area_files($context->id
, 'group');
437 // delete group calendar events
438 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
439 $DB->delete_records_select('event', "groupid IN ($groupssql)", array($courseid));
441 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
442 $fs = get_file_storage();
443 $fs->delete_area_files($context->id
, 'group');
445 $DB->delete_records('groups', array('courseid'=>$courseid));
447 // trigger groups events
448 events_trigger('groups_groups_deleted', $courseid);
451 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
458 * Delete all groupings from course
459 * @param int $courseid
460 * @param bool $showfeedback
461 * @return bool success
463 function groups_delete_groupings($courseid, $showfeedback=false) {
466 // delete any uses of groupings
467 $sql = "DELETE FROM {groupings_groups}
468 WHERE groupingid in (SELECT id FROM {groupings} g WHERE g.courseid = ?)";
469 $DB->execute($sql, array($courseid));
471 // remove the default groupingid from course
472 $DB->set_field('course', 'defaultgroupingid', 0, array('id'=>$courseid));
473 // remove the groupingid from all course modules
474 $DB->set_field('course_modules', 'groupingid', 0, array('course'=>$courseid));
476 // Delete all files associated with groupings for this course
477 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
478 $fs = get_file_storage();
479 $fs->delete_area_files($context->id
, 'grouping');
481 $DB->delete_records('groupings', array('courseid'=>$courseid));
483 // trigger groups events
484 events_trigger('groups_groupings_deleted', $courseid);
487 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
493 /* =================================== */
494 /* various functions used by groups UI */
495 /* =================================== */
498 * Obtains a list of the possible roles that group members might come from,
499 * on a course. Generally this includes only profile roles.
500 * @param object $context Context of course
501 * @return Array of role ID integers, or false if error/none.
503 function groups_get_possible_roles($context) {
504 $roles = get_profile_roles($context);
505 return array_keys($roles);
510 * Gets potential group members for grouping
511 * @param int $courseid The id of the course
512 * @param int $roleid The role to select users from
513 * @param int $cohortid restrict to cohort id
514 * @param string $orderby The column to sort users by
515 * @return array An array of the users
517 function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
520 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
522 // we are looking for all users with this role assigned in this context or higher
523 $listofcontexts = get_related_contexts_string($context);
525 list($esql, $params) = get_enrolled_sql($context);
528 $params['roleid'] = $roleid;
529 $where = "WHERE u.id IN (SELECT userid
530 FROM {role_assignments}
531 WHERE roleid = :roleid AND contextid $listofcontexts)";
537 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
538 $params['cohortid'] = $cohortid;
543 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
545 JOIN ($esql) e ON e.id = u.id
550 return $DB->get_records_sql($sql, $params);
555 * Parse a group name for characters to replace
556 * @param string $format The format a group name will follow
557 * @param int $groupnumber The number of the group to be used in the parsed format string
558 * @return string the parsed format string
560 function groups_parse_name($format, $groupnumber) {
561 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
563 for($i=0; $i<$groupnumber; $i++
) {
566 $str = str_replace('@', $letter, $format);
568 $str = str_replace('#', $groupnumber+
1, $format);
574 * Assigns group into grouping
575 * @param int groupingid
577 * @return bool true or exception
579 function groups_assign_grouping($groupingid, $groupid) {
582 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
585 $assign = new stdClass();
586 $assign->groupingid
= $groupingid;
587 $assign->groupid
= $groupid;
588 $assign->timeadded
= time();
589 $DB->insert_record('groupings_groups', $assign);
595 * Unassigns group grom grouping
596 * @param int groupingid
598 * @return bool success
600 function groups_unassign_grouping($groupingid, $groupid) {
602 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
608 * Lists users in a group based on their role on the course.
609 * Returns false if there's an error or there are no users in the group.
610 * Otherwise returns an array of role ID => role data, where role data includes:
611 * (role) $id, $shortname, $name
612 * $users: array of objects for each user which include the specified fields
613 * Users who do not have a role are stored in the returned array with key '-'
614 * and pseudo-role details (including a name, 'No role'). Users with multiple
615 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
616 * which roles each has by looking in the $roles array of the user object.
617 * @param int $groupid
618 * @param int $courseid Course ID (should match the group's course)
619 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
620 * @param string $sort SQL ORDER BY clause, default 'u.lastname ASC'
621 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
622 * @param array $whereparams any parameters required by $extrawheretest (named parameters).
623 * @return array Complex array as described above
625 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
626 $sort='u.lastname ASC', $extrawheretest='', $whereparams=array()) {
629 // Retrieve information about all users and their roles on the course or
630 // parent ('related') contexts
631 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
633 if ($extrawheretest) {
634 $extrawheretest = ' AND ' . $extrawheretest;
637 $sql = "SELECT r.id AS roleid, r.shortname AS roleshortname, r.name AS rolename,
638 u.id AS userid, $fields
639 FROM {groups_members} gm
640 JOIN {user} u ON u.id = gm.userid
641 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid ".get_related_contexts_string($context).")
642 LEFT JOIN {role} r ON r.id = ra.roleid
643 WHERE gm.groupid=:mgroupid
645 ORDER BY r.sortorder, $sort";
646 $whereparams['mgroupid'] = $groupid;
647 $rs = $DB->get_recordset_sql($sql, $whereparams);
649 return groups_calculate_role_people($rs, $context);
653 * Internal function used by groups_get_members_by_role to handle the
654 * results of a database query that includes a list of users and possible
657 * @param object $rs The record set (may be false)
658 * @param int $contextid ID of course context
659 * @return array As described in groups_get_members_by_role
661 function groups_calculate_role_people($rs, $context) {
668 $roles = $DB->get_records_menu('role', null, 'name', 'id, name');
669 $aliasnames = role_fix_names($roles, $context);
671 // Array of all involved roles
673 // Array of all retrieved users
676 foreach ($rs as $rec) {
677 // Create information about user if this is a new one
678 if (!array_key_exists($rec->userid
, $users)) {
679 // User data includes all the optional fields, but not any of the
680 // stuff we added to get the role details
681 $userdata = clone($rec);
682 unset($userdata->roleid
);
683 unset($userdata->roleshortname
);
684 unset($userdata->rolename
);
685 unset($userdata->userid
);
686 $userdata->id
= $rec->userid
;
688 // Make an array to hold the list of roles for this user
689 $userdata->roles
= array();
690 $users[$rec->userid
] = $userdata;
692 // If user has a role...
693 if (!is_null($rec->roleid
)) {
694 // Create information about role if this is a new one
695 if (!array_key_exists($rec->roleid
,$roles)) {
696 $roledata = new stdClass();
697 $roledata->id
= $rec->roleid
;
698 $roledata->shortname
= $rec->roleshortname
;
699 if (array_key_exists($rec->roleid
, $aliasnames)) {
700 $roledata->name
= $aliasnames[$rec->roleid
];
702 $roledata->name
= $rec->rolename
;
704 $roledata->users
= array();
705 $roles[$roledata->id
] = $roledata;
707 // Record that user has role
708 $users[$rec->userid
]->roles
[] = $roles[$rec->roleid
];
713 // Return false if there weren't any users
714 if (count($users) == 0) {
718 // Add pseudo-role for multiple roles
719 $roledata = new stdClass();
720 $roledata->name
= get_string('multipleroles','role');
721 $roledata->users
= array();
722 $roles['*'] = $roledata;
724 $roledata = new stdClass();
725 $roledata->name
= get_string('noroles','role');
726 $roledata->users
= array();
727 $roles[0] = $roledata;
729 // Now we rearrange the data to store users by role
730 foreach ($users as $userid=>$userdata) {
731 $rolecount = count($userdata->roles
);
732 if ($rolecount == 0) {
733 // does not have any roles
735 } else if($rolecount > 1) {
738 $roleid = $userdata->roles
[0]->id
;
740 $roles[$roleid]->users
[$userid] = $userdata;
743 // Delete roles not used
744 foreach ($roles as $key=>$roledata) {
745 if (count($roledata->users
)===0) {
750 // Return list of roles containing their users