MDL-39959: Replace Legacy events - Groups
[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);
329 $event->set_legacy_eventdata($data);
330 $event->trigger();
2942a5cd 331
332 return $id;
f16fa0a3 333}
334
e88dd876
PS
335/**
336 * Update the group icon from form data
4d8e2417
AG
337 *
338 * @param stdClass $group group information
339 * @param stdClass $data
340 * @param stdClass $editform
e88dd876
PS
341 */
342function groups_update_group_icon($group, $data, $editform) {
343 global $CFG, $DB;
344 require_once("$CFG->libdir/gdlib.php");
345
346 $fs = get_file_storage();
bf0f06b1 347 $context = context_course::instance($group->courseid, MUST_EXIST);
e88dd876
PS
348
349 //TODO: it would make sense to allow picture deleting too (skodak)
689096bc
PS
350 if ($iconfile = $editform->save_temp_file('imagefile')) {
351 if (process_new_icon($context, 'group', 'icon', $group->id, $iconfile)) {
352 $DB->set_field('groups', 'picture', 1, array('id'=>$group->id));
353 $group->picture = 1;
354 } else {
355 $fs->delete_area_files($context->id, 'group', 'icon', $group->id);
356 $DB->set_field('groups', 'picture', 0, array('id'=>$group->id));
357 $group->picture = 0;
e88dd876 358 }
689096bc
PS
359 @unlink($iconfile);
360 // Invalidate the group data as we've updated the group record.
361 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
e88dd876
PS
362 }
363}
364
f16fa0a3 365/**
366 * Update group
4d8e2417
AG
367 *
368 * @param stdClass $data group properties (with magic quotes)
369 * @param stdClass $editform
e88dd876 370 * @param array $editoroptions
4d8e2417 371 * @return bool true or exception
ddff2fa8 372 */
e88dd876 373function groups_update_group($data, $editform = false, $editoroptions = false) {
dfdaabd6 374 global $CFG, $DB;
e88dd876 375
bf0f06b1 376 $context = context_course::instance($data->courseid);
ddff2fa8 377
378 $data->timemodified = time();
dfdaabd6 379 $data->name = trim($data->name);
74b714df
ARN
380 if (isset($data->idnumber)) {
381 $data->idnumber = trim($data->idnumber);
382 if (($existing = groups_get_group_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
383 throw new moodle_exception('idnumbertaken');
384 }
385 }
8bdc9cac 386
e88dd876
PS
387 if ($editform and $editoroptions) {
388 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $context, 'group', 'description', $data->id);
8bdc9cac
SH
389 }
390
b25263ff 391 $DB->update_record('groups', $data);
2942a5cd 392
e17dbeeb
SH
393 // Invalidate the group data.
394 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
395
e88dd876
PS
396 $group = $DB->get_record('groups', array('id'=>$data->id));
397
b25263ff 398 if ($editform) {
e88dd876 399 groups_update_group_icon($group, $data, $editform);
ddff2fa8 400 }
401
861b0510
FM
402 // Trigger group event.
403 $params = array(
404 'context' => $context,
405 'objectid' => $group->id
406 );
407 $event = \core\event\group_updated::create($params);
408 $event->add_record_snapshot('groups', $group);
409 $event->trigger();
b25263ff 410
411 return true;
ddff2fa8 412}
413
f16fa0a3 414/**
415 * Update grouping
4d8e2417
AG
416 *
417 * @param stdClass $data grouping properties (with magic quotes)
418 * @param array $editoroptions
419 * @return bool true or exception
f16fa0a3 420 */
8bdc9cac 421function groups_update_grouping($data, $editoroptions=null) {
dfdaabd6 422 global $DB;
f16fa0a3 423 $data->timemodified = time();
dfdaabd6 424 $data->name = trim($data->name);
74b714df
ARN
425 if (isset($data->idnumber)) {
426 $data->idnumber = trim($data->idnumber);
427 if (($existing = groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) && $existing->id != $data->id) {
428 throw new moodle_exception('idnumbertaken');
429 }
430 }
8bdc9cac 431 if ($editoroptions !== null) {
64f93798 432 $data = file_postupdate_standard_editor($data, 'description', $editoroptions, $editoroptions['context'], 'grouping', 'description', $data->id);
8bdc9cac 433 }
b25263ff 434 $DB->update_record('groupings', $data);
e17dbeeb
SH
435
436 // Invalidate the group data.
437 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
438
861b0510
FM
439 // Trigger group event.
440 $params = array(
441 'context' => context_course::instance($data->courseid),
442 'objectid' => $data->id
443 );
444 $event = \core\event\grouping_updated::create($params);
445 $event->set_legacy_eventdata($data);
446 $event->trigger();
b25263ff 447
448 return true;
f16fa0a3 449}
450
ddff2fa8 451/**
452 * Delete a group best effort, first removing members and links with courses and groupings.
453 * Removes group avatar too.
4d8e2417 454 *
2942a5cd 455 * @param mixed $grouporid The id of group to delete or full group object
4d8e2417 456 * @return bool True if deletion was successful, false otherwise
ddff2fa8 457 */
2942a5cd 458function groups_delete_group($grouporid) {
b7e8cfb6 459 global $CFG, $DB;
460 require_once("$CFG->libdir/gdlib.php");
ddff2fa8 461
2942a5cd 462 if (is_object($grouporid)) {
463 $groupid = $grouporid->id;
464 $group = $grouporid;
465 } else {
466 $groupid = $grouporid;
467 if (!$group = $DB->get_record('groups', array('id'=>$groupid))) {
9a0df45a 468 //silently ignore attempts to delete missing already deleted groups ;-)
469 return true;
2942a5cd 470 }
ddff2fa8 471 }
472
0b5a80a1 473 // delete group calendar events
dfdaabd6 474 $DB->delete_records('event', array('groupid'=>$groupid));
ddff2fa8 475 //first delete usage in groupings_groups
dfdaabd6 476 $DB->delete_records('groupings_groups', array('groupid'=>$groupid));
ddff2fa8 477 //delete members
dfdaabd6 478 $DB->delete_records('groups_members', array('groupid'=>$groupid));
ddff2fa8 479 //group itself last
b25263ff 480 $DB->delete_records('groups', array('id'=>$groupid));
8bdc9cac
SH
481
482 // Delete all files associated with this group
bf0f06b1 483 $context = context_course::instance($group->courseid);
8bdc9cac 484 $fs = get_file_storage();
e88dd876
PS
485 $fs->delete_area_files($context->id, 'group', 'description', $groupid);
486 $fs->delete_area_files($context->id, 'group', 'icon', $groupid);
8bdc9cac 487
e17dbeeb
SH
488 // Invalidate the grouping cache for the course
489 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($group->courseid));
490
861b0510
FM
491 // Trigger group event.
492 $params = array(
493 'context' => $context,
494 'objectid' => $groupid
495 );
496 $event = \core\event\group_deleted::create($params);
497 $event->add_record_snapshot('groups', $group);
498 $event->trigger();
2942a5cd 499
b25263ff 500 return true;
ddff2fa8 501}
502
f16fa0a3 503/**
504 * Delete grouping
4d8e2417 505 *
16ef46e7 506 * @param int $groupingorid
f16fa0a3 507 * @return bool success
508 */
2942a5cd 509function groups_delete_grouping($groupingorid) {
dfdaabd6 510 global $DB;
511
2942a5cd 512 if (is_object($groupingorid)) {
513 $groupingid = $groupingorid->id;
514 $grouping = $groupingorid;
515 } else {
516 $groupingid = $groupingorid;
517 if (!$grouping = $DB->get_record('groupings', array('id'=>$groupingorid))) {
9a0df45a 518 //silently ignore attempts to delete missing already deleted groupings ;-)
519 return true;
2942a5cd 520 }
ddff2fa8 521 }
522
523 //first delete usage in groupings_groups
dfdaabd6 524 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid));
ddff2fa8 525 // remove the default groupingid from course
dfdaabd6 526 $DB->set_field('course', 'defaultgroupingid', 0, array('defaultgroupingid'=>$groupingid));
ddff2fa8 527 // remove the groupingid from all course modules
dfdaabd6 528 $DB->set_field('course_modules', 'groupingid', 0, array('groupingid'=>$groupingid));
ddff2fa8 529 //group itself last
b25263ff 530 $DB->delete_records('groupings', array('id'=>$groupingid));
8bdc9cac 531
bf0f06b1 532 $context = context_course::instance($grouping->courseid);
8bdc9cac 533 $fs = get_file_storage();
64f93798 534 $files = $fs->get_area_files($context->id, 'grouping', 'description', $groupingid);
8bdc9cac
SH
535 foreach ($files as $file) {
536 $file->delete();
537 }
538
e17dbeeb
SH
539 // Invalidate the grouping cache for the course
540 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($grouping->courseid));
541
861b0510
FM
542 // Trigger group event.
543 $params = array(
544 'context' => $context,
545 'objectid' => $groupingid
546 );
547 $event = \core\event\grouping_deleted::create($params);
548 $event->add_record_snapshot('groupings', $grouping);
549 $event->trigger();
2942a5cd 550
b25263ff 551 return true;
ddff2fa8 552}
553
f16fa0a3 554/**
ffc670d9 555 * Remove all users (or one user) from all groups in course
4d8e2417 556 *
f16fa0a3 557 * @param int $courseid
ffc670d9 558 * @param int $userid 0 means all users
f16fa0a3 559 * @param bool $showfeedback
560 * @return bool success
561 */
ffc670d9 562function groups_delete_group_members($courseid, $userid=0, $showfeedback=false) {
a1c54f7a 563 global $DB, $OUTPUT;
ddff2fa8 564
ffc670d9 565 if (is_bool($userid)) {
566 debugging('Incorrect userid function parameter');
567 return false;
568 }
569
861b0510
FM
570 // Select * so that the function groups_remove_member() gets the whole record.
571 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
572 foreach ($groups as $group) {
573 if ($userid) {
574 $userids = array($userid);
575 } else {
576 $userids = $DB->get_fieldset_select('groups_members', 'userid', 'groupid = :groupid', array('groupid' => $group->id));
577 }
ffc670d9 578
861b0510
FM
579 foreach ($userids as $id) {
580 groups_remove_member($group, $id);
581 }
ffc670d9 582 }
583
861b0510
FM
584 // TODO MDL-41312 Remove events_trigger_legacy('groups_members_removed').
585 // This event is kept here for backwards compatibility, because it cannot be
586 // translated to a new event as it is wrong.
ace9051c 587 $eventdata = new stdClass();
ffc670d9 588 $eventdata->courseid = $courseid;
589 $eventdata->userid = $userid;
861b0510 590 events_trigger_legacy('groups_members_removed', $eventdata);
2942a5cd 591
ddff2fa8 592 if ($showfeedback) {
16ef46e7 593 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupmembers', 'group'), 'notifysuccess');
ddff2fa8 594 }
595
596 return true;
597}
598
0b5a80a1 599/**
600 * Remove all groups from all groupings in course
4d8e2417 601 *
0b5a80a1 602 * @param int $courseid
603 * @param bool $showfeedback
604 * @return bool success
605 */
606function groups_delete_groupings_groups($courseid, $showfeedback=false) {
a1c54f7a 607 global $DB, $OUTPUT;
0b5a80a1 608
dfdaabd6 609 $groupssql = "SELECT id FROM {groups} g WHERE g.courseid = ?";
861b0510
FM
610 $results = $DB->get_recordset_select('groupings_groups', "groupid IN ($groupssql)",
611 array($courseid), '', 'groupid, groupingid');
612
613 foreach ($results as $result) {
614 groups_unassign_grouping($result->groupingid, $result->groupid, false);
615 }
0b5a80a1 616
e17dbeeb
SH
617 // Invalidate the grouping cache for the course
618 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
619
861b0510
FM
620 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_groups_removed').
621 // This event is kept here for backwards compatibility, because it cannot be
622 // translated to a new event as it is wrong.
623 events_trigger_legacy('groups_groupings_groups_removed', $courseid);
2942a5cd 624
16ef46e7 625 // no need to show any feedback here - we delete usually first groupings and then groups
0b5a80a1 626
627 return true;
628}
629
f16fa0a3 630/**
631 * Delete all groups from course
4d8e2417 632 *
f16fa0a3 633 * @param int $courseid
634 * @param bool $showfeedback
635 * @return bool success
636 */
ddff2fa8 637function groups_delete_groups($courseid, $showfeedback=false) {
a1c54f7a 638 global $CFG, $DB, $OUTPUT;
ddff2fa8 639
861b0510
FM
640 $groups = $DB->get_recordset('groups', array('courseid' => $courseid));
641 foreach ($groups as $group) {
642 groups_delete_group($group);
643 }
2942a5cd 644
e17dbeeb
SH
645 // Invalidate the grouping cache for the course
646 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
647
861b0510
FM
648 // TODO MDL-41312 Remove events_trigger_legacy('groups_groups_deleted').
649 // This event is kept here for backwards compatibility, because it cannot be
650 // translated to a new event as it is wrong.
651 events_trigger_legacy('groups_groups_deleted', $courseid);
2942a5cd 652
ddff2fa8 653 if ($showfeedback) {
16ef46e7 654 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groups', 'group'), 'notifysuccess');
ddff2fa8 655 }
656
657 return true;
658}
659
f16fa0a3 660/**
661 * Delete all groupings from course
4d8e2417 662 *
f16fa0a3 663 * @param int $courseid
664 * @param bool $showfeedback
665 * @return bool success
666 */
ddff2fa8 667function groups_delete_groupings($courseid, $showfeedback=false) {
a1c54f7a 668 global $DB, $OUTPUT;
ddff2fa8 669
861b0510
FM
670 $groupings = $DB->get_recordset_select('groupings', 'courseid = ?', array($courseid));
671 foreach ($groupings as $grouping) {
672 groups_delete_grouping($grouping);
673 }
8bdc9cac 674
861b0510 675 // Invalidate the grouping cache for the course.
e17dbeeb
SH
676 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
677
861b0510
FM
678 // TODO MDL-41312 Remove events_trigger_legacy('groups_groupings_deleted').
679 // This event is kept here for backwards compatibility, because it cannot be
680 // translated to a new event as it is wrong.
681 events_trigger_legacy('groups_groupings_deleted', $courseid);
2942a5cd 682
ddff2fa8 683 if ($showfeedback) {
16ef46e7 684 echo $OUTPUT->notification(get_string('deleted').' - '.get_string('groupings', 'group'), 'notifysuccess');
ddff2fa8 685 }
686
687 return true;
688}
689
690/* =================================== */
691/* various functions used by groups UI */
692/* =================================== */
693
e254aa34 694/**
695 * Obtains a list of the possible roles that group members might come from,
df997f84 696 * on a course. Generally this includes only profile roles.
4d8e2417
AG
697 *
698 * @param context $context Context of course
e254aa34 699 * @return Array of role ID integers, or false if error/none.
700 */
701function groups_get_possible_roles($context) {
df997f84
PS
702 $roles = get_profile_roles($context);
703 return array_keys($roles);
acf000b0 704}
705
706
707/**
708 * Gets potential group members for grouping
4d8e2417 709 *
acf000b0 710 * @param int $courseid The id of the course
711 * @param int $roleid The role to select users from
92343cd2 712 * @param int $cohortid restrict to cohort id
64fa9aa7 713 * @param string $orderby The column to sort users by
acf000b0 714 * @return array An array of the users
715 */
92343cd2 716function groups_get_potential_members($courseid, $roleid = null, $cohortid = null, $orderby = 'lastname ASC, firstname ASC') {
4454447d 717 global $DB;
f16fa0a3 718
bf0f06b1 719 $context = context_course::instance($courseid);
acf000b0 720
4f0c2d00 721 list($esql, $params) = get_enrolled_sql($context);
64f93798 722
acf000b0 723 if ($roleid) {
4e829d48
MN
724 // We are looking for all users with this role assigned in this context or higher.
725 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
726
727 $params = array_merge($params, $relatedctxparams, array('roleid' => $roleid));
4f0c2d00
PS
728 $where = "WHERE u.id IN (SELECT userid
729 FROM {role_assignments}
4e829d48 730 WHERE roleid = :roleid AND contextid $relatedctxsql)";
acf000b0 731 } else {
4f0c2d00 732 $where = "";
acf000b0 733 }
f16fa0a3 734
92343cd2 735 if ($cohortid) {
d490ca81
PS
736 $cohortjoin = "JOIN {cohort_members} cm ON (cm.userid = u.id AND cm.cohortid = :cohortid)";
737 $params['cohortid'] = $cohortid;
92343cd2
PS
738 } else {
739 $cohortjoin = "";
740 }
741
dfdaabd6 742 $sql = "SELECT u.id, u.username, u.firstname, u.lastname, u.idnumber
743 FROM {user} u
4f0c2d00 744 JOIN ($esql) e ON e.id = u.id
92343cd2 745 $cohortjoin
4f0c2d00 746 $where
dfdaabd6 747 ORDER BY $orderby";
f16fa0a3 748
dfdaabd6 749 return $DB->get_records_sql($sql, $params);
f16fa0a3 750
acf000b0 751}
f3f7610c 752
acf000b0 753/**
754 * Parse a group name for characters to replace
4d8e2417 755 *
acf000b0 756 * @param string $format The format a group name will follow
757 * @param int $groupnumber The number of the group to be used in the parsed format string
758 * @return string the parsed format string
759 */
760function groups_parse_name($format, $groupnumber) {
acf000b0 761 if (strstr($format, '@') !== false) { // Convert $groupnumber to a character series
f16fa0a3 762 $letter = 'A';
763 for($i=0; $i<$groupnumber; $i++) {
764 $letter++;
acf000b0 765 }
f16fa0a3 766 $str = str_replace('@', $letter, $format);
acf000b0 767 } else {
4454447d 768 $str = str_replace('#', $groupnumber+1, $format);
acf000b0 769 }
770 return($str);
ddff2fa8 771}
f3f7610c 772
f16fa0a3 773/**
774 * Assigns group into grouping
4d8e2417 775 *
f16fa0a3 776 * @param int groupingid
777 * @param int groupid
51e8d287 778 * @param int $timeadded The time the group was added to the grouping.
e17dbeeb 779 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
b25263ff 780 * @return bool true or exception
f16fa0a3 781 */
e17dbeeb 782function groups_assign_grouping($groupingid, $groupid, $timeadded = null, $invalidatecache = true) {
dfdaabd6 783 global $DB;
784
785 if ($DB->record_exists('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid))) {
f16fa0a3 786 return true;
787 }
ace9051c 788 $assign = new stdClass();
f16fa0a3 789 $assign->groupingid = $groupingid;
dfdaabd6 790 $assign->groupid = $groupid;
51e8d287
AG
791 if ($timeadded != null) {
792 $assign->timeadded = (integer)$timeadded;
793 } else {
794 $assign->timeadded = time();
795 }
b25263ff 796 $DB->insert_record('groupings_groups', $assign);
797
e17dbeeb
SH
798 if ($invalidatecache) {
799 // Invalidate the grouping cache for the course
800 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
801 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
802 }
803
b25263ff 804 return true;
f16fa0a3 805}
806
807/**
e17dbeeb 808 * Unassigns group from grouping
4d8e2417 809 *
f16fa0a3 810 * @param int groupingid
811 * @param int groupid
e17dbeeb 812 * @param bool $invalidatecache If set to true the course group cache will be invalidated as well.
f16fa0a3 813 * @return bool success
814 */
e17dbeeb 815function groups_unassign_grouping($groupingid, $groupid, $invalidatecache = true) {
dfdaabd6 816 global $DB;
b25263ff 817 $DB->delete_records('groupings_groups', array('groupingid'=>$groupingid, 'groupid'=>$groupid));
dfdaabd6 818
e17dbeeb
SH
819 if ($invalidatecache) {
820 // Invalidate the grouping cache for the course
821 $courseid = $DB->get_field('groupings', 'courseid', array('id' => $groupingid));
822 cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($courseid));
823 }
824
b25263ff 825 return true;
f16fa0a3 826}
827
e254aa34 828/**
829 * Lists users in a group based on their role on the course.
6f5e0852 830 * Returns false if there's an error or there are no users in the group.
e254aa34 831 * Otherwise returns an array of role ID => role data, where role data includes:
832 * (role) $id, $shortname, $name
833 * $users: array of objects for each user which include the specified fields
834 * Users who do not have a role are stored in the returned array with key '-'
835 * and pseudo-role details (including a name, 'No role'). Users with multiple
836 * roles, same deal with key '*' and name 'Multiple roles'. You can find out
837 * which roles each has by looking in the $roles array of the user object.
4d8e2417 838 *
e254aa34 839 * @param int $groupid
840 * @param int $courseid Course ID (should match the group's course)
841 * @param string $fields List of fields from user table prefixed with u, default 'u.*'
9695ff81 842 * @param string $sort SQL ORDER BY clause, default (when null passed) is what comes from users_order_by_sql.
97873016 843 * @param string $extrawheretest extra SQL conditions ANDed with the existing where clause.
9695ff81 844 * @param array $whereorsortparams any parameters required by $extrawheretest (named parameters).
e254aa34 845 * @return array Complex array as described above
846 */
97873016 847function groups_get_members_by_role($groupid, $courseid, $fields='u.*',
9695ff81 848 $sort=null, $extrawheretest='', $whereorsortparams=array()) {
4e829d48 849 global $DB;
e254aa34 850
851 // Retrieve information about all users and their roles on the course or
6f5e0852 852 // parent ('related') contexts
bf0f06b1 853 $context = context_course::instance($courseid);
dfdaabd6 854
4e829d48
MN
855 // We are looking for all users with this role assigned in this context or higher.
856 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
857
97873016 858 if ($extrawheretest) {
859 $extrawheretest = ' AND ' . $extrawheretest;
860 }
861
9695ff81
TH
862 if (is_null($sort)) {
863 list($sort, $sortparams) = users_order_by_sql('u');
864 $whereorsortparams = array_merge($whereorsortparams, $sortparams);
865 }
866
c52551dc 867 $sql = "SELECT r.id AS roleid, u.id AS userid, $fields
dfdaabd6 868 FROM {groups_members} gm
869 JOIN {user} u ON u.id = gm.userid
4e829d48 870 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid $relatedctxsql)
1c7a2f84 871 LEFT JOIN {role} r ON r.id = ra.roleid
4f0c2d00 872 WHERE gm.groupid=:mgroupid
1c7a2f84 873 ".$extrawheretest."
dfdaabd6 874 ORDER BY r.sortorder, $sort";
4e829d48 875 $whereorsortparams = array_merge($whereorsortparams, $relatedctxparams, array('mgroupid' => $groupid));
9695ff81 876 $rs = $DB->get_recordset_sql($sql, $whereorsortparams);
dfdaabd6 877
878 return groups_calculate_role_people($rs, $context);
e254aa34 879}
880
881/**
882 * Internal function used by groups_get_members_by_role to handle the
883 * results of a database query that includes a list of users and possible
884 * roles on a course.
885 *
4d8e2417
AG
886 * @param moodle_recordset $rs The record set (may be false)
887 * @param int $context ID of course context
6f5e0852 888 * @return array As described in groups_get_members_by_role
e254aa34 889 */
dfdaabd6 890function groups_calculate_role_people($rs, $context) {
891 global $CFG, $DB;
892
893 if (!$rs) {
894 return array();
3540f2b3 895 }
e254aa34 896
c52551dc 897 $allroles = role_fix_names(get_all_roles($context), $context);
dfdaabd6 898
e254aa34 899 // Array of all involved roles
dfdaabd6 900 $roles = array();
e254aa34 901 // Array of all retrieved users
dfdaabd6 902 $users = array();
e254aa34 903 // Fill arrays
dfdaabd6 904 foreach ($rs as $rec) {
e254aa34 905 // Create information about user if this is a new one
dfdaabd6 906 if (!array_key_exists($rec->userid, $users)) {
e254aa34 907 // User data includes all the optional fields, but not any of the
908 // stuff we added to get the role details
1c7a2f84 909 $userdata = clone($rec);
e254aa34 910 unset($userdata->roleid);
911 unset($userdata->roleshortname);
912 unset($userdata->rolename);
913 unset($userdata->userid);
dfdaabd6 914 $userdata->id = $rec->userid;
e254aa34 915
916 // Make an array to hold the list of roles for this user
dfdaabd6 917 $userdata->roles = array();
918 $users[$rec->userid] = $userdata;
e254aa34 919 }
920 // If user has a role...
dfdaabd6 921 if (!is_null($rec->roleid)) {
e254aa34 922 // Create information about role if this is a new one
c52551dc
PS
923 if (!array_key_exists($rec->roleid, $roles)) {
924 $role = $allroles[$rec->roleid];
ace9051c 925 $roledata = new stdClass();
c52551dc
PS
926 $roledata->id = $role->id;
927 $roledata->shortname = $role->shortname;
928 $roledata->name = $role->localname;
dfdaabd6 929 $roledata->users = array();
930 $roles[$roledata->id] = $roledata;
e254aa34 931 }
932 // Record that user has role
d6af3d84 933 $users[$rec->userid]->roles[$rec->roleid] = $roles[$rec->roleid];
e254aa34 934 }
935 }
dfdaabd6 936 $rs->close();
e254aa34 937
938 // Return false if there weren't any users
1c7a2f84 939 if (count($users) == 0) {
e254aa34 940 return false;
941 }
942
943 // Add pseudo-role for multiple roles
ace9051c 944 $roledata = new stdClass();
dfdaabd6 945 $roledata->name = get_string('multipleroles','role');
946 $roledata->users = array();
947 $roles['*'] = $roledata;
e254aa34 948
1c7a2f84
PS
949 $roledata = new stdClass();
950 $roledata->name = get_string('noroles','role');
951 $roledata->users = array();
952 $roles[0] = $roledata;
953
e254aa34 954 // Now we rearrange the data to store users by role
dfdaabd6 955 foreach ($users as $userid=>$userdata) {
956 $rolecount = count($userdata->roles);
1c7a2f84
PS
957 if ($rolecount == 0) {
958 // does not have any roles
959 $roleid = 0;
960 } else if($rolecount > 1) {
dfdaabd6 961 $roleid = '*';
e254aa34 962 } else {
d6af3d84
MA
963 $userrole = reset($userdata->roles);
964 $roleid = $userrole->id;
e254aa34 965 }
dfdaabd6 966 $roles[$roleid]->users[$userid] = $userdata;
e254aa34 967 }
968
969 // Delete roles not used
dfdaabd6 970 foreach ($roles as $key=>$roledata) {
971 if (count($roledata->users)===0) {
e254aa34 972 unset($roles[$key]);
973 }
974 }
975
976 // Return list of roles containing their users
977 return $roles;
978}