Revert "MDL-31000 Respect sortorder of repositories when displaying the filepicker"
[moodle.git] / group / lib.php
blobaef61d7095c28d50e28029aa7ef1422a5179f87c
1 <?php
2 /**
3 * Extra library for groups and groupings.
5 * @copyright &copy; 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
8 * @package groups
9 */
12 * INTERNAL FUNCTIONS - to be used by moodle core only
13 * require_once $CFG->dirroot.'/group/lib.php' must be used
16 /**
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) {
24 global $DB;
26 if (is_object($userorid)) {
27 $userid = $userorid->id;
28 $user = $userorid;
29 } else {
30 $userid = $userorid;
31 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
34 if (is_object($grouporid)) {
35 $groupid = $grouporid->id;
36 $group = $grouporid;
37 } else {
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)) {
44 return false;
47 if (groups_is_member($groupid, $userid)) {
48 return true;
51 $member = new stdClass();
52 $member->groupid = $groupid;
53 $member->userid = $userid;
54 $member->timeadded = time();
56 $DB->insert_record('groups_members', $member);
58 //update group info
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);
67 return true;
70 /**
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) {
77 global $DB;
79 if (is_object($userorid)) {
80 $userid = $userorid->id;
81 $user = $userorid;
82 } else {
83 $userid = $userorid;
84 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
87 if (is_object($grouporid)) {
88 $groupid = $grouporid->id;
89 $group = $grouporid;
90 } else {
91 $groupid = $grouporid;
92 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
95 if (!groups_is_member($groupid, $userid)) {
96 return true;
99 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
101 //update group info
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);
110 return true;
114 * Add a new group
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) {
120 global $CFG, $DB;
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));
149 if ($editform) {
150 groups_update_group_icon($group, $data, $editform);
153 //trigger groups events
154 events_trigger('groups_group_created', $group);
156 return $group->id;
160 * Add a new grouping
161 * @param object $data grouping properties
162 * @return id of grouping or false if error
164 function groups_create_grouping($data, $editoroptions=null) {
165 global $DB;
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
179 $data->id = $id;
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);
191 return $id;
195 * Update the group icon from form data
196 * @param $group
197 * @param $data
198 * @param $editform
200 function groups_update_group_icon($group, $data, $editform) {
201 global $CFG, $DB;
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));
212 $group->picture = 1;
213 } else {
214 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
215 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id));
216 $group->picture = 0;
218 @unlink($iconfile);
223 * Update group
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) {
230 global $CFG, $DB;
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));
245 if ($editform) {
246 groups_update_group_icon($group, $data, $editform);
249 //trigger groups events
250 events_trigger('groups_group_updated', $group);
253 return true;
257 * Update grouping
258 * @param object $data grouping properties (with magic quotes)
259 * @return boolean true or exception
261 function groups_update_grouping($data, $editoroptions=null) {
262 global $DB;
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);
272 return true;
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) {
282 global $CFG, $DB;
283 require_once("$CFG->libdir/gdlib.php");
285 if (is_object($grouporid)) {
286 $groupid = $grouporid->id;
287 $group = $grouporid;
288 } else {
289 $groupid = $grouporid;
290 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
291 //silently ignore attempts to delete missing already deleted groups ;-)
292 return true;
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));
300 //delete members
301 $DB->delete_records('groups_members', array('groupid'=>$groupid));
302 //group itself last
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);
314 return true;
318 * Delete grouping
319 * @param int $groupingorid
320 * @return bool success
322 function groups_delete_grouping($groupingorid) {
323 global $DB;
325 if (is_object($groupingorid)) {
326 $groupingid = $groupingorid->id;
327 $grouping = $groupingorid;
328 } else {
329 $groupingid = $groupingorid;
330 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
331 //silently ignore attempts to delete missing already deleted groupings ;-)
332 return true;
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));
342 //group itself last
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) {
349 $file->delete();
352 //trigger groups events
353 events_trigger('groups_grouping_deleted', $grouping);
355 return true;
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) {
366 global $DB, $OUTPUT;
368 if (is_bool($userid)) {
369 debugging('Incorrect userid function parameter');
370 return false;
373 $params = array('courseid'=>$courseid);
375 if ($userid) {
376 $usersql = "AND userid = :userid";
377 $params['userid'] = $userid;
378 } else {
379 $usersql = "";
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);
391 if ($showfeedback) {
392 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
395 return true;
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) {
405 global $DB, $OUTPUT;
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
415 return true;
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);
450 if ($showfeedback) {
451 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
454 return true;
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) {
464 global $DB, $OUTPUT;
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);
486 if ($showfeedback) {
487 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
490 return true;
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') {
518 global $DB;
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);
527 if ($roleid) {
528 $params['roleid'] = $roleid;
529 $where = "WHERE u.id IN (SELECT userid
530 FROM {role_assignments}
531 WHERE roleid = :roleid AND contextid $listofcontexts)";
532 } else {
533 $where = "";
536 if ($cohortid) {
537 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
538 $params['cohortid'] = $cohortid;
539 } else {
540 $cohortjoin = "";
543 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
544 FROM {user} u
545 JOIN ($esql) e ON e.id = u.id
546 $cohortjoin
547 $where
548 ORDER BY $orderby";
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
562 $letter = 'A';
563 for($i=0; $i<$groupnumber; $i++) {
564 $letter++;
566 $str = str_replace('@', $letter, $format);
567 } else {
568 $str = str_replace('#', $groupnumber+1, $format);
570 return($str);
574 * Assigns group into grouping
575 * @param int groupingid
576 * @param int groupid
577 * @return bool true or exception
579 function groups_assign_grouping($groupingid, $groupid) {
580 global $DB;
582 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
583 return true;
585 $assign = new stdClass();
586 $assign->groupingid = $groupingid;
587 $assign->groupid = $groupid;
588 $assign->timeadded = time();
589 $DB->insert_record('groupings_groups', $assign);
591 return true;
595 * Unassigns group grom grouping
596 * @param int groupingid
597 * @param int groupid
598 * @return bool success
600 function groups_unassign_grouping($groupingid, $groupid) {
601 global $DB;
602 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
604 return true;
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()) {
627 global $CFG, $DB;
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
644 ".$extrawheretest."
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
655 * roles on a course.
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) {
662 global $CFG, $DB;
664 if (!$rs) {
665 return array();
668 $roles = $DB->get_records_menu('role', null, 'name', 'id, name');
669 $aliasnames = role_fix_names($roles, $context);
671 // Array of all involved roles
672 $roles = array();
673 // Array of all retrieved users
674 $users = array();
675 // Fill arrays
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];
701 } else {
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];
711 $rs->close();
713 // Return false if there weren't any users
714 if (count($users) == 0) {
715 return false;
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
734 $roleid = 0;
735 } else if($rolecount > 1) {
736 $roleid = '*';
737 } else {
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) {
746 unset($roles[$key]);
750 // Return list of roles containing their users
751 return $roles;