MDL-27164 groups Do not show multiple instances of the same role as multiple
[moodle.git] / group / lib.php
CommitLineData
f3f7610c 1<?php
4d8e2417
AG
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17
f3f7610c 18/**
ddff2fa8 19 * Extra library for groups and groupings.
f3f7610c 20 *
4d8e2417
AG
21 * @copyright 2006 The Open University, J.White AT open.ac.uk, Petr Skoda (skodak)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @package core_group
f3f7610c
ML
24 */
25
ddff2fa8 26/*
27 * INTERNAL FUNCTIONS - to be used by moodle core only
28 * require_once $CFG->dirroot.'/group/lib.php' must be used
29 */
30
778918fd 31/**
32 * Adds a specified user to a group
4d8e2417
AG
33 *
34 * @param mixed $grouporid The group id or group object
35 * @param mixed $userorid The user id or user object
1d1917ae 36 * @param string $component Optional component name e.g. 'enrol_imsenterprise'
37 * @param int $itemid Optional itemid associated with component
4d8e2417 38 * @return bool True if user added successfully or the user is already a
f16fa0a3 39 * member of the group, false otherwise.
778918fd 40 */
1d1917ae 41function groups_add_member($grouporid, $userorid, $component=null, $itemid=0) {
dfdaabd6 42 global $DB;
43
9a0df45a 44 if (is_object($userorid)) {
45 $userid = $userorid->id;
46 $user = $userorid;
7881024e
PS
47 if (!isset($user->deleted)) {
48 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
49 }
9a0df45a 50 } else {
51 $userid = $userorid;
b18e25d5 52 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
2061e59c 53 }
54
7881024e
PS
55 if ($user->deleted) {
56 return false;
57 }
58
9a0df45a 59 if (is_object($grouporid)) {
60 $groupid = $grouporid->id;
61 $group = $grouporid;
62 } else {
63 $groupid = $grouporid;
64 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
778918fd 65 }
66
0d4723ee 67 //check if the user a participant of the group course
bf0f06b1 68 if (!is_enrolled(context_course::instance($group->courseid), $userid)) {
9a0df45a 69 return false;
0d4723ee 70 }
71
778918fd 72 if (groups_is_member($groupid, $userid)) {
73 return true;
74 }
75
ace9051c 76 $member = new stdClass();
778918fd 77 $member->groupid = $groupid;
78 $member->userid = $userid;
79 $member->timeadded = time();
1d1917ae 80 $member->component = '';
81 $member->itemid = 0;
82
83 // Check the component exists if specified
84 if (!empty($component)) {
85 $dir = get_component_directory($component);
86 if ($dir && is_dir($dir)) {
87 // Component exists and can be used
88 $member->component = $component;
89 $member->itemid = $itemid;
90 } else {
91 throw new coding_exception('Invalid call to groups_add_member(). An invalid component was specified');
92 }
93 }
94
95 if ($itemid !== 0 && empty($member->component)) {
96 // An itemid can only be specified if a valid component was found
97 throw new coding_exception('Invalid call to groups_add_member(). A component must be specified if an itemid is given');
98 }
778918fd 99
b25263ff 100 $DB->insert_record('groups_members', $member);
778918fd 101
102 //update group info
dfdaabd6 103 $DB->set_field('groups', 'timemodified', $member->timeadded, array('id'=>$groupid));
778918fd 104
2942a5cd 105 //trigger groups events
ace9051c 106 $eventdata = new stdClass();
778918fd 107 $eventdata->groupid = $groupid;
2942a5cd 108 $eventdata->userid = $userid;
1d1917ae 109 $eventdata->component = $member->component;
110 $eventdata->itemid = $member->itemid;
2942a5cd 111 events_trigger('groups_member_added', $eventdata);
778918fd 112
113 return true;
114}
115
1d1917ae 116/**
117 * Checks whether the current user is permitted (using the normal UI) to
118 * remove a specific group member, assuming that they have access to remove
119 * group members in general.
120 *
121 * For automatically-created group member entries, this checks with the
122 * relevant plugin to see whether it is permitted. The default, if the plugin
123 * doesn't provide a function, is true.
124 *
125 * For other entries (and any which have already been deleted/don't exist) it
126 * just returns true.
127 *
128 * @param mixed $grouporid The group id or group object
129 * @param mixed $userorid The user id or user object
130 * @return bool True if permitted, false otherwise
131 */
132function groups_remove_member_allowed($grouporid, $userorid) {
133 global $DB;
134
135 if (is_object($userorid)) {
136 $userid = $userorid->id;
137 } else {
138 $userid = $userorid;
139 }
140 if (is_object($grouporid)) {
141 $groupid = $grouporid->id;
142 } else {
143 $groupid = $grouporid;
144 }
145
146 // Get entry
147 if (!($entry = $DB->get_record('groups_members',
148 array('groupid' => $groupid, 'userid' => $userid), '*', IGNORE_MISSING))) {
149 // If the entry does not exist, they are allowed to remove it (this
150 // is consistent with groups_remove_member below).
151 return true;
152 }
153
154 // If the entry does not have a component value, they can remove it
155 if (empty($entry->component)) {
156 return true;
157 }
158
159 // It has a component value, so we need to call a plugin function (if it
160 // exists); the default is to allow removal
161 return component_callback($entry->component, 'allow_group_member_remove',
162 array($entry->itemid, $entry->groupid, $entry->userid), true);
163}
164
778918fd 165/**
166 * Deletes the link between the specified user and group.
4d8e2417
AG
167 *
168 * @param mixed $grouporid The group id or group object
169 * @param mixed $userorid The user id or user object
170 * @return bool True if deletion was successful, false otherwise
778918fd 171 */
9a0df45a 172function groups_remove_member($grouporid, $userorid) {
dfdaabd6 173 global $DB;
174
9a0df45a 175 if (is_object($userorid)) {
176 $userid = $userorid->id;
177 $user = $userorid;
178 } else {
179 $userid = $userorid;
b18e25d5 180 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
2061e59c 181 }
182
9a0df45a 183 if (is_object($grouporid)) {
184 $groupid = $grouporid->id;
185 $group = $grouporid;
186 } else {
187 $groupid = $grouporid;
188 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
778918fd 189 }
190
191 if (!groups_is_member($groupid, $userid)) {
192 return true;
193 }
194
b25263ff 195 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
196
778918fd 197 //update group info
dfdaabd6 198 $DB->set_field('groups', 'timemodified', time(), array('id'=>$groupid));
778918fd 199
2942a5cd 200 //trigger groups events
ace9051c 201 $eventdata = new stdClass();
2942a5cd 202 $eventdata->groupid = $groupid;
203 $eventdata->userid = $userid;
204 events_trigger('groups_member_removed', $eventdata);
205
778918fd 206 return true;
207}
208
ddff2fa8 209/**
210 * Add a new group
4d8e2417
AG
211 *
212 * @param stdClass $data group properties
213 * @param stdClass $editform
214 * @param array $editoroptions
ddff2fa8 215 * @return id of group or false if error
216 */
e88dd876 217function groups_create_group($data, $editform = false, $editoroptions = false) {
dfdaabd6 218 global $CFG, $DB;
6f5e0852 219
2061e59c 220 //check that courseid exists
9a0df45a 221 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
bf0f06b1 222 $context = context_course::instance($course->id);
ddff2fa8 223
dfdaabd6 224 $data->timecreated = time();
ddff2fa8 225 $data->timemodified = $data->timecreated;
dfdaabd6 226 $data->name = trim($data->name);
74b714df
ARN
227 if (isset($data->idnumber)) {
228 $data->idnumber = trim($data->idnumber);
229 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
230 throw new moodle_exception('idnumbertaken');
231 }
232 }
8bdc9cac 233
e88dd876 234 if ($editform and $editoroptions) {
8bdc9cac
SH
235 $data->description = $data->description_editor['text'];
236 $data->descriptionformat = $data->description_editor['format'];
237 }
238
e88dd876
PS
239 $data->id = $DB->insert_record('groups', $data);
240
241 if ($editform and $editoroptions) {
242 // Update description from editor with fixed files
243 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
ace9051c 244 $upd = new stdClass();
e88dd876
PS
245 $upd->id = $data->id;
246 $upd->description = $data->description;
247 $upd->descriptionformat = $data->descriptionformat;
248 $DB->update_record('groups', $upd);
249 }
250
251 $group = $DB->get_record('groups', array('id'=>$data->id));
ddff2fa8 252
b25263ff 253 if ($editform) {
e88dd876 254 groups_update_group_icon($group, $data, $editform);
ddff2fa8 255 }
256
b25263ff 257 //trigger groups events
e88dd876 258 events_trigger('groups_group_created', $group);
b25263ff 259
e88dd876 260 return $group->id;
ddff2fa8 261}
262
263/**
f16fa0a3 264 * Add a new grouping
4d8e2417
AG
265 *
266 * @param stdClass $data grouping properties
267 * @param array $editoroptions
f16fa0a3 268 * @return id of grouping or false if error
269 */
8bdc9cac 270function groups_create_grouping($data, $editoroptions=null) {
dfdaabd6 271 global $DB;
f16fa0a3 272
dfdaabd6 273 $data->timecreated = time();
f16fa0a3 274 $data->timemodified = $data->timecreated;
dfdaabd6 275 $data->name = trim($data->name);
74b714df
ARN
276 if (isset($data->idnumber)) {
277 $data->idnumber = trim($data->idnumber);
278 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
279 throw new moodle_exception('idnumbertaken');
280 }
281 }
8bdc9cac
SH
282
283 if ($editoroptions !== null) {
284 $data->description = $data->description_editor['text'];
285 $data->descriptionformat = $data->description_editor['format'];
286 }
287
2942a5cd 288 $id = $DB->insert_record('groupings', $data);
289
b25263ff 290 //trigger groups events
291 $data->id = $id;
8bdc9cac
SH
292
293 if ($editoroptions !== null) {
294 $description = new stdClass;
295 $description->id = $data->id;
296 $description->description_editor = $data->description_editor;
64f93798 297 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
8bdc9cac
SH
298 $DB->update_record('groupings', $description);
299 }
300
b25263ff 301 events_trigger('groups_grouping_created', $data);
2942a5cd 302
303 return $id;
f16fa0a3 304}
305
e88dd876
PS
306/**
307 * Update the group icon from form data
4d8e2417
AG
308 *
309 * @param stdClass $group group information
310 * @param stdClass $data
311 * @param stdClass $editform
e88dd876
PS
312 */
313function groups_update_group_icon($group, $data, $editform) {
314 global $CFG, $DB;
315 require_once("$CFG->libdir/gdlib.php");
316
317 $fs = get_file_storage();
bf0f06b1 318 $context = context_course::instance($group->courseid, MUST_EXIST);
e88dd876
PS
319
320 //TODO: it would make sense to allow picture deleting too (skodak)
5a45b936
MN
321 if (!empty($CFG->gdversion)) {
322 if ($iconfile = $editform->save_temp_file('imagefile')) {
323 if (process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
324 $DB->set_field('groups', 'picture', 1, array('id'=>$group->id));
325 $group->picture = 1;
326 } else {
327 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
328 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id));
329 $group->picture = 0;
330 }
331 @unlink($iconfile);
e88dd876 332 }
e88dd876
PS
333 }
334}
335
f16fa0a3 336/**
337 * Update group
4d8e2417
AG
338 *
339 * @param stdClass $data group properties (with magic quotes)
340 * @param stdClass $editform
e88dd876 341 * @param array $editoroptions
4d8e2417 342 * @return bool true or exception
ddff2fa8 343 */
e88dd876 344function groups_update_group($data, $editform = false, $editoroptions = false) {
dfdaabd6 345 global $CFG, $DB;
e88dd876 346
bf0f06b1 347 $context = context_course::instance($data->courseid);
ddff2fa8 348
349 $data->timemodified = time();
dfdaabd6 350 $data->name = trim($data->name);
74b714df
ARN
351 if (isset($data->idnumber)) {
352 $data->idnumber = trim($data->idnumber);
353 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
354 throw new moodle_exception('idnumbertaken');
355 }
356 }
8bdc9cac 357
e88dd876
PS
358 if ($editform and $editoroptions) {
359 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
8bdc9cac
SH
360 }
361
b25263ff 362 $DB->update_record('groups', $data);
2942a5cd 363
e88dd876
PS
364 $group = $DB->get_record('groups', array('id'=>$data->id));
365
b25263ff 366 if ($editform) {
e88dd876 367 groups_update_group_icon($group, $data, $editform);
ddff2fa8 368 }
369
b25263ff 370 //trigger groups events
e88dd876
PS
371 events_trigger('groups_group_updated', $group);
372
b25263ff 373
374 return true;
ddff2fa8 375}
376
f16fa0a3 377/**
378 * Update grouping
4d8e2417
AG
379 *
380 * @param stdClass $data grouping properties (with magic quotes)
381 * @param array $editoroptions
382 * @return bool true or exception
f16fa0a3 383 */
8bdc9cac 384function groups_update_grouping($data, $editoroptions=null) {
dfdaabd6 385 global $DB;
f16fa0a3 386 $data->timemodified = time();
dfdaabd6 387 $data->name = trim($data->name);
74b714df
ARN
388 if (isset($data->idnumber)) {
389 $data->idnumber = trim($data->idnumber);
390 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
391 throw new moodle_exception('idnumbertaken');
392 }
393 }
8bdc9cac 394 if ($editoroptions !== null) {
64f93798 395 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
8bdc9cac 396 }
b25263ff 397 $DB->update_record('groupings', $data);
398 //trigger groups events
399 events_trigger('groups_grouping_updated', $data);
400
401 return true;
f16fa0a3 402}
403
ddff2fa8 404/**
405 * Delete a group best effort, first removing members and links with courses and groupings.
406 * Removes group avatar too.
4d8e2417 407 *
2942a5cd 408 * @param mixed $grouporid The id of group to delete or full group object
4d8e2417 409 * @return bool True if deletion was successful, false otherwise
ddff2fa8 410 */
2942a5cd 411function groups_delete_group($grouporid) {
b7e8cfb6 412 global $CFG, $DB;
413 require_once("$CFG->libdir/gdlib.php");
ddff2fa8 414
2942a5cd 415 if (is_object($grouporid)) {
416 $groupid = $grouporid->id;
417 $group = $grouporid;
418 } else {
419 $groupid = $grouporid;
420 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
9a0df45a 421 //silently ignore attempts to delete missing already deleted groups ;-)
422 return true;
2942a5cd 423 }
ddff2fa8 424 }
425
0b5a80a1 426 // delete group calendar events
dfdaabd6 427 $DB->delete_records('event', array('groupid'=>$groupid));
ddff2fa8 428 //first delete usage in groupings_groups
dfdaabd6 429 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
ddff2fa8 430 //delete members
dfdaabd6 431 $DB->delete_records('groups_members', array('groupid'=>$groupid));
ddff2fa8 432 //group itself last
b25263ff 433 $DB->delete_records('groups', array('id'=>$groupid));
8bdc9cac
SH
434
435 // Delete all files associated with this group
bf0f06b1 436 $context = context_course::instance($group->courseid);
8bdc9cac 437 $fs = get_file_storage();
e88dd876
PS
438 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
439 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
8bdc9cac 440
b25263ff 441 //trigger groups events
442 events_trigger('groups_group_deleted', $group);
2942a5cd 443
b25263ff 444 return true;
ddff2fa8 445}
446
f16fa0a3 447/**
448 * Delete grouping
4d8e2417 449 *
16ef46e7 450 * @param int $groupingorid
f16fa0a3 451 * @return bool success
452 */
2942a5cd 453function groups_delete_grouping($groupingorid) {
dfdaabd6 454 global $DB;
455
2942a5cd 456 if (is_object($groupingorid)) {
457 $groupingid = $groupingorid->id;
458 $grouping = $groupingorid;
459 } else {
460 $groupingid = $groupingorid;
461 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
9a0df45a 462 //silently ignore attempts to delete missing already deleted groupings ;-)
463 return true;
2942a5cd 464 }
ddff2fa8 465 }
466
467 //first delete usage in groupings_groups
dfdaabd6 468 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
ddff2fa8 469 // remove the default groupingid from course
dfdaabd6 470 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
ddff2fa8 471 // remove the groupingid from all course modules
dfdaabd6 472 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
ddff2fa8 473 //group itself last
b25263ff 474 $DB->delete_records('groupings', array('id'=>$groupingid));
8bdc9cac 475
bf0f06b1 476 $context = context_course::instance($grouping->courseid);
8bdc9cac 477 $fs = get_file_storage();
64f93798 478 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
8bdc9cac
SH
479 foreach ($files as $file) {
480 $file->delete();
481 }
482
b25263ff 483 //trigger groups events
484 events_trigger('groups_grouping_deleted', $grouping);
2942a5cd 485
b25263ff 486 return true;
ddff2fa8 487}
488
f16fa0a3 489/**
ffc670d9 490 * Remove all users (or one user) from all groups in course
4d8e2417 491 *
f16fa0a3 492 * @param int $courseid
ffc670d9 493 * @param int $userid 0 means all users
f16fa0a3 494 * @param bool $showfeedback
495 * @return bool success
496 */
ffc670d9 497function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
a1c54f7a 498 global $DB, $OUTPUT;
ddff2fa8 499
ffc670d9 500 if (is_bool($userid)) {
501 debugging('Incorrect userid function parameter');
502 return false;
503 }
504
505 $params = array('courseid'=>$courseid);
506
507 if ($userid) {
508 $usersql = "AND userid = :userid";
509 $params['userid'] = $userid;
510 } else {
511 $usersql = "";
512 }
513
514 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = :courseid";
515 $DB->delete_records_select('groups_members', "groupid IN ($groupssql) $usersql", $params);
ddff2fa8 516
2942a5cd 517 //trigger groups events
ace9051c 518 $eventdata = new stdClass();
ffc670d9 519 $eventdata->courseid = $courseid;
520 $eventdata->userid = $userid;
521 events_trigger('groups_members_removed', $eventdata);
2942a5cd 522
ddff2fa8 523 if ($showfeedback) {
16ef46e7 524 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
ddff2fa8 525 }
526
527 return true;
528}
529
0b5a80a1 530/**
531 * Remove all groups from all groupings in course
4d8e2417 532 *
0b5a80a1 533 * @param int $courseid
534 * @param bool $showfeedback
535 * @return bool success
536 */
537function groups_delete_groupings_groups($courseid, $showfeedback=false) {
a1c54f7a 538 global $DB, $OUTPUT;
0b5a80a1 539
dfdaabd6 540 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
541 $DB->delete_records_select('groupings_groups', "groupid IN ($groupssql)", array($courseid));
0b5a80a1 542
2942a5cd 543 //trigger groups events
544 events_trigger('groups_groupings_groups_removed', $courseid);
545
16ef46e7 546 // no need to show any feedback here - we delete usually first groupings and then groups
0b5a80a1 547
548 return true;
549}
550
f16fa0a3 551/**
552 * Delete all groups from course
4d8e2417 553 *
f16fa0a3 554 * @param int $courseid
555 * @param bool $showfeedback
556 * @return bool success
557 */
ddff2fa8 558function groups_delete_groups($courseid, $showfeedback=false) {
a1c54f7a 559 global $CFG, $DB, $OUTPUT;
ddff2fa8 560
0b5a80a1 561 // delete any uses of groups
8bdc9cac 562 // Any associated files are deleted as part of groups_delete_groupings_groups
0b5a80a1 563 groups_delete_groupings_groups($courseid, $showfeedback);
ffc670d9 564 groups_delete_group_members($courseid, 0, $showfeedback);
ddff2fa8 565
d08787af 566 // delete group pictures and descriptions
bf0f06b1 567 $context = context_course::instance($courseid);
d08787af
PS
568 $fs = get_file_storage();
569 $fs->delete_area_files($context->id, 'group');
ddff2fa8 570
0b5a80a1 571 // delete group calendar events
dfdaabd6 572 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
573 $DB->delete_records_select('event', "groupid IN ($groupssql)", array($courseid));
0b5a80a1 574
bf0f06b1 575 $context = context_course::instance($courseid);
64f93798
PS
576 $fs = get_file_storage();
577 $fs->delete_area_files($context->id, 'group');
578
dfdaabd6 579 $DB->delete_records('groups', array('courseid'=>$courseid));
2942a5cd 580
16ef46e7 581 // trigger groups events
2942a5cd 582 events_trigger('groups_groups_deleted', $courseid);
583
ddff2fa8 584 if ($showfeedback) {
16ef46e7 585 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
ddff2fa8 586 }
587
588 return true;
589}
590
f16fa0a3 591/**
592 * Delete all groupings from course
4d8e2417 593 *
f16fa0a3 594 * @param int $courseid
595 * @param bool $showfeedback
596 * @return bool success
597 */
ddff2fa8 598function groups_delete_groupings($courseid, $showfeedback=false) {
a1c54f7a 599 global $DB, $OUTPUT;
ddff2fa8 600
601 // delete any uses of groupings
dfdaabd6 602 $sql = "DELETE FROM {groupings_groups}
603 WHERE groupingid in (SELECT id FROM {groupings} g WHERE g.courseid = ?)";
604 $DB->execute($sql, array($courseid));
ddff2fa8 605
606 // remove the default groupingid from course
dfdaabd6 607 $DB->set_field('course', 'defaultgroupingid', 0, array('id'=>$courseid));
ddff2fa8 608 // remove the groupingid from all course modules
dfdaabd6 609 $DB->set_field('course_modules', 'groupingid', 0, array('course'=>$courseid));
ddff2fa8 610
8bdc9cac 611 // Delete all files associated with groupings for this course
bf0f06b1 612 $context = context_course::instance($courseid);
8bdc9cac 613 $fs = get_file_storage();
64f93798
PS
614 $fs->delete_area_files($context->id, 'grouping');
615
616 $DB->delete_records('groupings', array('courseid'=>$courseid));
8bdc9cac 617
16ef46e7 618 // trigger groups events
2942a5cd 619 events_trigger('groups_groupings_deleted', $courseid);
620
ddff2fa8 621 if ($showfeedback) {
16ef46e7 622 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
ddff2fa8 623 }
624
625 return true;
626}
627
628/* =================================== */
629/* various functions used by groups UI */
630/* =================================== */
631
e254aa34 632/**
633 * Obtains a list of the possible roles that group members might come from,
df997f84 634 * on a course. Generally this includes only profile roles.
4d8e2417
AG
635 *
636 * @param context $context Context of course
e254aa34 637 * @return Array of role ID integers, or false if error/none.
638 */
639function groups_get_possible_roles($context) {
df997f84
PS
640 $roles = get_profile_roles($context);
641 return array_keys($roles);
acf000b0 642}
643
644
645/**
646 * Gets potential group members for grouping
4d8e2417 647 *
acf000b0 648 * @param int $courseid The id of the course
649 * @param int $roleid The role to select users from
92343cd2 650 * @param int $cohortid restrict to cohort id
64fa9aa7 651 * @param string $orderby The column to sort users by
acf000b0 652 * @return array An array of the users
653 */
92343cd2 654function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
4454447d 655 global $DB;
f16fa0a3 656
bf0f06b1 657 $context = context_course::instance($courseid);
acf000b0 658
659 // we are looking for all users with this role assigned in this context or higher
4f0c2d00 660 $listofcontexts = get_related_contexts_string($context);
f16fa0a3 661
4f0c2d00 662 list($esql, $params) = get_enrolled_sql($context);
64f93798 663
acf000b0 664 if ($roleid) {
dfdaabd6 665 $params['roleid'] = $roleid;
4f0c2d00
PS
666 $where = "WHERE u.id IN (SELECT userid
667 FROM {role_assignments}
668 WHERE roleid = :roleid AND contextid $listofcontexts)";
acf000b0 669 } else {
4f0c2d00 670 $where = "";
acf000b0 671 }
f16fa0a3 672
92343cd2 673 if ($cohortid) {
d490ca81
PS
674 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
675 $params['cohortid'] = $cohortid;
92343cd2
PS
676 } else {
677 $cohortjoin = "";
678 }
679
dfdaabd6 680 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
681 FROM {user} u
4f0c2d00 682 JOIN ($esql) e ON e.id = u.id
92343cd2 683 $cohortjoin
4f0c2d00 684 $where
dfdaabd6 685 ORDER BY $orderby";
f16fa0a3 686
dfdaabd6 687 return $DB->get_records_sql($sql, $params);
f16fa0a3 688
acf000b0 689}
f3f7610c 690
acf000b0 691/**
692 * Parse a group name for characters to replace
4d8e2417 693 *
acf000b0 694 * @param string $format The format a group name will follow
695 * @param int $groupnumber The number of the group to be used in the parsed format string
696 * @return string the parsed format string
697 */
698function groups_parse_name($format, $groupnumber) {
acf000b0 699 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
f16fa0a3 700 $letter = 'A';
701 for($i=0; $i<$groupnumber; $i++) {
702 $letter++;
acf000b0 703 }
f16fa0a3 704 $str = str_replace('@', $letter, $format);
acf000b0 705 } else {
4454447d 706 $str = str_replace('#', $groupnumber+1, $format);
acf000b0 707 }
708 return($str);
ddff2fa8 709}
f3f7610c 710
f16fa0a3 711/**
712 * Assigns group into grouping
4d8e2417 713 *
f16fa0a3 714 * @param int groupingid
715 * @param int groupid
b25263ff 716 * @return bool true or exception
f16fa0a3 717 */
718function groups_assign_grouping($groupingid, $groupid) {
dfdaabd6 719 global $DB;
720
721 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
f16fa0a3 722 return true;
723 }
ace9051c 724 $assign = new stdClass();
f16fa0a3 725 $assign->groupingid = $groupingid;
dfdaabd6 726 $assign->groupid = $groupid;
727 $assign->timeadded = time();
b25263ff 728 $DB->insert_record('groupings_groups', $assign);
729
730 return true;
f16fa0a3 731}
732
733/**
734 * Unassigns group grom grouping
4d8e2417 735 *
f16fa0a3 736 * @param int groupingid
737 * @param int groupid
738 * @return bool success
739 */
740function groups_unassign_grouping($groupingid, $groupid) {
dfdaabd6 741 global $DB;
b25263ff 742 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
dfdaabd6 743
b25263ff 744 return true;
f16fa0a3 745}
746
e254aa34 747/**
748 * Lists users in a group based on their role on the course.
6f5e0852 749 * Returns false if there's an error or there are no users in the group.
e254aa34 750 * Otherwise returns an array of role ID => role data, where role data includes:
751 * (role) $id, $shortname, $name
752 * $users: array of objects for each user which include the specified fields
753 * Users who do not have a role are stored in the returned array with key '-'
754 * and pseudo-role details (including a name, 'No role'). Users with multiple
755 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
756 * which roles each has by looking in the $roles array of the user object.
4d8e2417 757 *
e254aa34 758 * @param int $groupid
759 * @param int $courseid Course ID (should match the group's course)
760 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
9695ff81 761 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
97873016 762 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
9695ff81 763 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
e254aa34 764 * @return array Complex array as described above
765 */
97873016 766function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
9695ff81 767 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
dfdaabd6 768 global $CFG, $DB;
e254aa34 769
770 // Retrieve information about all users and their roles on the course or
6f5e0852 771 // parent ('related') contexts
bf0f06b1 772 $context = context_course::instance($courseid);
dfdaabd6 773
97873016 774 if ($extrawheretest) {
775 $extrawheretest = ' AND ' . $extrawheretest;
776 }
777
9695ff81
TH
778 if (is_null($sort)) {
779 list($sort, $sortparams) = users_order_by_sql('u');
780 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
781 }
782
c52551dc 783 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
dfdaabd6 784 FROM {groups_members} gm
785 JOIN {user} u ON u.id = gm.userid
1c7a2f84
PS
786 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid ".get_related_contexts_string($context).")
787 LEFT JOIN {role} r ON r.id = ra.roleid
4f0c2d00 788 WHERE gm.groupid=:mgroupid
1c7a2f84 789 ".$extrawheretest."
dfdaabd6 790 ORDER BY r.sortorder, $sort";
9695ff81
TH
791 $whereorsortparams['mgroupid'] = $groupid;
792 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
dfdaabd6 793
794 return groups_calculate_role_people($rs, $context);
e254aa34 795}
796
797/**
798 * Internal function used by groups_get_members_by_role to handle the
799 * results of a database query that includes a list of users and possible
800 * roles on a course.
801 *
4d8e2417
AG
802 * @param moodle_recordset $rs The record set (may be false)
803 * @param int $context ID of course context
6f5e0852 804 * @return array As described in groups_get_members_by_role
e254aa34 805 */
dfdaabd6 806function groups_calculate_role_people($rs, $context) {
807 global $CFG, $DB;
808
809 if (!$rs) {
810 return array();
3540f2b3 811 }
e254aa34 812
c52551dc 813 $allroles = role_fix_names(get_all_roles($context), $context);
dfdaabd6 814
e254aa34 815 // Array of all involved roles
dfdaabd6 816 $roles = array();
e254aa34 817 // Array of all retrieved users
dfdaabd6 818 $users = array();
e254aa34 819 // Fill arrays
dfdaabd6 820 foreach ($rs as $rec) {
e254aa34 821 // Create information about user if this is a new one
dfdaabd6 822 if (!array_key_exists($rec->userid, $users)) {
e254aa34 823 // User data includes all the optional fields, but not any of the
824 // stuff we added to get the role details
1c7a2f84 825 $userdata = clone($rec);
e254aa34 826 unset($userdata->roleid);
827 unset($userdata->roleshortname);
828 unset($userdata->rolename);
829 unset($userdata->userid);
dfdaabd6 830 $userdata->id = $rec->userid;
e254aa34 831
832 // Make an array to hold the list of roles for this user
dfdaabd6 833 $userdata->roles = array();
834 $users[$rec->userid] = $userdata;
e254aa34 835 }
836 // If user has a role...
dfdaabd6 837 if (!is_null($rec->roleid)) {
e254aa34 838 // Create information about role if this is a new one
c52551dc
PS
839 if (!array_key_exists($rec->roleid, $roles)) {
840 $role = $allroles[$rec->roleid];
ace9051c 841 $roledata = new stdClass();
c52551dc
PS
842 $roledata->id = $role->id;
843 $roledata->shortname = $role->shortname;
844 $roledata->name = $role->localname;
dfdaabd6 845 $roledata->users = array();
846 $roles[$roledata->id] = $roledata;
e254aa34 847 }
848 // Record that user has role
d6af3d84 849 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
e254aa34 850 }
851 }
dfdaabd6 852 $rs->close();
e254aa34 853
854 // Return false if there weren't any users
1c7a2f84 855 if (count($users) == 0) {
e254aa34 856 return false;
857 }
858
859 // Add pseudo-role for multiple roles
ace9051c 860 $roledata = new stdClass();
dfdaabd6 861 $roledata->name = get_string('multipleroles','role');
862 $roledata->users = array();
863 $roles['*'] = $roledata;
e254aa34 864
1c7a2f84
PS
865 $roledata = new stdClass();
866 $roledata->name = get_string('noroles','role');
867 $roledata->users = array();
868 $roles[0] = $roledata;
869
e254aa34 870 // Now we rearrange the data to store users by role
dfdaabd6 871 foreach ($users as $userid=>$userdata) {
872 $rolecount = count($userdata->roles);
1c7a2f84
PS
873 if ($rolecount == 0) {
874 // does not have any roles
875 $roleid = 0;
876 } else if($rolecount > 1) {
dfdaabd6 877 $roleid = '*';
e254aa34 878 } else {
d6af3d84
MA
879 $userrole = reset($userdata->roles);
880 $roleid = $userrole->id;
e254aa34 881 }
dfdaabd6 882 $roles[$roleid]->users[$userid] = $userdata;
e254aa34 883 }
884
885 // Delete roles not used
dfdaabd6 886 foreach ($roles as $key=>$roledata) {
887 if (count($roledata->users)===0) {
e254aa34 888 unset($roles[$key]);
889 }
890 }
891
892 // Return list of roles containing their users
893 return $roles;
894}