+ //With post method
+ if ($request->isMethod('POST')) {
+ //Refill the fields in case the form is not valid.
+ $reset->handleRequest($request);
+
+ //With reset submitted and valid
+ if ($reset->isSubmitted() && $reset->isValid()) {
+ //Set data
+ $data = $reset->getData();
+
+ //Set password
+ $data->setPassword($this->hasher->hashPassword($data, $data->getPassword()));
+
+ //Queue user password save
+ $this->manager->persist($data);
+
+ //Flush to get the ids
+ $this->manager->flush();
+
+ //Add notice
+ $this->addFlash('notice', $this->translator->trans('Account %mail% password updated', ['%mail%' => $mail]));
+
+ //Redirect to cleanup the form
+ return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']);
+ }
+ }
+
+ //Add reset view
+ $this->config['edit']['view']['context']['reset'] = $reset->createView();
+
+ //Add google calendar array
+ $this->config['edit']['view']['context']['calendar'] = [
+ //Form by mail
+ 'form' => [],
+ //Uri to link account
+ 'link' => null,
+ //Logo
+ 'logo' => [
+ 'png' => '@RapsysAir/png/calendar.png',
+ 'svg' => '@RapsysAir/svg/calendar.svg'
+ ]
+ ];
+
+ //Set login hint
+ $this->google->setLoginHint($user->getMail());
+
+ //With user tokens
+ if (!($googleTokens = $user->getGoogleTokens())->isEmpty()) {
+ //Iterate on each google token
+ //XXX: either we finish with a valid token set or a logic exception after token removal
+ foreach($googleTokens as $googleToken) {
+ //Clear client cache before changing access token
+ //TODO: set a per token cache ?
+ $this->google->getCache()->clear();
+
+ //Set access token
+ $this->google->setAccessToken(
+ [
+ 'access_token' => $googleToken->getAccess(),
+ 'refresh_token' => $googleToken->getRefresh(),
+ 'created' => $googleToken->getCreated()->getTimestamp(),
+ 'expires_in' => $googleToken->getExpired()->getTimestamp() - (new \DateTime('now'))->getTimestamp(),
+ ]
+ );
+
+ //With expired token
+ if ($this->google->isAccessTokenExpired()) {
+ //Refresh token
+ if (($refresh = $this->google->getRefreshToken()) && ($token = $this->google->fetchAccessTokenWithRefreshToken($refresh)) && empty($token['error'])) {
+ //Set access token
+ $googleToken->setAccess($token['access_token']);
+
+ //Set expires
+ $googleToken->setExpired(new \DateTime('+'.$token['expires_in'].' second'));
+
+ //Set refresh
+ $googleToken->setRefresh($token['refresh_token']);
+
+ //Queue google token save
+ $this->manager->persist($googleToken);
+
+ //Flush to get the ids
+ $this->manager->flush();
+ //Refresh failed
+ } else {
+ //Add error in flash message
+ $this->addFlash(
+ 'error',
+ $this->translator->trans(
+ empty($token['error'])?'Unable to refresh token':'Unable to refresh token: %error%',
+ empty($token['error'])?[]:['%error%' => str_replace('_', ' ', $token['error'])]
+ )
+ );
+
+ //Set calendar mails
+ $cmails = [];
+
+ //Iterate on each google token calendars
+ foreach($googleToken->getGoogleCalendars() as $googleCalendar) {
+ //Add calendar mail
+ $cmails[] = $googleCalendar->getMail();
+
+ //Remove google token calendar
+ $this->manager->remove($googleCalendar);
+ }
+
+ //Log unlinked google token infos
+ $this->logger->emergency(
+ $this->translator->trans(
+ 'expired: mail=%mail% gmail=%gmail% cmails=%cmails% locale=%locale%',
+ [
+ '%mail%' => $googleToken->getUser()->getMail(),
+ '%gmail%' => $googleToken->getMail(),
+ '%cmails' => implode(',', $cmails),
+ '%locale%' => $request->getLocale()
+ ]
+ )
+ );
+
+ //Remove google token
+ $this->manager->remove($googleToken);
+
+ //Flush to delete it
+ $this->manager->flush();
+
+ //TODO: warn user by mail ?
+
+ //Skip to next token
+ continue;
+ }
+ }
+
+ //XXX: TODO: remove DEBUG
+ #$this->cache->delete('user.edit.calendar.'.$this->slugger->short($googleToken->getMail()));
+
+ //Retrieve calendar
+ try {
+ //Get calendars
+ $calendars = $this->cache->get(
+ //Set key to user.edit.$mail
+ ($calendarKey = 'user.edit.calendar.'.($googleShortMail = $this->slugger->short($googleMail = $googleToken->getMail()))),
+ //Fetch mail calendar list
+ function (ItemInterface $item): array {
+ //Expire after 1h
+ $item->expiresAfter(3600);
+
+ //Get google calendar service
+ $service = new \Google\Service\Calendar($this->google);
+
+ //Init calendars
+ $calendars = [];
+
+ //Init counter
+ $count = 0;
+
+ //Set page token
+ $pageToken = null;
+
+ //Iterate until next page token is null
+ do {
+ //Get token calendar list
+ //XXX: require permission to read and write events
+ $calendarList = $service->calendarList->listCalendarList(['pageToken' => $pageToken, 'minAccessRole' => 'writer', 'showHidden' => true]);
+
+ //Iterate on items
+ foreach($calendarList->getItems() as $calendarItem) {
+ //With primary calendar
+ if ($calendarItem->getPrimary()) {
+ //Add primary calendar
+ //XXX: use primary as key as described in google api documentation
+ $calendars = ['primary' => $this->translator->trans('Primary') /*$calendarItem->getSummary()*/] + $calendars;
+ //With secondary calendar
+ } else {
+ //Add secondary calendar
+ //XXX: Append counter to make sure summary is unique for later array_flip call
+ $calendars += [$calendarItem->getId() => $calendarItem->getSummary().' ('.++$count.')'];
+ }
+ }
+ } while ($pageToken = $calendarList->getNextPageToken());
+
+ //Cache calendars
+ return $calendars;
+ }
+ );
+ //Catch exception
+ } catch(\Google\Service\Exception $e) {
+ //With 401 or code
+ //XXX: see https://cloud.google.com/apis/design/errors
+ if ($e->getCode() == 401 || $e->getCode() == 403) {
+ //Add error in flash message
+ $this->addFlash(
+ 'error',
+ $this->translator->trans(
+ 'Unable to list calendars: %error%',
+ ['%error%' => $e->getMessage()]
+ )
+ );
+
+ //Set calendar mails
+ $cmails = [];
+
+ //Iterate on each google token calendars
+ foreach($googleToken->getGoogleCalendars() as $googleCalendar) {
+ //Add calendar mail
+ $cmails[] = $googleCalendar->getMail();
+
+ //Remove google token calendar
+ $this->manager->remove($googleCalendar);
+ }
+
+ //Log unlinked google token infos
+ $this->logger->emergency(
+ $this->translator->trans(
+ 'denied: mail=%mail% gmail=%gmail% cmails=%cmails% locale=%locale%',
+ [
+ '%mail%' => $googleToken->getUser()->getMail(),
+ '%gmail%' => $googleToken->getMail(),
+ '%cmails' => implode(',', $cmails),
+ '%locale%' => $request->getLocale()
+ ]
+ )
+ );
+
+ //Remove google token
+ $this->manager->remove($googleToken);
+
+ //Flush to delete it
+ $this->manager->flush();
+
+ //TODO: warn user by mail ?
+
+ //Skip to next token
+ continue;
+ }
+
+ //Throw error
+ throw new \LogicException('Calendar list failed', 0, $e);
+ }
+
+ //Set formData array
+ $formData = ['calendar' => []];
+
+ //With google calendars
+ if (!($googleCalendars = $googleToken->getGoogleCalendars())->isEmpty()) {
+ //Iterate on each google calendars
+ foreach($googleCalendars as $googleCalendar) {
+ //With existing google calendar
+ if (isset($calendars[$googleCalendar->getMail()])) {
+ //Add google calendar to form data
+ $formData['calendar'][] = $googleCalendar->getMail();
+ } else {
+ //Remove google calendar from database
+ $this->manager->remove($googleCalendar);
+
+ //Flush to persist ids
+ $this->manager->flush();
+ }
+ }
+ }
+
+ //TODO: add feature for alerts (-30min/-1h) ?
+ //TODO: [Direct link to calendar ?][Direct link to calendar settings ?][Alerts][Remove]
+
+ //Create the CalendarType form and give the proper parameters
+ $form = $this->factory->createNamed('calendar_'.$googleShortMail, 'Rapsys\AirBundle\Form\CalendarType', $formData, [
+ //Set action to register route name and context
+ 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']),
+ //Set calendar choices
+ //XXX: unique calendar summary required by choice widget is guaranteed by appending ' (x)' to secondary calendars earlier
+ 'calendar_choices' => array_flip($calendars),
+ //Set method
+ 'method' => 'POST'
+ ]);
+
+ //With post method
+ if ($request->isMethod('POST')) {
+ //Refill the fields in case the form is not valid.
+ $form->handleRequest($request);
+
+ //With reset submitted and valid
+ if ($form->isSubmitted() && $form->isValid()) {
+ //Set data
+ $data = $form->getData();
+
+ //Refresh button
+ if (($clicked = $form->getClickedButton()->getName()) == 'refresh') {
+ //Remove calendar key
+ $this->cache->delete($calendarKey);
+
+ //Add notice
+ $this->addFlash('notice', $this->translator->trans('Account %mail% calendars updated', ['%mail%' => $googleMail]));
+ //Add button
+ } elseif ($clicked == 'add') {
+ //Get google calendar service
+ $service = new \Google\Service\Calendar($this->google);
+
+ //Add calendar
+ try {
+ //Instantiate calendar
+ $calendar = new \Google\Service\Calendar\Calendar(
+ [
+ 'summary' => $this->translator->trans($this->config['context']['site']['title']),
+ 'timeZone' => date_default_timezone_get()
+ ]
+ );
+
+ //Insert calendar
+ $service->calendars->insert($calendar);
+ //Catch exception
+ } catch(\Google\Service\Exception $e) {
+ //Throw error
+ throw new \LogicException('Calendar insert failed', 0, $e);
+ }
+
+ //Remove calendar key
+ $this->cache->delete($calendarKey);
+
+ //Add notice
+ $this->addFlash('notice', $this->translator->trans('Account %mail% calendar added', ['%mail%' => $googleMail]));
+ //Delete button
+ } elseif ($clicked == 'delete') {
+ //Get google calendar service
+ $service = new \Google\Service\Calendar($this->google);
+
+ //Remove calendar
+ try {
+ //Set site title
+ $siteTitle = $this->translator->trans($this->config['context']['site']['title']);
+
+ //Iterate on calendars
+ foreach($calendars as $calendarId => $calendarSummary) {
+ //With calendar matching site title
+ if (substr($calendarSummary, 0, strlen($siteTitle)) == $siteTitle) {
+ //Delete the calendar
+ $service->calendars->delete($calendarId);
+ }
+ }
+ //Catch exception
+ } catch(\Google\Service\Exception $e) {
+ //Throw error
+ throw new \LogicException('Calendar delete failed', 0, $e);
+ }
+
+ //Remove calendar key
+ $this->cache->delete($calendarKey);
+
+ //Add notice
+ $this->addFlash('notice', $this->translator->trans('Account %mail% calendars deleted', ['%mail%' => $googleMail]));
+ //Unlink button
+ } elseif ($clicked == 'unlink') {
+ //Iterate on each google calendars
+ foreach($googleCalendars as $googleCalendar) {
+ //Remove google calendar from database
+ $this->manager->remove($googleCalendar);
+ }
+
+ //Remove google token from database
+ $this->manager->remove($googleToken);
+
+ //Flush to persist
+ $this->manager->flush();
+
+ //Revoke access token
+ $this->google->revokeToken($googleToken->getAccess());
+
+ //With refresh token
+ if ($refresh = $googleToken->getRefresh()) {
+ //Revoke refresh token
+ $this->google->revokeToken($googleToken->getRefresh());
+ }
+
+ //Remove calendar key
+ $this->cache->delete($calendarKey);
+
+ //Add notice
+ $this->addFlash('notice', $this->translator->trans('Account %mail% calendars unlinked', ['%mail%' => $googleMail]));
+ //Submit button
+ } else {
+ //Flipped calendar data
+ $dataCalendarFlip = array_flip($data['calendar']);
+
+ //Iterate on each google calendars
+ foreach($googleCalendars as $googleCalendar) {
+ //Without calendar in flipped data
+ if (!isset($dataCalendarFlip[$googleCalendarMail = $googleCalendar->getMail()])) {
+ //Remove google calendar from database
+ $this->manager->remove($googleCalendar);
+ //With calendar in flipped data
+ } else {
+ //Remove google calendar from calendar data
+ unset($data['calendar'][$dataCalendarFlip[$googleCalendarMail]]);
+ }
+ }
+
+ //Iterate on remaining calendar data
+ foreach($data['calendar'] as $googleCalendarMail) {
+ //Create new google calendar
+ //XXX: remove trailing ' (x)' from summary
+ $googleCalendar = new GoogleCalendar($googleToken, $googleCalendarMail, preg_replace('/ \([0-9]\)$/', '', $calendars[$googleCalendarMail]));
+
+ //Queue google calendar save
+ $this->manager->persist($googleCalendar);
+ }
+
+ //Flush to persist ids
+ $this->manager->flush();
+
+ //Add notice
+ $this->addFlash('notice', $this->translator->trans('Account %mail% calendars updated', ['%mail%' => $googleMail]));
+ }
+
+ //Redirect to cleanup the form
+ return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']);
+ }
+ }
+
+ //Add form view
+ $this->config['edit']['view']['context']['calendar']['form'][$googleToken->getMail()] = $form->createView();
+ }
+ }
+
+ //Add google calendar auth url
+ $this->config['edit']['view']['context']['calendar']['link'] = $this->google->createAuthUrl();