MDL-28471 better question flag icons.
[moodle.git] / group / lib.php
blob6c9e52c28641cda66776cfb0a38cee7d047b29fd
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 $groupingid
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').' groups_members');
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 // Delete all files associated with groupings for this course
411 $context = get_context_instance(CONTEXT_COURSE, $courseid);
413 //trigger groups events
414 events_trigger('groups_groupings_groups_removed', $courseid);
416 if ($showfeedback) {
417 echo $OUTPUT->notification(get_string('deleted').' groupings_groups');
420 return true;
424 * Delete all groups from course
425 * @param int $courseid
426 * @param bool $showfeedback
427 * @return bool success
429 function groups_delete_groups($courseid, $showfeedback=false) {
430 global $CFG, $DB, $OUTPUT;
432 // delete any uses of groups
433 // Any associated files are deleted as part of groups_delete_groupings_groups
434 groups_delete_groupings_groups($courseid, $showfeedback);
435 groups_delete_group_members($courseid, 0, $showfeedback);
437 // delete group pictures and descriptions
438 $context = get_context_instance(CONTEXT_COURSE, $courseid);
439 $fs = get_file_storage();
440 $fs->delete_area_files($context->id, 'group');
442 // delete group calendar events
443 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
444 $DB->delete_records_select('event', "groupid IN ($groupssql)", array($courseid));
446 $context = get_context_instance(CONTEXT_COURSE, $courseid);
447 $fs = get_file_storage();
448 $fs->delete_area_files($context->id, 'group');
450 $DB->delete_records('groups', array('courseid'=>$courseid));
452 //trigger groups events
453 events_trigger('groups_groups_deleted', $courseid);
455 if ($showfeedback) {
456 echo $OUTPUT->notification(get_string('deleted').' groups');
459 return true;
463 * Delete all groupings from course
464 * @param int $courseid
465 * @param bool $showfeedback
466 * @return bool success
468 function groups_delete_groupings($courseid, $showfeedback=false) {
469 global $DB, $OUTPUT;
471 $context = get_context_instance(CONTEXT_COURSE, $courseid);
472 $fs = get_file_storage();
474 // delete any uses of groupings
475 $sql = "DELETE FROM {groupings_groups}
476 WHERE groupingid in (SELECT id FROM {groupings} g WHERE g.courseid = ?)";
477 $DB->execute($sql, array($courseid));
479 // remove the default groupingid from course
480 $DB->set_field('course', 'defaultgroupingid', 0, array('id'=>$courseid));
481 // remove the groupingid from all course modules
482 $DB->set_field('course_modules', 'groupingid', 0, array('course'=>$courseid));
484 // Delete all files associated with groupings for this course
485 $context = get_context_instance(CONTEXT_COURSE, $courseid);
486 $fs = get_file_storage();
487 $fs->delete_area_files($context->id, 'grouping');
489 $DB->delete_records('groupings', array('courseid'=>$courseid));
491 //trigger groups events
492 events_trigger('groups_groupings_deleted', $courseid);
494 if ($showfeedback) {
495 echo $OUTPUT->notification(get_string('deleted').' groupings');
498 return true;
501 /* =================================== */
502 /* various functions used by groups UI */
503 /* =================================== */
506 * Obtains a list of the possible roles that group members might come from,
507 * on a course. Generally this includes only profile roles.
508 * @param object $context Context of course
509 * @return Array of role ID integers, or false if error/none.
511 function groups_get_possible_roles($context) {
512 $roles = get_profile_roles($context);
513 return array_keys($roles);
518 * Gets potential group members for grouping
519 * @param int $courseid The id of the course
520 * @param int $roleid The role to select users from
521 * @param int $cohortid restrict to cohort id
522 * @param string $orderby The column to sort users by
523 * @return array An array of the users
525 function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
526 global $DB;
528 $context = get_context_instance(CONTEXT_COURSE, $courseid);
530 // we are looking for all users with this role assigned in this context or higher
531 $listofcontexts = get_related_contexts_string($context);
533 list($esql, $params) = get_enrolled_sql($context);
535 if ($roleid) {
536 $params['roleid'] = $roleid;
537 $where = "WHERE u.id IN (SELECT userid
538 FROM {role_assignments}
539 WHERE roleid = :roleid AND contextid $listofcontexts)";
540 } else {
541 $where = "";
544 if ($cohortid) {
545 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
546 $params['cohortid'] = $cohortid;
547 } else {
548 $cohortjoin = "";
551 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
552 FROM {user} u
553 JOIN ($esql) e ON e.id = u.id
554 $cohortjoin
555 $where
556 ORDER BY $orderby";
558 return $DB->get_records_sql($sql, $params);
563 * Parse a group name for characters to replace
564 * @param string $format The format a group name will follow
565 * @param int $groupnumber The number of the group to be used in the parsed format string
566 * @return string the parsed format string
568 function groups_parse_name($format, $groupnumber) {
569 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
570 $letter = 'A';
571 for($i=0; $i<$groupnumber; $i++) {
572 $letter++;
574 $str = str_replace('@', $letter, $format);
575 } else {
576 $str = str_replace('#', $groupnumber+1, $format);
578 return($str);
582 * Assigns group into grouping
583 * @param int groupingid
584 * @param int groupid
585 * @return bool true or exception
587 function groups_assign_grouping($groupingid, $groupid) {
588 global $DB;
590 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
591 return true;
593 $assign = new stdClass();
594 $assign->groupingid = $groupingid;
595 $assign->groupid = $groupid;
596 $assign->timeadded = time();
597 $DB->insert_record('groupings_groups', $assign);
599 return true;
603 * Unassigns group grom grouping
604 * @param int groupingid
605 * @param int groupid
606 * @return bool success
608 function groups_unassign_grouping($groupingid, $groupid) {
609 global $DB;
610 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
612 return true;
616 * Lists users in a group based on their role on the course.
617 * Returns false if there's an error or there are no users in the group.
618 * Otherwise returns an array of role ID => role data, where role data includes:
619 * (role) $id, $shortname, $name
620 * $users: array of objects for each user which include the specified fields
621 * Users who do not have a role are stored in the returned array with key '-'
622 * and pseudo-role details (including a name, 'No role'). Users with multiple
623 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
624 * which roles each has by looking in the $roles array of the user object.
625 * @param int $groupid
626 * @param int $courseid Course ID (should match the group's course)
627 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
628 * @param string $sort SQL ORDER BY clause, default 'u.lastname ASC'
629 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
630 * @param array $whereparams any parameters required by $extrawheretest (named parameters).
631 * @return array Complex array as described above
633 function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
634 $sort='u.lastname ASC', $extrawheretest='', $whereparams=array()) {
635 global $CFG, $DB;
637 // Retrieve information about all users and their roles on the course or
638 // parent ('related') contexts
639 $context = get_context_instance(CONTEXT_COURSE, $courseid);
641 if ($extrawheretest) {
642 $extrawheretest = ' AND ' . $extrawheretest;
645 $sql = "SELECT r.id AS roleid, r.shortname AS roleshortname, r.name AS rolename,
646 u.id AS userid, $fields
647 FROM {groups_members} gm
648 JOIN {user} u ON u.id = gm.userid
649 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid ".get_related_contexts_string($context).")
650 LEFT JOIN {role} r ON r.id = ra.roleid
651 WHERE gm.groupid=:mgroupid
652 ".$extrawheretest."
653 ORDER BY r.sortorder, $sort";
654 $whereparams['mgroupid'] = $groupid;
655 $rs = $DB->get_recordset_sql($sql, $whereparams);
657 return groups_calculate_role_people($rs, $context);
661 * Internal function used by groups_get_members_by_role to handle the
662 * results of a database query that includes a list of users and possible
663 * roles on a course.
665 * @param object $rs The record set (may be false)
666 * @param int $contextid ID of course context
667 * @return array As described in groups_get_members_by_role
669 function groups_calculate_role_people($rs, $context) {
670 global $CFG, $DB;
672 if (!$rs) {
673 return array();
676 $roles = $DB->get_records_menu('role', null, 'name', 'id, name');
677 $aliasnames = role_fix_names($roles, $context);
679 // Array of all involved roles
680 $roles = array();
681 // Array of all retrieved users
682 $users = array();
683 // Fill arrays
684 foreach ($rs as $rec) {
685 // Create information about user if this is a new one
686 if (!array_key_exists($rec->userid, $users)) {
687 // User data includes all the optional fields, but not any of the
688 // stuff we added to get the role details
689 $userdata = clone($rec);
690 unset($userdata->roleid);
691 unset($userdata->roleshortname);
692 unset($userdata->rolename);
693 unset($userdata->userid);
694 $userdata->id = $rec->userid;
696 // Make an array to hold the list of roles for this user
697 $userdata->roles = array();
698 $users[$rec->userid] = $userdata;
700 // If user has a role...
701 if (!is_null($rec->roleid)) {
702 // Create information about role if this is a new one
703 if (!array_key_exists($rec->roleid,$roles)) {
704 $roledata = new stdClass();
705 $roledata->id = $rec->roleid;
706 $roledata->shortname = $rec->roleshortname;
707 if (array_key_exists($rec->roleid, $aliasnames)) {
708 $roledata->name = $aliasnames[$rec->roleid];
709 } else {
710 $roledata->name = $rec->rolename;
712 $roledata->users = array();
713 $roles[$roledata->id] = $roledata;
715 // Record that user has role
716 $users[$rec->userid]->roles[] = $roles[$rec->roleid];
719 $rs->close();
721 // Return false if there weren't any users
722 if (count($users) == 0) {
723 return false;
726 // Add pseudo-role for multiple roles
727 $roledata = new stdClass();
728 $roledata->name = get_string('multipleroles','role');
729 $roledata->users = array();
730 $roles['*'] = $roledata;
732 $roledata = new stdClass();
733 $roledata->name = get_string('noroles','role');
734 $roledata->users = array();
735 $roles[0] = $roledata;
737 // Now we rearrange the data to store users by role
738 foreach ($users as $userid=>$userdata) {
739 $rolecount = count($userdata->roles);
740 if ($rolecount == 0) {
741 // does not have any roles
742 $roleid = 0;
743 } else if($rolecount > 1) {
744 $roleid = '*';
745 } else {
746 $roleid = $userdata->roles[0]->id;
748 $roles[$roleid]->users[$userid] = $userdata;
751 // Delete roles not used
752 foreach ($roles as $key=>$roledata) {
753 if (count($roledata->users)===0) {
754 unset($roles[$key]);
758 // Return list of roles containing their users
759 return $roles;