/**
  * Handles the scenario where a role's capabilities change.
  *
  * Searches through each context where role is assigned, determines users assigned the role in that context,
  * Then searches through each child course of each context where the role is assigned, determines each user's capability,
  * and adds to/removes from sharepoint group.
  *
  * @param int $roleid The ID of the role that changed.
  * @param string $requiredcap The required capability.
  * @param \local\o365\rest\sharepoint $sharepoint Constructed sharepoint API client.
  * @return bool Success/Failure.
  */
 protected function do_role_capabilitychange($roleid, $requiredcap, $sharepoint)
 {
     global $DB;
     $roleassignmentssorted = [];
     $roleassignments = $DB->get_recordset('role_assignments', ['roleid' => $roleid], '', 'contextid, userid');
     $o365userids = [];
     foreach ($roleassignments as $roleassignment) {
         $roleassignmentssorted[$roleassignment->contextid][] = $roleassignment->userid;
         $o365userids[$roleassignment->userid] = (int) $roleassignment->userid;
     }
     $roleassignments->close();
     // Limit recorded users to o365 users.
     $o365userids = \local_o365\utils::limit_to_o365_users($o365userids);
     foreach ($roleassignmentssorted as $contextid => $users) {
         $users = array_intersect($users, $o365userids);
         $context = \context::instance_by_id($contextid);
         if ($context->contextlevel == CONTEXT_COURSE) {
             $this->sync_spsiteaccess_for_courses_and_users([$context->instanceid], $users, $requiredcap, $sharepoint);
         } else {
             if ($context->get_course_context(false) == false) {
                 // Get all course contexts that are children of the current context.
                 $courseids = [];
                 $sql = "SELECT ctx.instanceid\n                          FROM {context} ctx\n                         WHERE ctx.contextlevel = ? AND ctx.path LIKE ?";
                 $params = [CONTEXT_COURSE, $context->path . '/%'];
                 $childcourses = $DB->get_recordset_sql($sql, $params);
                 foreach ($childcourses as $childcourse) {
                     $courseids[] = $childcourse->instanceid;
                 }
                 $childcourses->close();
                 $this->sync_spsiteaccess_for_courses_and_users($courseids, $users, $requiredcap, $sharepoint);
             }
         }
     }
     return true;
 }