die('The session state did not match.');
    }
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
    header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}
// Check if access token successfully acquired
if ($client->getAccessToken()) {
    try {
        // This code will create a new, private playlist in the authorized user's channel and
        // add the video to the playlist.
        // 1. Create the PlaylistSnippet and add the required data.
        $playlistSnippet = new Google_PlaylistSnippet();
        $playlistSnippet->setTitle('Test Playlist  ' . date("Y-m-d H:i:s"));
        $playlistSnippet->setDescription('A private playlist created with the YouTube API v3');
        // 2. Create playlist status describing the privacy setting.
        $playlistStatus = new Google_PlaylistStatus();
        $playlistStatus->setPrivacyStatus('private');
        // 3. Create a playlist insert request with snippet and status.
        $youTubePlaylist = new Google_Playlist();
        $youTubePlaylist->setSnippet($playlistSnippet);
        $youTubePlaylist->setStatus($playlistStatus);
        // 4. Execute the request and return an object containing information about the new playlist
        $playlistResponse = $youtube->playlists->insert('snippet,status', $youTubePlaylist, array());
        // 5. Add the video to the playlist
        //   a. Create a resource id with video id and kind.
        $resourceId = new Google_ResourceId();
        $resourceId->setVideoId('SZj6rAYkYOg');
 public function sync($youtubeUsername, $videoId, $currentVideoPlaylists, $newVideoPlaylists)
 {
     $playlistsLoaded = false;
     for ($i = 1; $i <= $this->_playlistLoadAttemptsLimit; $i++) {
         try {
             KalturaLog::debug('Trying to load all playlists, attempt ' . $i);
             $this->loadPlaylistsForChannel($youtubeUsername);
             $playlistsLoaded = true;
             break;
         } catch (Exception $ex) {
             KalturaLog::err('Failed to load all playlists on attempt ' . $i);
             KalturaLog::debug($ex);
         }
     }
     if (!$playlistsLoaded) {
         KalturaLog::err('An error occurred while loading playlists, sync playlists proccess cannot proceed');
         return $currentVideoPlaylists;
     }
     KalturaLog::info('Current playlists: ' . $currentVideoPlaylists);
     KalturaLog::info('New playlists: ' . $newVideoPlaylists);
     $currentPlaylistsArray = explode(',', $currentVideoPlaylists);
     $newPlaylistsArray = explode(',', $newVideoPlaylists);
     sort($currentPlaylistsArray);
     sort($newPlaylistsArray);
     foreach ($currentPlaylistsArray as &$tempPlaylist) {
         $tempPlaylist = trim($tempPlaylist);
     }
     foreach ($newPlaylistsArray as &$tempPlaylist) {
         $tempPlaylist = trim($tempPlaylist);
     }
     if (count($currentVideoPlaylists) == 0 && count($newVideoPlaylists) == 0) {
         return null;
     }
     if (var_export($currentPlaylistsArray, true) === var_export($newPlaylistsArray, true)) {
         // nothing changed
         return null;
     }
     /**
      * used to store the playlists that were really linked to an entry,
      * if an api error occurs, the playlist will not be added
      */
     $currentPlaylistsReal = array();
     // playlists we need to add the video to
     foreach ($newPlaylistsArray as $playlist) {
         if (!$playlist) {
             continue;
         }
         if (!in_array($playlist, $currentPlaylistsArray)) {
             $playlistId = $this->getPlaylistIdByTitle($playlist);
             if (!$playlistId) {
                 // create the playlist
                 $playlistSnippet = new Google_PlaylistSnippet();
                 $playlistSnippet->setChannelId($this->_channelId);
                 $playlistSnippet->setTitle($playlist);
                 $googlePlaylist = new Google_Playlist();
                 $googlePlaylist->setSnippet($playlistSnippet);
                 try {
                     $playlistResponse = $this->_youtubeService->playlists->insert('snippet', $googlePlaylist);
                 } catch (Exception $ex) {
                     KalturaLog::err('Failed to create new playlist ' . $playlist);
                     KalturaLog::debug($ex);
                     continue;
                 }
                 $playlistId = $playlistResponse['id'];
             }
             $playlistItem = new Google_PlaylistItem();
             $contentDetails = new Google_PlaylistItemContentDetails();
             $contentDetails->setVideoId($videoId);
             $playlistItemSnippet = new Google_PlaylistItemSnippet();
             $playlistItemSnippet->setPlaylistId($playlistId);
             $resourceId = new Google_ResourceId();
             $resourceId->setKind('youtube#video');
             $resourceId->setVideoId($videoId);
             $playlistItemSnippet->setResourceId($resourceId);
             $playlistItem->setSnippet($playlistItemSnippet);
             try {
                 $this->_youtubeService->playlistItems->insert('snippet', $playlistItem);
             } catch (Exception $ex) {
                 KalturaLog::err('Failed to insert playlist item for playlist ' . $playlist);
                 KalturaLog::debug($ex);
                 continue;
             }
             $currentPlaylistsReal[] = $playlist;
         } else {
             $currentPlaylistsReal[] = $playlist;
         }
     }
     // playlists we need to remove the video from
     foreach ($currentPlaylistsArray as $playlist) {
         if (!$playlist) {
             continue;
         }
         if (!in_array($playlist, $newPlaylistsArray)) {
             $playlistId = $this->getPlaylistIdByTitle($playlist);
             if (!$playlistId) {
                 continue;
             }
             $playlistItems = null;
             try {
                 $playlistItems = $this->_youtubeService->playlistItems->listPlaylistItems('snippet', array('playlistId' => $playlistId));
             } catch (Exception $ex) {
                 // failed to list playlists items, we need to keep that playlist in our records
                 $currentPlaylistsReal[] = $playlist;
                 KalturaLog::err('Failed to list playlist items for playlist ' . $playlist);
                 KalturaLog::debug($ex);
                 continue;
             }
             if (!isset($playlistItems['items']) || !count($playlistItems['items'])) {
                 continue;
             }
             foreach ($playlistItems['items'] as $playlistItem) {
                 if (!isset($playlistItem['snippet']['resourceId']['videoId'])) {
                     continue;
                 }
                 $playlistItemVideoId = $playlistItem['snippet']['resourceId']['videoId'];
                 if ($playlistItemVideoId == $videoId) {
                     try {
                         $this->_youtubeService->playlistItems->delete($playlistItem['id']);
                     } catch (Exception $ex) {
                         // playlist item could not be deleted, we need to keep that playlist in our records as well
                         $currentPlaylistsReal[] = $playlist;
                         KalturaLog::err('Failed to delete playlist item for playlist ' . $playlist);
                         KalturaLog::debug($ex);
                     }
                 }
             }
         }
     }
     return $currentPlaylistsReal;
 }