3 * Extra library for groups and groupings.
5 * @copyright © 2006 The Open University
6 * @author J.White AT open.ac.uk
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);
45 $eventdata = new object();
46 $eventdata->groupid
= $groupid;
47 $eventdata->userid
= $userid;
48 events_trigger('group_user_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);
79 * @param object $data group properties (with magic quotes)
80 * @param object $um upload manager with group picture
81 * @return id of group or false if error
83 function groups_create_group($data, $um=false) {
85 require_once("$CFG->libdir/gdlib.php");
87 $data->timecreated
= time();
88 $data->timemodified
= $data->timecreated
;
89 $data->name
= trim($data->name
);
90 $id = insert_record('groups', $data);
94 if (save_profile_image($id, $um, 'groups')) {
95 set_field('groups', 'picture', 1, 'id', $id);
104 * @param object $data grouping properties (with magic quotes)
105 * @return id of grouping or false if error
107 function groups_create_grouping($data) {
110 $data->timecreated
= time();
111 $data->timemodified
= $data->timecreated
;
112 $data->name
= trim($data->name
);
113 return insert_record('groupings', $data);
118 * @param object $data group properties (with magic quotes)
119 * @param object $um upload manager with group picture
120 * @return boolean success
122 function groups_update_group($data, $um=false) {
124 require_once("$CFG->libdir/gdlib.php");
126 $data->timemodified
= time();
127 $data->name
= trim($data->name
);
128 $result = update_record('groups', $data);
130 if ($result and $um) {
132 if (save_profile_image($data->id
, $um, 'groups')) {
133 set_field('groups', 'picture', 1, 'id', $data->id
);
142 * @param object $data grouping properties (with magic quotes)
143 * @return boolean success
145 function groups_update_grouping($data) {
147 $data->timemodified
= time();
148 $data->name
= trim($data->name
);
149 return update_record('groupings', $data);
153 * Delete a group best effort, first removing members and links with courses and groupings.
154 * Removes group avatar too.
155 * @param int $groupid The group to delete
156 * @return boolean True if deletion was successful, false otherwise
158 function groups_delete_group($groupid) {
160 require_once($CFG->libdir
.'/gdlib.php');
162 if (empty($groupid)) {
166 // delete group calendar events
167 delete_records('event', 'groupid', $groupid);
168 //first delete usage in groupings_groups
169 delete_records('groupings_groups', 'groupid', $groupid);
171 delete_records('groups_members', 'groupid', $groupid);
173 delete_profile_image($groupid, 'groups');
175 return delete_records('groups', 'id', $groupid);
180 * @param int $groupingid
181 * @return bool success
183 function groups_delete_grouping($groupingid) {
184 if (empty($groupingid)) {
189 //first delete usage in groupings_groups
190 delete_records('groupings_groups', 'groupingid', $groupingid);
191 // remove the default groupingid from course
192 set_field('course', 'defaultgroupingid', 0, 'defaultgroupingid', $groupingid);
193 // remove the groupingid from all course modules
194 set_field('course_modules', 'groupingid', 0, 'groupingid', $groupingid);
196 return delete_records('groupings', 'id', $groupingid);
200 * Remove all users from all groups in course
201 * @param int $courseid
202 * @param bool $showfeedback
203 * @return bool success
205 function groups_delete_group_members($courseid, $showfeedback=false) {
208 $groupssql = "SELECT id FROM {$CFG->prefix}groups g WHERE g.courseid = $courseid";
209 delete_records_select('groups_members', "groupid IN ($groupssql)");
212 notify(get_string('deleted').' groups_members');
219 * Remove all groups from all groupings in course
220 * @param int $courseid
221 * @param bool $showfeedback
222 * @return bool success
224 function groups_delete_groupings_groups($courseid, $showfeedback=false) {
227 $groupssql = "SELECT id FROM {$CFG->prefix}groups g WHERE g.courseid = $courseid";
228 delete_records_select('groupings_groups', "groupid IN ($groupssql)");
231 notify(get_string('deleted').' groupings_groups');
238 * Delete all groups from course
239 * @param int $courseid
240 * @param bool $showfeedback
241 * @return bool success
243 function groups_delete_groups($courseid, $showfeedback=false) {
245 require_once($CFG->libdir
.'/gdlib.php');
247 $groupssql = "SELECT id FROM {$CFG->prefix}groups g WHERE g.courseid = $courseid";
249 // delete any uses of groups
250 groups_delete_groupings_groups($courseid, $showfeedback);
251 groups_delete_group_members($courseid, $showfeedback);
253 // delete group pictures
254 if ($groups = get_records('groups', 'courseid', $courseid)) {
255 foreach($groups as $group) {
256 delete_profile_image($group->id
, 'groups');
260 // delete group calendar events
261 delete_records_select('event', "groupid IN ($groupssql)");
263 delete_records('groups', 'courseid', $courseid);
265 notify(get_string('deleted').' groups');
272 * Delete all groupings from course
273 * @param int $courseid
274 * @param bool $showfeedback
275 * @return bool success
277 function groups_delete_groupings($courseid, $showfeedback=false) {
280 // delete any uses of groupings
281 $sql = "DELETE FROM {$CFG->prefix}groupings_groups
282 WHERE groupingid in (SELECT id FROM {$CFG->prefix}groupings g WHERE g.courseid = $courseid)";
283 execute_sql($sql, false);
285 // remove the default groupingid from course
286 set_field('course', 'defaultgroupingid', 0, 'id', $courseid);
287 // remove the groupingid from all course modules
288 set_field('course_modules', 'groupingid', 0, 'course', $courseid);
290 delete_records('groupings', 'courseid', $courseid);
292 notify(get_string('deleted').' groupings');
298 /* =================================== */
299 /* various functions used by groups UI */
300 /* =================================== */
303 * Gets the users for a course who are not in a specified group, and returns
304 * them in an array organised by role. For the array format, see
305 * groups_get_members_by_role.
306 * @param int $groupid The id of the group
307 * @param string searchtext similar to searchtext in role assign, search
308 * @return array An array of role id or '*' => information about that role
309 * including a list of users
311 function groups_get_users_not_in_group_by_role($courseid, $groupid, $searchtext='', $sort = 'u.lastname ASC') {
314 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
316 if ($searchtext !== '') { // Search for a subset of remaining users
318 $FULLNAME = sql_fullname();
319 $wheresearch = " AND u.id IN (SELECT id FROM {$CFG->prefix}user WHERE $FULLNAME $LIKE '%$searchtext%' OR email $LIKE '%$searchtext%' )";
324 /// Get list of allowed roles
325 if(!($validroleids=groups_get_possible_roles($context))) {
328 $roleids = '('.implode(',', $validroleids).')';
330 /// Construct the main SQL
331 $select = " SELECT r.id AS roleid,r.shortname AS roleshortname,r.name AS rolename,
332 u.id AS userid, u.firstname, u.lastname";
333 $from = " FROM {$CFG->prefix}user u
334 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
335 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid";
337 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
339 AND ra.roleid in $roleids
340 AND u.id NOT IN (SELECT userid
341 FROM {$CFG->prefix}groups_members
342 WHERE groupid = $groupid)
344 $orderby = " ORDER BY $sort";
346 return groups_calculate_role_people(get_recordset_sql(
347 $select.$from.$where.$orderby),$context->id
);
352 * Obtains a list of the possible roles that group members might come from,
353 * on a course. Generally this includes all the roles who would have
354 * course:view on that course, except the doanything roles.
355 * @param object $context Context of course
356 * @return Array of role ID integers, or false if error/none.
358 function groups_get_possible_roles($context) {
359 $capability = 'moodle/course:view';
362 // find all possible "student" roles
363 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW
, $context)) {
365 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM
)) {
366 return false; // Something is seriously wrong
368 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
371 $validroleids = array();
372 foreach ($possibleroles as $possiblerole) {
374 if (isset($doanythingroles[$possiblerole->id
])) { // We don't want these included
378 if ($caps = role_context_capabilities($possiblerole->id
, $context, $capability)) { // resolved list
379 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
380 $validroleids[] = $possiblerole->id
;
384 if (empty($validroleids)) {
387 return $validroleids;
389 return false; // No need to continue, since no roles have this capability set
395 * Gets potential group members for grouping
396 * @param int $courseid The id of the course
397 * @param int $roleid The role to select users from
398 * @param string $orderby The colum to sort users by
399 * @return array An array of the users
401 function groups_get_potential_members($courseid, $roleid = null, $orderby = 'lastname,firstname') {
404 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
405 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
406 $rolenames = array();
407 $avoidroles = array();
409 if ($roles = get_roles_used_in_context($context, true)) {
411 $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW
, $context);
412 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
414 foreach ($roles as $role) {
415 if (!isset($canviewroles[$role->id
])) { // Avoid this role (eg course creator)
416 $avoidroles[] = $role->id
;
417 unset($roles[$role->id
]);
420 if (isset($doanythingroles[$role->id
])) { // Avoid this role (ie admin)
421 $avoidroles[] = $role->id
;
422 unset($roles[$role->id
]);
425 $rolenames[$role->id
] = strip_tags(role_get_name($role, $context)); // Used in menus etc later on
429 $select = 'SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber ';
430 $from = "FROM {$CFG->prefix}user u INNER JOIN
431 {$CFG->prefix}role_assignments r on u.id=r.userid ";
434 $adminroles = 'AND r.roleid NOT IN (';
435 $adminroles .= implode(',', $avoidroles);
441 // we are looking for all users with this role assigned in this context or higher
442 if ($usercontexts = get_parent_contexts($context)) {
443 $listofcontexts = '('.implode(',', $usercontexts).')';
445 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
449 $selectrole = " AND r.roleid = $roleid ";
454 $where = "WHERE (r.contextid = $context->id OR r.contextid in $listofcontexts)
455 AND u.deleted = 0 $selectrole
456 AND u.username != 'guest'
458 $order = "ORDER BY $orderby ";
460 return(get_records_sql($select.$from.$where.$order));
465 * Parse a group name for characters to replace
466 * @param string $format The format a group name will follow
467 * @param int $groupnumber The number of the group to be used in the parsed format string
468 * @return string the parsed format string
470 function groups_parse_name($format, $groupnumber) {
471 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
473 for($i=0; $i<$groupnumber; $i++
) {
476 $str = str_replace('@', $letter, $format);
478 $str = str_replace('#', $groupnumber+
1, $format);
484 * Assigns group into grouping
485 * @param int groupingid
487 * @return bool success
489 function groups_assign_grouping($groupingid, $groupid) {
490 if (record_exists('groupings_groups', 'groupingid', $groupingid, 'groupid', $groupid)) {
493 $assign = new object();
494 $assign->groupingid
= $groupingid;
495 $assign->groupid
= $groupid;
496 $assign->timeadded
= time();
497 return (bool)insert_record('groupings_groups', $assign);
501 * Unassigns group grom grouping
502 * @param int groupingid
504 * @return bool success
506 function groups_unassign_grouping($groupingid, $groupid) {
507 return delete_records('groupings_groups', 'groupingid', $groupingid, 'groupid', $groupid);
511 * Lists users in a group based on their role on the course.
512 * Returns false if there's an error or there are no users in the group.
513 * Otherwise returns an array of role ID => role data, where role data includes:
514 * (role) $id, $shortname, $name
515 * $users: array of objects for each user which include the specified fields
516 * Users who do not have a role are stored in the returned array with key '-'
517 * and pseudo-role details (including a name, 'No role'). Users with multiple
518 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
519 * which roles each has by looking in the $roles array of the user object.
520 * @param int $groupid
521 * @param int $courseid Course ID (should match the group's course)
522 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
523 * @param string $sort SQL ORDER BY clause, default 'u.lastname ASC'
524 * @return array Complex array as described above
526 function groups_get_members_by_role($groupid, $courseid, $fields='u.*', $sort='u.lastname ASC') {
529 // Retrieve information about all users and their roles on the course or
530 // parent ('related') contexts
531 $context=get_context_instance(CONTEXT_COURSE
,$courseid);
532 $rs=get_recordset_sql($crap="SELECT r.id AS roleid,r.shortname AS roleshortname,r.name AS rolename,
533 u.id AS userid,$fields
534 FROM {$CFG->prefix}groups_members gm
535 INNER JOIN {$CFG->prefix}user u ON u.id = gm.userid
536 INNER JOIN {$CFG->prefix}role_assignments ra
538 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
539 WHERE gm.groupid='$groupid'
540 AND ra.contextid ".get_related_contexts_string($context)."
541 ORDER BY r.sortorder,$sort");
543 return groups_calculate_role_people($rs,$context->id
);
547 * Internal function used by groups_get_members_by_role to handle the
548 * results of a database query that includes a list of users and possible
551 * @param object $rs The record set (may be false)
552 * @param int $contextid ID of course context
553 * @return array As described in groups_get_members_by_role
555 function groups_calculate_role_people($rs,$contextid) {
561 // Get role aliases for course in array of roleid => obj->text
562 if(!($aliasnames=get_records('role_names','contextid',$contextid,'','roleid,name'))) {
566 // Array of all involved roles
568 // Array of all retrieved users
571 while($rec=rs_fetch_next_record($rs)) {
572 // Create information about user if this is a new one
573 if(!array_key_exists($rec->userid
,$users)) {
574 // User data includes all the optional fields, but not any of the
575 // stuff we added to get the role details
576 $userdata=clone($rec);
577 unset($userdata->roleid
);
578 unset($userdata->roleshortname
);
579 unset($userdata->rolename
);
580 unset($userdata->userid
);
581 $userdata->id
=$rec->userid
;
583 // Make an array to hold the list of roles for this user
584 $userdata->roles
=array();
585 $users[$rec->userid
]=$userdata;
587 // If user has a role...
588 if(!is_null($rec->roleid
)) {
589 // Create information about role if this is a new one
590 if(!array_key_exists($rec->roleid
,$roles)) {
591 $roledata=new StdClass
;
592 $roledata->id
=$rec->roleid
;
593 $roledata->shortname
=$rec->roleshortname
;
594 if(array_key_exists($rec->roleid
,$aliasnames)) {
595 $roledata->name
=$aliasnames[$rec->roleid
]->name
;
597 $roledata->name
=$rec->rolename
;
599 $roledata->users
=array();
600 $roles[$roledata->id
]=$roledata;
602 // Record that user has role
603 $users[$rec->userid
]->roles
[] = $roles[$rec->roleid
];
608 // Return false if there weren't any users
609 if(count($users)==0) {
613 // Add pseudo-role for multiple roles
614 $roledata=new StdClass
;
615 $roledata->name
=get_string('multipleroles','role');
616 $roledata->users
=array();
617 $roles['*']=$roledata;
619 // Now we rearrange the data to store users by role
620 foreach($users as $userid=>$userdata) {
621 $rolecount=count($userdata->roles
);
623 debugging("Unexpected: user $userid is missing roles");
624 } else if($rolecount>1) {
627 $roleid=$userdata->roles
[0]->id
;
629 $roles[$roleid]->users
[$userid]=$userdata;
632 // Delete roles not used
633 foreach($roles as $key=>$roledata) {
634 if(count($roledata->users
)===0) {
639 // Return list of roles containing their users