[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/group/ -> lib.php (source)

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


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1