Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
/group/ -> lib.php (source)

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 and 403]

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