diff --git a/classes/feature/calsync/main.php b/classes/feature/calsync/main.php index bb9b2fcdb..33b085f0a 100644 --- a/classes/feature/calsync/main.php +++ b/classes/feature/calsync/main.php @@ -72,6 +72,16 @@ public function construct_calendar_api($muserid, $systemfallback = true) { $tokenresource = unified::get_tokenresource(); $token = token::instance($muserid, $tokenresource, $this->clientdata, $this->httpclient); + if ($token && $token->is_expired()) { + try { + if (!$token->refresh()) { + $token = null; + } + } catch (moodle_exception $e) { + // Token fails to refresh, so we'll use application token. + $token = null; + } + } if (empty($token) && $systemfallback === true) { $token = utils::get_application_token($tokenresource, $this->clientdata, $this->httpclient); } @@ -393,7 +403,7 @@ public function create_outlook_event_from_moodle_event($moodleventid) { */ public function get_calendars() { global $USER; - $apiclient = $this->construct_calendar_api($USER->id, false); + $apiclient = $this->construct_calendar_api($USER->id); $o365upn = utils::get_o365_upn($USER->id); if ($o365upn) { return $apiclient->get_calendars($o365upn); @@ -411,7 +421,7 @@ public function get_calendars() { * @return array Array of events. */ public function get_events($muserid, $o365calid, $since = null) { - $apiclient = $this->construct_calendar_api($muserid, false); + $apiclient = $this->construct_calendar_api($muserid); $o365upn = utils::get_o365_upn($muserid); $events = []; @@ -562,7 +572,7 @@ protected function group_first_last_name($groupname) { */ public function create_outlook_calendar($name) { global $USER; - $apiclient = $this->construct_calendar_api($USER->id, false); + $apiclient = $this->construct_calendar_api($USER->id); $o365upn = utils::get_o365_upn($USER->id); if ($o365upn) { return $apiclient->create_calendar($name, $o365upn);