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