MDL-50357 groups: remove pointless option of groups_delete_group_members
[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
861b0510
FM
67 // Check if the user a participant of the group course.
68 $context = context_course::instance($group->courseid);
69 if (!is_enrolled($context, $userid)) {
9a0df45a 70 return false;
0d4723ee 71 }
72
778918fd 73 if (groups_is_member($groupid, $userid)) {
74 return true;
75 }
76
ace9051c 77 $member = new stdClass();
778918fd 78 $member->groupid = $groupid;
79 $member->userid = $userid;
80 $member->timeadded = time();
1d1917ae 81 $member->component = '';
82 $member->itemid = 0;
83
84 // Check the component exists if specified
85 if (!empty($component)) {
b0d1d941 86 $dir = core_component::get_component_directory($component);
1d1917ae 87 if ($dir && is_dir($dir)) {
88 // Component exists and can be used
89 $member->component = $component;
90 $member->itemid = $itemid;
91 } else {
92 throw new coding_exception('Invalid call to groups_add_member(). An invalid component was specified');
93 }
94 }
95
96 if ($itemid !== 0 && empty($member->component)) {
97 // An itemid can only be specified if a valid component was found
98 throw new coding_exception('Invalid call to groups_add_member(). A component must be specified if an itemid is given');
99 }
778918fd 100
b25263ff 101 $DB->insert_record('groups_members', $member);
778918fd 102
861b0510 103 // Update group info, and group object.
dfdaabd6 104 $DB->set_field('groups', 'timemodified', $member->timeadded, array('id'=>$groupid));
861b0510
FM
105 $group->timemodified = $member->timeadded;
106
107 // Trigger group event.
108 $params = array(
109 'context' => $context,
110 'objectid' => $groupid,
111 'relateduserid' => $userid,
112 'other' => array(
113 'component' => $member->component,
114 'itemid' => $member->itemid
115 )
116 );
117 $event = \core\event\group_member_added::create($params);
118 $event->add_record_snapshot('groups', $group);
119 $event->trigger();
778918fd 120
121 return true;
122}
123
1d1917ae 124/**
125 * Checks whether the current user is permitted (using the normal UI) to
126 * remove a specific group member, assuming that they have access to remove
127 * group members in general.
128 *
129 * For automatically-created group member entries, this checks with the
130 * relevant plugin to see whether it is permitted. The default, if the plugin
131 * doesn't provide a function, is true.
132 *
133 * For other entries (and any which have already been deleted/don't exist) it
134 * just returns true.
135 *
136 * @param mixed $grouporid The group id or group object
137 * @param mixed $userorid The user id or user object
138 * @return bool True if permitted, false otherwise
139 */
140function groups_remove_member_allowed($grouporid, $userorid) {
141 global $DB;
142
143 if (is_object($userorid)) {
144 $userid = $userorid->id;
145 } else {
146 $userid = $userorid;
147 }
148 if (is_object($grouporid)) {
149 $groupid = $grouporid->id;
150 } else {
151 $groupid = $grouporid;
152 }
153
154 // Get entry
155 if (!($entry = $DB->get_record('groups_members',
156 array('groupid' => $groupid, 'userid' => $userid), '*', IGNORE_MISSING))) {
157 // If the entry does not exist, they are allowed to remove it (this
158 // is consistent with groups_remove_member below).
159 return true;
160 }
161
162 // If the entry does not have a component value, they can remove it
163 if (empty($entry->component)) {
164 return true;
165 }
166
167 // It has a component value, so we need to call a plugin function (if it
168 // exists); the default is to allow removal
169 return component_callback($entry->component, 'allow_group_member_remove',
170 array($entry->itemid, $entry->groupid, $entry->userid), true);
171}
172
778918fd 173/**
174 * Deletes the link between the specified user and group.
4d8e2417
AG
175 *
176 * @param mixed $grouporid The group id or group object
177 * @param mixed $userorid The user id or user object
178 * @return bool True if deletion was successful, false otherwise
778918fd 179 */
9a0df45a 180function groups_remove_member($grouporid, $userorid) {
dfdaabd6 181 global $DB;
182
9a0df45a 183 if (is_object($userorid)) {
184 $userid = $userorid->id;
9a0df45a 185 } else {
186 $userid = $userorid;
2061e59c 187 }
188
9a0df45a 189 if (is_object($grouporid)) {
190 $groupid = $grouporid->id;
191 $group = $grouporid;
192 } else {
193 $groupid = $grouporid;
194 $group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
778918fd 195 }
196
197 if (!groups_is_member($groupid, $userid)) {
198 return true;
199 }
200
b25263ff 201 $DB->delete_records('groups_members', array('groupid'=>$groupid, 'userid'=>$userid));
202
861b0510
FM
203 // Update group info.
204 $time = time();
205 $DB->set_field('groups', 'timemodified', $time, array('id' => $groupid));
206 $group->timemodified = $time;
207
208 // Trigger group event.
209 $params = array(
210 'context' => context_course::instance($group->courseid),
211 'objectid' => $groupid,
212 'relateduserid' => $userid
213 );
214 $event = \core\event\group_member_removed::create($params);
215 $event->add_record_snapshot('groups', $group);
216 $event->trigger();
2942a5cd 217
778918fd 218 return true;
219}
220
ddff2fa8 221/**
222 * Add a new group
4d8e2417
AG
223 *
224 * @param stdClass $data group properties
225 * @param stdClass $editform
226 * @param array $editoroptions
ddff2fa8 227 * @return id of group or false if error
228 */
e88dd876 229function groups_create_group($data, $editform = false, $editoroptions = false) {
dfdaabd6 230 global $CFG, $DB;
6f5e0852 231
2061e59c 232 //check that courseid exists
74df2951 233 $course = $DB->get_record('course', array('id' => $data->courseid), '*', MUST_EXIST);
bf0f06b1 234 $context = context_course::instance($course->id);
ddff2fa8 235
dfdaabd6 236 $data->timecreated = time();
ddff2fa8 237 $data->timemodified = $data->timecreated;
dfdaabd6 238 $data->name = trim($data->name);
74b714df
ARN
239 if (isset($data->idnumber)) {
240 $data->idnumber = trim($data->idnumber);
241 if (groups_get_group_by_idnumber($course->id, $data->idnumber)) {
242 throw new moodle_exception('idnumbertaken');
243 }
244 }
8bdc9cac 245
e88dd876 246 if ($editform and $editoroptions) {
8bdc9cac
SH
247 $data->description = $data->description_editor['text'];
248 $data->descriptionformat = $data->description_editor['format'];
249 }
250
e88dd876
PS
251 $data->id = $DB->insert_record('groups', $data);
252
253 if ($editform and $editoroptions) {
254 // Update description from editor with fixed files
255 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
ace9051c 256 $upd = new stdClass();
e88dd876
PS
257 $upd->id = $data->id;
258 $upd->description = $data->description;
259 $upd->descriptionformat = $data->descriptionformat;
260 $DB->update_record('groups', $upd);
261 }
262
263 $group = $DB->get_record('groups', array('id'=>$data->id));
ddff2fa8 264
b25263ff 265 if ($editform) {
e88dd876 266 groups_update_group_icon($group, $data, $editform);
ddff2fa8 267 }
268
e17dbeeb
SH
269 // Invalidate the grouping cache for the course
270 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($course->id));
271
861b0510
FM
272 // Trigger group event.
273 $params = array(
274 'context' => $context,
275 'objectid' => $group->id
276 );
277 $event = \core\event\group_created::create($params);
278 $event->add_record_snapshot('groups', $group);
279 $event->trigger();
b25263ff 280
e88dd876 281 return $group->id;
ddff2fa8 282}
283
284/**
f16fa0a3 285 * Add a new grouping
4d8e2417
AG
286 *
287 * @param stdClass $data grouping properties
288 * @param array $editoroptions
f16fa0a3 289 * @return id of grouping or false if error
290 */
8bdc9cac 291function groups_create_grouping($data, $editoroptions=null) {
dfdaabd6 292 global $DB;
f16fa0a3 293
dfdaabd6 294 $data->timecreated = time();
f16fa0a3 295 $data->timemodified = $data->timecreated;
dfdaabd6 296 $data->name = trim($data->name);
74b714df
ARN
297 if (isset($data->idnumber)) {
298 $data->idnumber = trim($data->idnumber);
299 if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
300 throw new moodle_exception('idnumbertaken');
301 }
302 }
8bdc9cac
SH
303
304 if ($editoroptions !== null) {
305 $data->description = $data->description_editor['text'];
306 $data->descriptionformat = $data->description_editor['format'];
307 }
308
2942a5cd 309 $id = $DB->insert_record('groupings', $data);
b25263ff 310 $data->id = $id;
8bdc9cac
SH
311
312 if ($editoroptions !== null) {
313 $description = new stdClass;
314 $description->id = $data->id;
315 $description->description_editor = $data->description_editor;
64f93798 316 $description = file_postupdate_standard_editor($description, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $description->id);
8bdc9cac
SH
317 $DB->update_record('groupings', $description);
318 }
319
e17dbeeb
SH
320 // Invalidate the grouping cache for the course
321 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
322
861b0510
FM
323 // Trigger group event.
324 $params = array(
325 'context' => context_course::instance($data->courseid),
326 'objectid' => $id
327 );
328 $event = \core\event\grouping_created::create($params);
861b0510 329 $event->trigger();
2942a5cd 330
331 return $id;
f16fa0a3 332}
333
e88dd876
PS
334/**
335 * Update the group icon from form data
4d8e2417
AG
336 *
337 * @param stdClass $group group information
338 * @param stdClass $data
339 * @param stdClass $editform
e88dd876
PS
340 */
341function groups_update_group_icon($group, $data, $editform) {
342 global $CFG, $DB;
343 require_once("$CFG->libdir/gdlib.php");
344
345 $fs = get_file_storage();
bf0f06b1 346 $context = context_course::instance($group->courseid, MUST_EXIST);
d996c620 347 $newpicture = $group->picture;
e88dd876 348
d996c620
FM
349 if (!empty($data->deletepicture)) {
350 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
351 $newpicture = 0;
352 } else if ($iconfile = $editform->save_temp_file('imagefile')) {
21449d01 353 if ($rev = process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
d996c620 354 $newpicture = $rev;
689096bc
PS
355 } else {
356 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
d996c620 357 $newpicture = 0;
e88dd876 358 }
689096bc 359 @unlink($iconfile);
d996c620
FM
360 }
361
362 if ($newpicture != $group->picture) {
363 $DB->set_field('groups', 'picture', $newpicture, array('id' => $group->id));
364 $group->picture = $newpicture;
365
689096bc
PS
366 // Invalidate the group data as we've updated the group record.
367 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
e88dd876
PS
368 }
369}
370
f16fa0a3 371/**
372 * Update group
4d8e2417
AG
373 *
374 * @param stdClass $data group properties (with magic quotes)
375 * @param stdClass $editform
e88dd876 376 * @param array $editoroptions
4d8e2417 377 * @return bool true or exception
ddff2fa8 378 */
e88dd876 379function groups_update_group($data, $editform = false, $editoroptions = false) {
dfdaabd6 380 global $CFG, $DB;
e88dd876 381
bf0f06b1 382 $context = context_course::instance($data->courseid);
ddff2fa8 383
384 $data->timemodified = time();
f84b9e65
TB
385 if (isset($data->name)) {
386 $data->name = trim($data->name);
387 }
74b714df
ARN
388 if (isset($data->idnumber)) {
389 $data->idnumber = trim($data->idnumber);
390 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
391 throw new moodle_exception('idnumbertaken');
392 }
393 }
8bdc9cac 394
e88dd876
PS
395 if ($editform and $editoroptions) {
396 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
8bdc9cac
SH
397 }
398
b25263ff 399 $DB->update_record('groups', $data);
2942a5cd 400
e17dbeeb
SH
401 // Invalidate the group data.
402 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
403
e88dd876
PS
404 $group = $DB->get_record('groups', array('id'=>$data->id));
405
b25263ff 406 if ($editform) {
e88dd876 407 groups_update_group_icon($group, $data, $editform);
ddff2fa8 408 }
409
861b0510
FM
410 // Trigger group event.
411 $params = array(
412 'context' => $context,
413 'objectid' => $group->id
414 );
415 $event = \core\event\group_updated::create($params);
416 $event->add_record_snapshot('groups', $group);
417 $event->trigger();
b25263ff 418
419 return true;
ddff2fa8 420}
421
f16fa0a3 422/**
423 * Update grouping
4d8e2417
AG
424 *
425 * @param stdClass $data grouping properties (with magic quotes)
426 * @param array $editoroptions
427 * @return bool true or exception
f16fa0a3 428 */
8bdc9cac 429function groups_update_grouping($data, $editoroptions=null) {
dfdaabd6 430 global $DB;
f16fa0a3 431 $data->timemodified = time();
f84b9e65
TB
432 if (isset($data->name)) {
433 $data->name = trim($data->name);
434 }
74b714df
ARN
435 if (isset($data->idnumber)) {
436 $data->idnumber = trim($data->idnumber);
437 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
438 throw new moodle_exception('idnumbertaken');
439 }
440 }
8bdc9cac 441 if ($editoroptions !== null) {
64f93798 442 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
8bdc9cac 443 }
b25263ff 444 $DB->update_record('groupings', $data);
e17dbeeb
SH
445
446 // Invalidate the group data.
447 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
448
861b0510
FM
449 // Trigger group event.
450 $params = array(
451 'context' => context_course::instance($data->courseid),
452 'objectid' => $data->id
453 );
454 $event = \core\event\grouping_updated::create($params);
861b0510 455 $event->trigger();
b25263ff 456
457 return true;
f16fa0a3 458}
459
ddff2fa8 460/**
461 * Delete a group best effort, first removing members and links with courses and groupings.
462 * Removes group avatar too.
4d8e2417 463 *
2942a5cd 464 * @param mixed $grouporid The id of group to delete or full group object
4d8e2417 465 * @return bool True if deletion was successful, false otherwise
ddff2fa8 466 */
2942a5cd 467function groups_delete_group($grouporid) {
b7e8cfb6 468 global $CFG, $DB;
469 require_once("$CFG->libdir/gdlib.php");
ddff2fa8 470
2942a5cd 471 if (is_object($grouporid)) {
472 $groupid = $grouporid->id;
473 $group = $grouporid;
474 } else {
475 $groupid = $grouporid;
476 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
9a0df45a 477 //silently ignore attempts to delete missing already deleted groups ;-)
478 return true;
2942a5cd 479 }
ddff2fa8 480 }
481
0b5a80a1 482 // delete group calendar events
dfdaabd6 483 $DB->delete_records('event', array('groupid'=>$groupid));
ddff2fa8 484 //first delete usage in groupings_groups
dfdaabd6 485 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
ddff2fa8 486 //delete members
dfdaabd6 487 $DB->delete_records('groups_members', array('groupid'=>$groupid));
ddff2fa8 488 //group itself last
b25263ff 489 $DB->delete_records('groups', array('id'=>$groupid));
8bdc9cac
SH
490
491 // Delete all files associated with this group
bf0f06b1 492 $context = context_course::instance($group->courseid);
8bdc9cac 493 $fs = get_file_storage();
e88dd876
PS
494 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
495 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
8bdc9cac 496
e17dbeeb
SH
497 // Invalidate the grouping cache for the course
498 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
499
861b0510
FM
500 // Trigger group event.
501 $params = array(
502 'context' => $context,
503 'objectid' => $groupid
504 );
505 $event = \core\event\group_deleted::create($params);
506 $event->add_record_snapshot('groups', $group);
507 $event->trigger();
2942a5cd 508
b25263ff 509 return true;
ddff2fa8 510}
511
f16fa0a3 512/**
513 * Delete grouping
4d8e2417 514 *
16ef46e7 515 * @param int $groupingorid
f16fa0a3 516 * @return bool success
517 */
2942a5cd 518function groups_delete_grouping($groupingorid) {
dfdaabd6 519 global $DB;
520
2942a5cd 521 if (is_object($groupingorid)) {
522 $groupingid = $groupingorid->id;
523 $grouping = $groupingorid;
524 } else {
525 $groupingid = $groupingorid;
526 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
9a0df45a 527 //silently ignore attempts to delete missing already deleted groupings ;-)
528 return true;
2942a5cd 529 }
ddff2fa8 530 }
531
532 //first delete usage in groupings_groups
dfdaabd6 533 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
ddff2fa8 534 // remove the default groupingid from course
dfdaabd6 535 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
ddff2fa8 536 // remove the groupingid from all course modules
dfdaabd6 537 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
ddff2fa8 538 //group itself last
b25263ff 539 $DB->delete_records('groupings', array('id'=>$groupingid));
8bdc9cac 540
bf0f06b1 541 $context = context_course::instance($grouping->courseid);
8bdc9cac 542 $fs = get_file_storage();
64f93798 543 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
8bdc9cac
SH
544 foreach ($files as $file) {
545 $file->delete();
546 }
547
e17dbeeb
SH
548 // Invalidate the grouping cache for the course
549 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
550
861b0510
FM
551 // Trigger group event.
552 $params = array(
553 'context' => $context,
554 'objectid' => $groupingid
555 );
556 $event = \core\event\grouping_deleted::create($params);
557 $event->add_record_snapshot('groupings', $grouping);
558 $event->trigger();
2942a5cd 559
b25263ff 560 return true;
ddff2fa8 561}
562
f16fa0a3 563/**
ffc670d9 564 * Remove all users (or one user) from all groups in course
4d8e2417 565 *
f16fa0a3 566 * @param int $courseid
ffc670d9 567 * @param int $userid 0 means all users
53a2405c 568 * @param bool $unused - formerly $showfeedback, is no longer used.
f16fa0a3 569 * @return bool success
570 */
53a2405c 571function groups_delete_group_members($courseid, $userid=0, $unused=false) {
a1c54f7a 572 global $DB, $OUTPUT;
ddff2fa8 573
04503c5c
MN
574 // Get the users in the course which are in a group.
575 $sql = "SELECT gm.id as gmid, gm.userid, g.*
576 FROM {groups_members} gm
577 INNER JOIN {groups} g
578 ON gm.groupid = g.id
579 WHERE g.courseid = :courseid";
580 $params = array();
581 $params['courseid'] = $courseid;
582 // Check if we want to delete a specific user.
583 if ($userid) {
584 $sql .= " AND gm.userid = :userid";
585 $params['userid'] = $userid;
586 }
587 $rs = $DB->get_recordset_sql($sql, $params);
588 foreach ($rs as $usergroup) {
589 groups_remove_member($usergroup, $usergroup->userid);
590 }
591 $rs->close();
ffc670d9 592
861b0510
FM
593 // TODO MDL-41312 Remove events_trigger_legacy('groups_members_removed').
594 // This event is kept here for backwards compatibility, because it cannot be
595 // translated to a new event as it is wrong.
ace9051c 596 $eventdata = new stdClass();
ffc670d9 597 $eventdata->courseid = $courseid;
598 $eventdata->userid = $userid;
861b0510 599 events_trigger_legacy('groups_members_removed', $eventdata);
2942a5cd 600
ddff2fa8 601 return true;
602}
603
0b5a80a1 604/**
605 * Remove all groups from all groupings in course
4d8e2417 606 *
0b5a80a1 607 * @param int $courseid
608 * @param bool $showfeedback
609 * @return bool success
610 */
611function groups_delete_groupings_groups($courseid, $showfeedback=false) {
a1c54f7a 612 global $DB, $OUTPUT;
0b5a80a1 613
dfdaabd6 614 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
861b0510
FM
615 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
616 array($courseid), '', 'groupid, groupingid');
617
618 foreach ($results as $result) {
619 groups_unassign_grouping($result->groupingid, $result->groupid, false);
620 }
0b5a80a1 621
e17dbeeb
SH
622 // Invalidate the grouping cache for the course
623 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
624
861b0510
FM
625 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_groups_removed').
626 // This event is kept here for backwards compatibility, because it cannot be
627 // translated to a new event as it is wrong.
628 events_trigger_legacy('groups_groupings_groups_removed', $courseid);
2942a5cd 629
16ef46e7 630 // no need to show any feedback here - we delete usually first groupings and then groups
0b5a80a1 631
632 return true;
633}
634
f16fa0a3 635/**
636 * Delete all groups from course
4d8e2417 637 *
f16fa0a3 638 * @param int $courseid
639 * @param bool $showfeedback
640 * @return bool success
641 */
ddff2fa8 642function groups_delete_groups($courseid, $showfeedback=false) {
a1c54f7a 643 global $CFG, $DB, $OUTPUT;
ddff2fa8 644
861b0510
FM
645 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
646 foreach ($groups as $group) {
647 groups_delete_group($group);
648 }
2942a5cd 649
e17dbeeb
SH
650 // Invalidate the grouping cache for the course
651 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
652
861b0510
FM
653 // TODO MDL-41312 Remove events_trigger_legacy('groups_groups_deleted').
654 // This event is kept here for backwards compatibility, because it cannot be
655 // translated to a new event as it is wrong.
656 events_trigger_legacy('groups_groups_deleted', $courseid);
2942a5cd 657
ddff2fa8 658 if ($showfeedback) {
16ef46e7 659 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
ddff2fa8 660 }
661
662 return true;
663}
664
f16fa0a3 665/**
666 * Delete all groupings from course
4d8e2417 667 *
f16fa0a3 668 * @param int $courseid
669 * @param bool $showfeedback
670 * @return bool success
671 */
ddff2fa8 672function groups_delete_groupings($courseid, $showfeedback=false) {
a1c54f7a 673 global $DB, $OUTPUT;
ddff2fa8 674
861b0510
FM
675 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
676 foreach ($groupings as $grouping) {
677 groups_delete_grouping($grouping);
678 }
8bdc9cac 679
861b0510 680 // Invalidate the grouping cache for the course.
e17dbeeb
SH
681 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
682
861b0510
FM
683 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_deleted').
684 // This event is kept here for backwards compatibility, because it cannot be
685 // translated to a new event as it is wrong.
686 events_trigger_legacy('groups_groupings_deleted', $courseid);
2942a5cd 687
ddff2fa8 688 if ($showfeedback) {
16ef46e7 689 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
ddff2fa8 690 }
691
692 return true;
693}
694
695/* =================================== */
696/* various functions used by groups UI */
697/* =================================== */
698
e254aa34 699/**
700 * Obtains a list of the possible roles that group members might come from,
df997f84 701 * on a course. Generally this includes only profile roles.
4d8e2417
AG
702 *
703 * @param context $context Context of course
e254aa34 704 * @return Array of role ID integers, or false if error/none.
705 */
706function groups_get_possible_roles($context) {
df997f84
PS
707 $roles = get_profile_roles($context);
708 return array_keys($roles);
acf000b0 709}
710
711
712/**
713 * Gets potential group members for grouping
4d8e2417 714 *
acf000b0 715 * @param int $courseid The id of the course
716 * @param int $roleid The role to select users from
e4ebf7ef 717 * @param mixed $source restrict to cohort, grouping or group id
64fa9aa7 718 * @param string $orderby The column to sort users by
55c9a150 719 * @param int $notingroup restrict to users not in existing groups
acf000b0 720 * @return array An array of the users
721 */
e4ebf7ef 722function groups_get_potential_members($courseid, $roleid = null, $source = null,
55c9a150
S
723 $orderby = 'lastname ASC, firstname ASC',
724 $notingroup = null) {
4454447d 725 global $DB;
f16fa0a3 726
bf0f06b1 727 $context = context_course::instance($courseid);
acf000b0 728
4f0c2d00 729 list($esql, $params) = get_enrolled_sql($context);
64f93798 730
55c9a150
S
731 $notingroupsql = "";
732 if ($notingroup) {
733 // We want to eliminate users that are already associated with a course group.
734 $notingroupsql = "u.id NOT IN (SELECT userid
735 FROM {groups_members}
736 WHERE groupid IN (SELECT id
737 FROM {groups}
738 WHERE courseid = :courseid))";
739 $params['courseid'] = $courseid;
740 }
741
acf000b0 742 if ($roleid) {
4e829d48 743 // We are looking for all users with this role assigned in this context or higher.
55c9a150
S
744 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true),
745 SQL_PARAMS_NAMED,
746 'relatedctx');
4e829d48
MN
747
748 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
4f0c2d00
PS
749 $where = "WHERE u.id IN (SELECT userid
750 FROM {role_assignments}
4e829d48 751 WHERE roleid = :roleid AND contextid $relatedctxsql)";
55c9a150
S
752 $where .= $notingroup ? "AND $notingroupsql" : "";
753 } else if ($notingroup) {
754 $where = "WHERE $notingroupsql";
acf000b0 755 } else {
4f0c2d00 756 $where = "";
acf000b0 757 }
f16fa0a3 758
e4ebf7ef
GF
759 $sourcejoin = "";
760 if (is_int($source)) {
761 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
762 $params['cohortid'] = $source;
92343cd2 763 } else {
e4ebf7ef
GF
764 // Auto-create groups from an existing cohort membership.
765 if (isset($source['cohortid'])) {
766 $sourcejoin .= "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid) ";
767 $params['cohortid'] = $source['cohortid'];
768 }
769 // Auto-create groups from an existing group membership.
770 if (isset($source['groupid'])) {
771 $sourcejoin .= "JOIN {groups_members} gp ON (gp.userid = u.id AND gp.groupid = :groupid) ";
772 $params['groupid'] = $source['groupid'];
773 }
774 // Auto-create groups from an existing grouping membership.
775 if (isset($source['groupingid'])) {
776 $sourcejoin .= "JOIN {groupings_groups} gg ON gg.groupingid = :groupingid ";
777 $sourcejoin .= "JOIN {groups_members} gm ON (gm.userid = u.id AND gm.groupid = gg.groupid) ";
778 $params['groupingid'] = $source['groupingid'];
779 }
92343cd2
PS
780 }
781
60f55a2f 782 $allusernamefields = get_all_user_name_fields(true, 'u');
e4ebf7ef 783 $sql = "SELECT DISTINCT u.id, u.username, $allusernamefields, u.idnumber
dfdaabd6 784 FROM {user} u
4f0c2d00 785 JOIN ($esql) e ON e.id = u.id
e4ebf7ef 786 $sourcejoin
4f0c2d00 787 $where
dfdaabd6 788 ORDER BY $orderby";
f16fa0a3 789
dfdaabd6 790 return $DB->get_records_sql($sql, $params);
f16fa0a3 791
acf000b0 792}
f3f7610c 793
acf000b0 794/**
795 * Parse a group name for characters to replace
4d8e2417 796 *
acf000b0 797 * @param string $format The format a group name will follow
798 * @param int $groupnumber The number of the group to be used in the parsed format string
799 * @return string the parsed format string
800 */
801function groups_parse_name($format, $groupnumber) {
acf000b0 802 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
f16fa0a3 803 $letter = 'A';
804 for($i=0; $i<$groupnumber; $i++) {
805 $letter++;
acf000b0 806 }
f16fa0a3 807 $str = str_replace('@', $letter, $format);
acf000b0 808 } else {
4454447d 809 $str = str_replace('#', $groupnumber+1, $format);
acf000b0 810 }
811 return($str);
ddff2fa8 812}
f3f7610c 813
f16fa0a3 814/**
815 * Assigns group into grouping
4d8e2417 816 *
f16fa0a3 817 * @param int groupingid
818 * @param int groupid
51e8d287 819 * @param int $timeadded The time the group was added to the grouping.
e17dbeeb 820 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
b25263ff 821 * @return bool true or exception
f16fa0a3 822 */
e17dbeeb 823function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
dfdaabd6 824 global $DB;
825
826 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
f16fa0a3 827 return true;
828 }
ace9051c 829 $assign = new stdClass();
f16fa0a3 830 $assign->groupingid = $groupingid;
dfdaabd6 831 $assign->groupid = $groupid;
51e8d287
AG
832 if ($timeadded != null) {
833 $assign->timeadded = (integer)$timeadded;
834 } else {
835 $assign->timeadded = time();
836 }
b25263ff 837 $DB->insert_record('groupings_groups', $assign);
838
e17dbeeb
SH
839 if ($invalidatecache) {
840 // Invalidate the grouping cache for the course
841 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
842 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
843 }
844
b25263ff 845 return true;
f16fa0a3 846}
847
848/**
e17dbeeb 849 * Unassigns group from grouping
4d8e2417 850 *
f16fa0a3 851 * @param int groupingid
852 * @param int groupid
e17dbeeb 853 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
f16fa0a3 854 * @return bool success
855 */
e17dbeeb 856function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
dfdaabd6 857 global $DB;
b25263ff 858 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
dfdaabd6 859
e17dbeeb
SH
860 if ($invalidatecache) {
861 // Invalidate the grouping cache for the course
862 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
863 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
864 }
865
b25263ff 866 return true;
f16fa0a3 867}
868
e254aa34 869/**
870 * Lists users in a group based on their role on the course.
6f5e0852 871 * Returns false if there's an error or there are no users in the group.
e254aa34 872 * Otherwise returns an array of role ID => role data, where role data includes:
873 * (role) $id, $shortname, $name
874 * $users: array of objects for each user which include the specified fields
875 * Users who do not have a role are stored in the returned array with key '-'
876 * and pseudo-role details (including a name, 'No role'). Users with multiple
877 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
878 * which roles each has by looking in the $roles array of the user object.
4d8e2417 879 *
e254aa34 880 * @param int $groupid
881 * @param int $courseid Course ID (should match the group's course)
882 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
9695ff81 883 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
97873016 884 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
9695ff81 885 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
e254aa34 886 * @return array Complex array as described above
887 */
97873016 888function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
9695ff81 889 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
4e829d48 890 global $DB;
e254aa34 891
892 // Retrieve information about all users and their roles on the course or
6f5e0852 893 // parent ('related') contexts
bf0f06b1 894 $context = context_course::instance($courseid);
dfdaabd6 895
4e829d48
MN
896 // We are looking for all users with this role assigned in this context or higher.
897 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
898
97873016 899 if ($extrawheretest) {
900 $extrawheretest = ' AND ' . $extrawheretest;
901 }
902
9695ff81
TH
903 if (is_null($sort)) {
904 list($sort, $sortparams) = users_order_by_sql('u');
905 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
906 }
907
c52551dc 908 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
dfdaabd6 909 FROM {groups_members} gm
910 JOIN {user} u ON u.id = gm.userid
4e829d48 911 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
1c7a2f84 912 LEFT JOIN {role} r ON r.id = ra.roleid
4f0c2d00 913 WHERE gm.groupid=:mgroupid
1c7a2f84 914 ".$extrawheretest."
dfdaabd6 915 ORDER BY r.sortorder, $sort";
4e829d48 916 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
9695ff81 917 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
dfdaabd6 918
919 return groups_calculate_role_people($rs, $context);
e254aa34 920}
921
922/**
923 * Internal function used by groups_get_members_by_role to handle the
924 * results of a database query that includes a list of users and possible
925 * roles on a course.
926 *
4d8e2417
AG
927 * @param moodle_recordset $rs The record set (may be false)
928 * @param int $context ID of course context
6f5e0852 929 * @return array As described in groups_get_members_by_role
e254aa34 930 */
dfdaabd6 931function groups_calculate_role_people($rs, $context) {
932 global $CFG, $DB;
933
934 if (!$rs) {
935 return array();
3540f2b3 936 }
e254aa34 937
c52551dc 938 $allroles = role_fix_names(get_all_roles($context), $context);
dfdaabd6 939
e254aa34 940 // Array of all involved roles
dfdaabd6 941 $roles = array();
e254aa34 942 // Array of all retrieved users
dfdaabd6 943 $users = array();
e254aa34 944 // Fill arrays
dfdaabd6 945 foreach ($rs as $rec) {
e254aa34 946 // Create information about user if this is a new one
dfdaabd6 947 if (!array_key_exists($rec->userid, $users)) {
e254aa34 948 // User data includes all the optional fields, but not any of the
949 // stuff we added to get the role details
1c7a2f84 950 $userdata = clone($rec);
e254aa34 951 unset($userdata->roleid);
952 unset($userdata->roleshortname);
953 unset($userdata->rolename);
954 unset($userdata->userid);
dfdaabd6 955 $userdata->id = $rec->userid;
e254aa34 956
957 // Make an array to hold the list of roles for this user
dfdaabd6 958 $userdata->roles = array();
959 $users[$rec->userid] = $userdata;
e254aa34 960 }
961 // If user has a role...
dfdaabd6 962 if (!is_null($rec->roleid)) {
e254aa34 963 // Create information about role if this is a new one
c52551dc
PS
964 if (!array_key_exists($rec->roleid, $roles)) {
965 $role = $allroles[$rec->roleid];
ace9051c 966 $roledata = new stdClass();
c52551dc
PS
967 $roledata->id = $role->id;
968 $roledata->shortname = $role->shortname;
969 $roledata->name = $role->localname;
dfdaabd6 970 $roledata->users = array();
971 $roles[$roledata->id] = $roledata;
e254aa34 972 }
973 // Record that user has role
d6af3d84 974 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
e254aa34 975 }
976 }
dfdaabd6 977 $rs->close();
e254aa34 978
979 // Return false if there weren't any users
1c7a2f84 980 if (count($users) == 0) {
e254aa34 981 return false;
982 }
983
984 // Add pseudo-role for multiple roles
ace9051c 985 $roledata = new stdClass();
dfdaabd6 986 $roledata->name = get_string('multipleroles','role');
987 $roledata->users = array();
988 $roles['*'] = $roledata;
e254aa34 989
1c7a2f84
PS
990 $roledata = new stdClass();
991 $roledata->name = get_string('noroles','role');
992 $roledata->users = array();
993 $roles[0] = $roledata;
994
e254aa34 995 // Now we rearrange the data to store users by role
dfdaabd6 996 foreach ($users as $userid=>$userdata) {
997 $rolecount = count($userdata->roles);
1c7a2f84
PS
998 if ($rolecount == 0) {
999 // does not have any roles
1000 $roleid = 0;
1001 } else if($rolecount > 1) {
dfdaabd6 1002 $roleid = '*';
e254aa34 1003 } else {
d6af3d84
MA
1004 $userrole = reset($userdata->roles);
1005 $roleid = $userrole->id;
e254aa34 1006 }
dfdaabd6 1007 $roles[$roleid]->users[$userid] = $userdata;
e254aa34 1008 }
1009
1010 // Delete roles not used
dfdaabd6 1011 foreach ($roles as $key=>$roledata) {
1012 if (count($roledata->users)===0) {
e254aa34 1013 unset($roles[$key]);
1014 }
1015 }
1016
1017 // Return list of roles containing their users
1018 return $roles;
1019}
9c1561ef
MG
1020
1021/**
1022 * Synchronises enrolments with the group membership
1023 *
1024 * Designed for enrolment methods provide automatic synchronisation between enrolled users
1025 * and group membership, such as enrol_cohort and enrol_meta .
1026 *
1027 * @param string $enrolname name of enrolment method without prefix
1028 * @param int $courseid course id where sync needs to be performed (0 for all courses)
1029 * @param string $gidfield name of the field in 'enrol' table that stores group id
1030 * @return array Returns the list of removed and added users. Each record contains fields:
1031 * userid, enrolid, courseid, groupid, groupname
1032 */
1033function groups_sync_with_enrolment($enrolname, $courseid = 0, $gidfield = 'customint2') {
1034 global $DB;
1035 $onecourse = $courseid ? "AND e.courseid = :courseid" : "";
1036 $params = array(
1037 'enrolname' => $enrolname,
1038 'component' => 'enrol_'.$enrolname,
1039 'courseid' => $courseid
1040 );
1041
1042 $affectedusers = array(
1043 'removed' => array(),
1044 'added' => array()
1045 );
1046
1047 // Remove invalid.
1048 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1049 FROM {groups_members} gm
1050 JOIN {groups} g ON (g.id = gm.groupid)
1051 JOIN {enrol} e ON (e.enrol = :enrolname AND e.courseid = g.courseid $onecourse)
1052 JOIN {user_enrolments} ue ON (ue.userid = gm.userid AND ue.enrolid = e.id)
1053 WHERE gm.component=:component AND gm.itemid = e.id AND g.id <> e.{$gidfield}";
1054
1055 $rs = $DB->get_recordset_sql($sql, $params);
1056 foreach ($rs as $gm) {
1057 groups_remove_member($gm->groupid, $gm->userid);
1058 $affectedusers['removed'][] = $gm;
1059 }
1060 $rs->close();
1061
1062 // Add missing.
1063 $sql = "SELECT ue.userid, ue.enrolid, e.courseid, g.id AS groupid, g.name AS groupname
1064 FROM {user_enrolments} ue
1065 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrolname $onecourse)
1066 JOIN {groups} g ON (g.courseid = e.courseid AND g.id = e.{$gidfield})
1067 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0)
1068 LEFT JOIN {groups_members} gm ON (gm.groupid = g.id AND gm.userid = ue.userid)
1069 WHERE gm.id IS NULL";
1070
1071 $rs = $DB->get_recordset_sql($sql, $params);
1072 foreach ($rs as $ue) {
1073 groups_add_member($ue->groupid, $ue->userid, 'enrol_'.$enrolname, $ue->enrolid);
1074 $affectedusers['added'][] = $ue;
1075 }
1076 $rs->close();
1077
1078 return $affectedusers;
53a2405c 1079}