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 int $userid The user id
19 * @param int $groupid The group id
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($groupid, $userid) {
24 if (!groups_group_exists($groupid)) {
28 if (groups_is_member($groupid, $userid)) {
32 $member = new object();
33 $member->groupid
= $groupid;
34 $member->userid
= $userid;
35 $member->timeadded
= time();
37 if (!insert_record('groups_members', $member)) {
42 set_field('groups', 'timemodified', $member->timeadded
, 'id', $groupid);
44 //trigger groups events
45 $eventdata = new object();
46 $eventdata->groupid
= $groupid;
47 $eventdata->userid
= $userid;
48 events_trigger('groups_member_added', $eventdata);
54 * Deletes the link between the specified user and group.
55 * @param int $groupid The group to delete the user from
56 * @param int $userid The user to delete
57 * @return boolean True if deletion was successful, false otherwise
59 function groups_remove_member($groupid, $userid) {
60 if (!groups_group_exists($groupid)) {
64 if (!groups_is_member($groupid, $userid)) {
68 if (!delete_records('groups_members', 'groupid', $groupid, 'userid', $userid)) {
72 set_field('groups', 'timemodified', time(), 'id', $groupid);
74 //trigger groups events
75 $eventdata = new object();
76 $eventdata->groupid
= $groupid;
77 $eventdata->userid
= $userid;
78 events_trigger('groups_member_removed', $eventdata);
85 * @param object $data group properties (with magic quotes)
86 * @param object $um upload manager with group picture
87 * @return id of group or false if error
89 function groups_create_group($data, $um=false) {
91 require_once("$CFG->libdir/gdlib.php");
93 $data->timecreated
= time();
94 $data->timemodified
= $data->timecreated
;
95 $data->name
= trim($data->name
);
96 $id = insert_record('groups', $data);
102 if (save_profile_image($id, $um, 'groups')) {
103 set_field('groups', 'picture', 1, 'id', $id);
108 //trigger groups events
109 events_trigger('groups_group_created', stripslashes_recursive($data));
117 * @param object $data grouping properties (with magic quotes)
118 * @return id of grouping or false if error
120 function groups_create_grouping($data) {
123 $data->timecreated
= time();
124 $data->timemodified
= $data->timecreated
;
125 $data->name
= trim($data->name
);
127 $id = insert_record('groupings', $data);
130 //trigger groups events
132 events_trigger('groups_grouping_created', stripslashes_recursive($data));
140 * @param object $data group properties (with magic quotes)
141 * @param object $um upload manager with group picture
142 * @return boolean success
144 function groups_update_group($data, $um=false) {
146 require_once("$CFG->libdir/gdlib.php");
148 $data->timemodified
= time();
149 $data->name
= trim($data->name
);
150 $result = update_record('groups', $data);
155 if (save_profile_image($data->id
, $um, 'groups')) {
156 set_field('groups', 'picture', 1, 'id', $data->id
);
161 //trigger groups events
162 events_trigger('groups_group_updated', stripslashes_recursive($data));
170 * @param object $data grouping properties (with magic quotes)
171 * @return boolean success
173 function groups_update_grouping($data) {
175 $data->timemodified
= time();
176 $data->name
= trim($data->name
);
177 $result = update_record('groupings', $data);
179 //trigger groups events
180 events_trigger('groups_grouping_updated', stripslashes_recursive($data));
186 * Delete a group best effort, first removing members and links with courses and groupings.
187 * Removes group avatar too.
188 * @param mixed $grouporid The id of group to delete or full group object
189 * @return boolean True if deletion was successful, false otherwise
191 function groups_delete_group($grouporid) {
193 require_once($CFG->libdir
.'/gdlib.php');
195 if (is_object($grouporid)) {
196 $groupid = $grouporid->id
;
199 $groupid = $grouporid;
200 if (!$group = get_record('groups', 'id', $groupid)) {
205 // delete group calendar events
206 delete_records('event', 'groupid', $groupid);
207 //first delete usage in groupings_groups
208 delete_records('groupings_groups', 'groupid', $groupid);
210 delete_records('groups_members', 'groupid', $groupid);
212 delete_profile_image($groupid, 'groups');
214 $result = delete_records('groups', 'id', $groupid);
217 //trigger groups events
218 events_trigger('groups_group_deleted', $group);
226 * @param int $groupingid
227 * @return bool success
229 function groups_delete_grouping($groupingorid) {
230 if (is_object($groupingorid)) {
231 $groupingid = $groupingorid->id
;
232 $grouping = $groupingorid;
234 $groupingid = $groupingorid;
235 if (!$grouping = get_record('groupings', 'id', $groupingorid)) {
240 //first delete usage in groupings_groups
241 delete_records('groupings_groups', 'groupingid', $groupingid);
242 // remove the default groupingid from course
243 set_field('course', 'defaultgroupingid', 0, 'defaultgroupingid', $groupingid);
244 // remove the groupingid from all course modules
245 set_field('course_modules', 'groupingid', 0, 'groupingid', $groupingid);
247 $result = delete_records('groupings', 'id', $groupingid);
250 //trigger groups events
251 events_trigger('groups_grouping_deleted', $grouping);
258 * Remove all users (or one user) from all groups in course
259 * @param int $courseid
260 * @param int $userid 0 means all users
261 * @param bool $showfeedback
262 * @return bool success
264 function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
267 if (is_bool($userid)) {
268 debugging('Incorrect userid function parameter');
273 $usersql = "AND userid = $userid";
278 $groupssql = "SELECT id FROM {$CFG->prefix}groups g WHERE g.courseid = $courseid";
279 delete_records_select('groups_members', "groupid IN ($groupssql) $usersql");
281 //trigger groups events
282 $eventdata = new object();
283 $eventdata->courseid
= $courseid;
284 $eventdata->userid
= $userid;
285 events_trigger('groups_members_removed', $eventdata);
288 notify(get_string('deleted').' groups_members');
295 * Remove all groups from all groupings in course
296 * @param int $courseid
297 * @param bool $showfeedback
298 * @return bool success
300 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
303 $groupssql = "SELECT id FROM {$CFG->prefix}groups g WHERE g.courseid = $courseid";
304 delete_records_select('groupings_groups', "groupid IN ($groupssql)");
306 //trigger groups events
307 events_trigger('groups_groupings_groups_removed', $courseid);
310 notify(get_string('deleted').' groupings_groups');
317 * Delete all groups from course
318 * @param int $courseid
319 * @param bool $showfeedback
320 * @return bool success
322 function groups_delete_groups($courseid, $showfeedback=false) {
324 require_once($CFG->libdir
.'/gdlib.php');
326 $groupssql = "SELECT id FROM {$CFG->prefix}groups g WHERE g.courseid = $courseid";
328 // delete any uses of groups
329 groups_delete_groupings_groups($courseid, $showfeedback);
330 groups_delete_group_members($courseid, 0, $showfeedback);
332 // delete group pictures
333 if ($groups = get_records('groups', 'courseid', $courseid)) {
334 foreach($groups as $group) {
335 delete_profile_image($group->id
, 'groups');
339 // delete group calendar events
340 delete_records_select('event', "groupid IN ($groupssql)");
342 delete_records('groups', 'courseid', $courseid);
344 //trigger groups events
345 events_trigger('groups_groups_deleted', $courseid);
348 notify(get_string('deleted').' groups');
355 * Delete all groupings from course
356 * @param int $courseid
357 * @param bool $showfeedback
358 * @return bool success
360 function groups_delete_groupings($courseid, $showfeedback=false) {
363 // delete any uses of groupings
364 $sql = "DELETE FROM {$CFG->prefix}groupings_groups
365 WHERE groupingid in (SELECT id FROM {$CFG->prefix}groupings g WHERE g.courseid = $courseid)";
366 execute_sql($sql, false);
368 // remove the default groupingid from course
369 set_field('course', 'defaultgroupingid', 0, 'id', $courseid);
370 // remove the groupingid from all course modules
371 set_field('course_modules', 'groupingid', 0, 'course', $courseid);
373 delete_records('groupings', 'courseid', $courseid);
375 //trigger groups events
376 events_trigger('groups_groupings_deleted', $courseid);
379 notify(get_string('deleted').' groupings');
385 /* =================================== */
386 /* various functions used by groups UI */
387 /* =================================== */
390 * Gets the users for a course who are not in a specified group, and returns
391 * them in an array organised by role. For the array format, see
392 * groups_get_members_by_role.
393 * @param int $groupid The id of the group
394 * @param string searchtext similar to searchtext in role assign, search
395 * @return array An array of role id or '*' => information about that role
396 * including a list of users
398 function groups_get_users_not_in_group_by_role($courseid, $groupid, $searchtext='', $sort = 'u.lastname ASC') {
401 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
403 if ($searchtext !== '') { // Search for a subset of remaining users
405 $FULLNAME = sql_fullname();
406 $wheresearch = " AND u.id IN (SELECT id FROM {$CFG->prefix}user WHERE $FULLNAME $LIKE '%$searchtext%' OR email $LIKE '%$searchtext%' )";
411 /// Get list of allowed roles
412 if(!($validroleids=groups_get_possible_roles($context))) {
415 $roleids = '('.implode(',', $validroleids).')';
417 /// Construct the main SQL
418 $select = " SELECT r.id AS roleid,r.shortname AS roleshortname,r.name AS rolename,
419 u.id AS userid, u.firstname, u.lastname";
420 $from = " FROM {$CFG->prefix}user u
421 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
422 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid";
424 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
426 AND ra.roleid in $roleids
427 AND u.id NOT IN (SELECT userid
428 FROM {$CFG->prefix}groups_members
429 WHERE groupid = $groupid)
431 $orderby = " ORDER BY $sort";
433 return groups_calculate_role_people(get_recordset_sql(
434 $select.$from.$where.$orderby),$context);
439 * Obtains a list of the possible roles that group members might come from,
440 * on a course. Generally this includes all the roles who would have
441 * course:view on that course, except the doanything roles.
442 * @param object $context Context of course
443 * @return Array of role ID integers, or false if error/none.
445 function groups_get_possible_roles($context) {
446 $capability = 'moodle/course:view';
449 // find all possible "student" roles
450 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW
, $context)) {
452 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
453 return false; // Something is seriously wrong
455 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
458 $validroleids = array();
459 foreach ($possibleroles as $possiblerole) {
461 if (isset($doanythingroles[$possiblerole->id
])) { // We don't want these included
465 if ($caps = role_context_capabilities($possiblerole->id
, $context, $capability)) { // resolved list
466 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
467 $validroleids[] = $possiblerole->id
;
471 if (empty($validroleids)) {
474 return $validroleids;
476 return false; // No need to continue, since no roles have this capability set
482 * Gets potential group members for grouping
483 * @param int $courseid The id of the course
484 * @param int $roleid The role to select users from
485 * @param string $orderby The colum to sort users by
486 * @return array An array of the users
488 function groups_get_potential_members($courseid, $roleid = null, $orderby = 'lastname,firstname') {
491 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
492 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
493 $rolenames = array();
494 $avoidroles = array();
496 if ($roles = get_roles_used_in_context($context, true)) {
498 $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW
, $context);
499 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
501 foreach ($roles as $role) {
502 if (!isset($canviewroles[$role->id
])) { // Avoid this role (eg course creator)
503 $avoidroles[] = $role->id
;
504 unset($roles[$role->id
]);
507 if (isset($doanythingroles[$role->id
])) { // Avoid this role (ie admin)
508 $avoidroles[] = $role->id
;
509 unset($roles[$role->id
]);
512 $rolenames[$role->id
] = strip_tags(role_get_name($role, $context)); // Used in menus etc later on
516 $select = 'SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber ';
517 $from = "FROM {$CFG->prefix}user u INNER JOIN
518 {$CFG->prefix}role_assignments r on u.id=r.userid ";
521 $adminroles = 'AND r.roleid NOT IN (';
522 $adminroles .= implode(',', $avoidroles);
528 // we are looking for all users with this role assigned in this context or higher
529 if ($usercontexts = get_parent_contexts($context)) {
530 $listofcontexts = '('.implode(',', $usercontexts).')';
532 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
536 $selectrole = " AND r.roleid = $roleid ";
541 $where = "WHERE (r.contextid = $context->id OR r.contextid in $listofcontexts)
542 AND u.deleted = 0 $selectrole
543 AND u.username != 'guest'
545 $order = "ORDER BY $orderby ";
547 return(get_records_sql($select.$from.$where.$order));
552 * Parse a group name for characters to replace
553 * @param string $format The format a group name will follow
554 * @param int $groupnumber The number of the group to be used in the parsed format string
555 * @return string the parsed format string
557 function groups_parse_name($format, $groupnumber) {
558 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
560 for($i=0; $i<$groupnumber; $i++
) {
563 $str = str_replace('@', $letter, $format);
565 $str = str_replace('#', $groupnumber+
1, $format);
571 * Assigns group into grouping
572 * @param int groupingid
574 * @return bool success
576 function groups_assign_grouping($groupingid, $groupid) {
577 if (record_exists('groupings_groups', 'groupingid', $groupingid, 'groupid', $groupid)) {
580 $assign = new object();
581 $assign->groupingid
= $groupingid;
582 $assign->groupid
= $groupid;
583 $assign->timeadded
= time();
584 return (bool)insert_record('groupings_groups', $assign);
588 * Unassigns group grom grouping
589 * @param int groupingid
591 * @return bool success
593 function groups_unassign_grouping($groupingid, $groupid) {
594 return delete_records('groupings_groups', 'groupingid', $groupingid, 'groupid', $groupid);
598 * Lists users in a group based on their role on the course.
599 * Returns false if there's an error or there are no users in the group.
600 * Otherwise returns an array of role ID => role data, where role data includes:
601 * (role) $id, $shortname, $name
602 * $users: array of objects for each user which include the specified fields
603 * Users who do not have a role are stored in the returned array with key '-'
604 * and pseudo-role details (including a name, 'No role'). Users with multiple
605 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
606 * which roles each has by looking in the $roles array of the user object.
607 * @param int $groupid
608 * @param int $courseid Course ID (should match the group's course)
609 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
610 * @param string $sort SQL ORDER BY clause, default 'u.lastname ASC'
611 * @return array Complex array as described above
613 function groups_get_members_by_role($groupid, $courseid, $fields='u.*', $sort='u.lastname ASC') {
616 // Retrieve information about all users and their roles on the course or
617 // parent ('related') contexts
618 $context=get_context_instance(CONTEXT_COURSE
,$courseid);
619 $rs=get_recordset_sql($crap="SELECT r.id AS roleid,r.shortname AS roleshortname,r.name AS rolename,
620 u.id AS userid,$fields
621 FROM {$CFG->prefix}groups_members gm
622 INNER JOIN {$CFG->prefix}user u ON u.id = gm.userid
623 INNER JOIN {$CFG->prefix}role_assignments ra
625 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
626 WHERE gm.groupid='$groupid'
627 AND ra.contextid ".get_related_contexts_string($context)."
628 ORDER BY r.sortorder,$sort");
630 return groups_calculate_role_people($rs,$context);
634 * Internal function used by groups_get_members_by_role to handle the
635 * results of a database query that includes a list of users and possible
638 * @param object $rs The record set (may be false)
639 * @param object $context of course
640 * @return array As described in groups_get_members_by_role
642 function groups_calculate_role_people($rs,$context) {
648 $roles = get_records_menu('role', null, 'name', 'id, name');
649 $aliasnames = role_fix_names($roles, $context);
651 // Array of all involved roles
653 // Array of all retrieved users
656 while($rec=rs_fetch_next_record($rs)) {
657 // Create information about user if this is a new one
658 if(!array_key_exists($rec->userid
,$users)) {
659 // User data includes all the optional fields, but not any of the
660 // stuff we added to get the role details
661 $userdata=clone($rec);
662 unset($userdata->roleid
);
663 unset($userdata->roleshortname
);
664 unset($userdata->rolename
);
665 unset($userdata->userid
);
666 $userdata->id
=$rec->userid
;
668 // Make an array to hold the list of roles for this user
669 $userdata->roles
=array();
670 $users[$rec->userid
]=$userdata;
672 // If user has a role...
673 if(!is_null($rec->roleid
)) {
674 // Create information about role if this is a new one
675 if(!array_key_exists($rec->roleid
,$roles)) {
676 $roledata=new StdClass
;
677 $roledata->id
=$rec->roleid
;
678 $roledata->shortname
=$rec->roleshortname
;
679 if(array_key_exists($rec->roleid
,$aliasnames)) {
680 $roledata->name
=$aliasnames[$rec->roleid
];
682 $roledata->name
=$rec->rolename
;
684 $roledata->users
=array();
685 $roles[$roledata->id
]=$roledata;
687 // Record that user has role
688 $users[$rec->userid
]->roles
[] = $roles[$rec->roleid
];
693 // Return false if there weren't any users
694 if(count($users)==0) {
698 // Add pseudo-role for multiple roles
699 $roledata=new StdClass
;
700 $roledata->name
=get_string('multipleroles','role');
701 $roledata->users
=array();
702 $roles['*']=$roledata;
704 // Now we rearrange the data to store users by role
705 foreach($users as $userid=>$userdata) {
706 $rolecount=count($userdata->roles
);
708 debugging("Unexpected: user $userid is missing roles");
709 } else if($rolecount>1) {
712 $roleid=$userdata->roles
[0]->id
;
714 $roles[$roleid]->users
[$userid]=$userdata;
717 // Delete roles not used
718 foreach($roles as $key=>$roledata) {
719 if(count($roledata->users
)===0) {
724 // Return list of roles containing their users