/**
  * Returns an authorized API client.
  * @return Google_Client the authorized client object
  */
 private function getGoogleApiClient()
 {
     $client = new Google_Client();
     $client->setApplicationName($this->CFG['GOOGLE_API_APPLICATION_NAME']);
     $client->setScopes(Google_Service_Calendar::CALENDAR);
     $client->setAuthConfigFile($this->CFG['GOOGLE_API_CLIENT_SECRET_PATH']);
     $client->setAccessType('offline');
     // Load previously authorized credentials from a file.
     $credentialsPath = $this->CFG['GOOGLE_API_CREDENTIALS_PATH'];
     if (file_exists($credentialsPath)) {
         $accessToken = file_get_contents($credentialsPath);
     } else {
         // Request authorization from the user.
         $authUrl = $client->createAuthUrl();
         printf("Open the following link in your browser:\n%s\n", $authUrl);
         print 'Enter verification code: ';
         $authCode = trim(fgets(STDIN));
         // Exchange authorization code for an access token.
         $accessToken = $client->authenticate($authCode);
         // Store the credentials to disk.
         if (!file_exists(dirname($credentialsPath))) {
             mkdir(dirname($credentialsPath), 0700, true);
         }
         file_put_contents($credentialsPath, $accessToken);
         printf("Credentials saved to %s\n", $credentialsPath);
     }
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($credentialsPath, $client->getAccessToken());
     }
     return $client;
 }
 public function refreshToken($accessToken)
 {
     $this->_googleClient->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($this->_googleClient->isAccessTokenExpired()) {
         $this->_googleClient->refreshToken($this->_googleClient->getRefreshToken());
     }
     return $this->_googleClient->getAccessToken();
 }
Example #3
1
 public function add_google_client()
 {
     $auth_config = $this->get_auth_config();
     if (!empty($auth_config)) {
         try {
             $client = new Google_Client();
             $client->setAuthConfig($this->get_auth_config());
             $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
             $client->setAccessType('offline');
             $token = $this->get_token();
             if ($token) {
                 $client->setAccessToken($token);
             }
             if ($client->isAccessTokenExpired()) {
                 $refresh_token = $this->get_refresh_token();
                 if ($refresh_token) {
                     $client->refreshToken($refresh_token);
                     $this->update_token($client->getAccessToken());
                 }
             }
             $this->client = $client;
             $this->service = new Google_Service_Analytics($this->client);
         } catch (Exception $e) {
             $message = 'Google Analytics Error[' . $e->getCode() . ']: ' . $e->getMessage();
             $this->disconnect($message);
             error_log($message, E_USER_ERROR);
             return;
         }
     }
 }
 /**
  * @throws MissingConfigurationException
  * @return \Google_Client
  */
 public function create()
 {
     $client = new \Google_Client();
     $requiredAuthenticationSettings = array('applicationName', 'clientId', 'clientSecret', 'developerKey');
     foreach ($requiredAuthenticationSettings as $key) {
         if (!isset($this->authenticationSettings[$key])) {
             throw new MissingConfigurationException(sprintf('Missing setting "TYPO3.Neos.GoogleAnalytics.authentication.%s"', $key), 1415796352);
         }
     }
     $client->setApplicationName($this->authenticationSettings['applicationName']);
     $client->setClientId($this->authenticationSettings['clientId']);
     $client->setClientSecret($this->authenticationSettings['clientSecret']);
     $client->setDeveloperKey($this->authenticationSettings['developerKey']);
     $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
     $client->setAccessType('offline');
     $accessToken = $this->tokenStorage->getAccessToken();
     if ($accessToken !== NULL) {
         $client->setAccessToken($accessToken);
         if ($client->isAccessTokenExpired()) {
             $refreshToken = $this->tokenStorage->getRefreshToken();
             $client->refreshToken($refreshToken);
         }
     }
     return $client;
 }
Example #5
0
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET);
    $client->setAccessType('offline');
    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIAL_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n\n\t%s\n\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        // Exchange authorization code for an access token.
        $accessToken = $client->authenticate($authCode);
        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}
 /**
  * Permet de reconnecté le compte Google si l'access_token n'est plus valide
  * @param User $user
  * @param bool $saveInSession
  * @return bool
  */
 protected function refreshConnect(User $user, $saveInSession = true)
 {
     $response = true;
     $session = new Session();
     $refreshToken = $user->getGoogleRefreshToken();
     if (null != $refreshToken) {
         try {
             $this->client->refreshToken($refreshToken);
             $newAccessToken = $this->getAccessToken();
             if ($saveInSession) {
                 $session->set('access_token', $newAccessToken);
             }
             $this->setAccessToken($newAccessToken);
         } catch (\Exception $e) {
             $response = false;
         }
     } else {
         $response = false;
     }
     if ($response === false) {
         // revoked access
         $this->disconnect($user);
     }
     return $response;
 }
Example #7
0
 function onNextendYoutube(&$google, &$youtube)
 {
     $config = new NextendData();
     $config->loadJson(NextendSmartSliderStorage::get(self::$_group));
     if (!class_exists('Google_Client')) {
         require_once dirname(__FILE__) . '/googleclient/Google_Client.php';
     }
     if (!class_exists('Google_YouTubeService')) {
         require_once dirname(__FILE__) . '/googleclient/contrib/Google_YouTubeService.php';
     }
     $google = new Google_Client();
     $google->setClientId($config->get('apikey', ''));
     $google->setClientSecret($config->get('apisecret', ''));
     $token = $config->get('token', null);
     if ($token) {
         $google->setAccessToken($token);
     }
     $youtube = new Google_YouTubeService($google);
     if ($google->isAccessTokenExpired()) {
         $token = json_decode($google->getAccessToken(), true);
         if (isset($token['refresh_token'])) {
             $google->refreshToken($token['refresh_token']);
             $config->set('token', $google->getAccessToken());
             NextendSmartSliderStorage::set(self::$_group, $config->toJSON());
         }
     }
 }
Example #8
0
function getClient()
{
    $config = (include __DIR__ . '/ini.php');
    $client = new Google_Client();
    $client->setApplicationName("Webkameleon");
    $client->setClientId($config['oauth2_client_id']);
    $client->setClientSecret($config['oauth2_client_secret']);
    $client->setRedirectUri($config['oauth2_redirect_uri']);
    $client->setScopes($config['oauth2_scopes']);
    $client->setState('offline');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        die($client->getAccessToken());
    } elseif (!isset($config['token'])) {
        Header('Location: ' . $client->createAuthUrl());
    } else {
        $client->setAccessToken($config['token']);
        if ($client->isAccessTokenExpired()) {
            $token = json_decode($config['token'], true);
            $client->refreshToken($token['refresh_token']);
        }
    }
    return $client;
}
 private function refreshAuthToken(\Google_Client $client)
 {
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents(CREDENTIALS_FILE, $client->getAccessToken());
     }
 }
 public function __construct()
 {
     $config_file = $_SERVER['HOME'] . '/' . self::CONFIG_FILE_NAME;
     if (file_exists($config_file)) {
         $config = json_decode(file_get_contents($config_file));
     }
     if (!$config) {
         throw new Exception(sprintf('Could not find or read the config file at ' . '%s. You can use the config.json file in the samples root as a ' . 'template.', $config_file));
     }
     $client = new Google_Client();
     $client->setApplicationName($config->applicationName);
     $client->setClientId($config->clientId);
     $client->setClientSecret($config->clientSecret);
     try {
         $client->refreshToken($config->refreshToken);
     } catch (Google_Auth_Exception $exception) {
         print str_repeat('*', 40);
         print "Your refresh token was missing or invalid, fetching a new one\n";
         $refresh_token = $this->getRefreshToken($client);
         $config->refreshToken = $refresh_token;
         file_put_contents($config_file, json_encode($config));
         print "Refresh token saved to your config file\n";
         print str_repeat('*', 40);
     }
     $this->merchant_id = $config->merchantId;
     $this->service = new Google_Service_ShoppingContent($client);
 }
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    $credentialsPath = CREDENTIALS_PATH;
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        $accessToken = $client->authenticate($authCode);
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}
 /**
  * Constructor for current class
  *
  * @param string $clientId
  * @param string $clientSecret
  * @param string $refreshToken
  * @return GMail
  */
 public static function createByParams($clientId, $clientSecret, $refreshToken)
 {
     $client = new \Google_Client();
     $client->setClientId($clientId);
     $client->setClientSecret($clientSecret);
     $client->addScope(\Google_Service_Gmail::MAIL_GOOGLE_COM);
     $client->refreshToken($refreshToken);
     return self::createByClient($client);
 }
Example #13
0
 /**
  * Load Google and Calendar Service data by Staff
  *
  * @param AB_Staff $staff
  * @return bool
  */
 public function loadByStaff(AB_Staff $staff)
 {
     $this->staff = $staff;
     if ($staff->get('google_data')) {
         try {
             $this->client->setAccessToken($staff->get('google_data'));
             if ($this->client->isAccessTokenExpired()) {
                 $this->client->refreshToken($this->client->getRefreshToken());
                 $staff->set('google_data', $this->client->getAccessToken());
                 $staff->save();
             }
             $this->service = new Google_Service_Calendar($this->client);
             return true;
         } catch (Exception $e) {
             $this->errors[] = $e->getMessage();
         }
     }
     return false;
 }
Example #14
0
 private function get_login_token()
 {
     $config = $this->config;
     $client = new Google_Client();
     $client->setClientId($config['client_id']);
     $client->setClientSecret($config['client_secret']);
     $client->setScopes($config['scope']);
     $client->refreshToken($config['refresh_token']);
     $token = $client->getAuth()->getAccessToken();
     return json_decode($token)->access_token;
 }
 public function fetchAction()
 {
     $em = $this->getDoctrine()->getEntityManager();
     // TODO move to a cron job
     // TODO move google credentials to symfony parameters file
     $configDirectories = array(__DIR__ . '/../Resources/config');
     $locator = new FileLocator($configDirectories);
     $clientSecret = $locator->locate('client_secret.json');
     $credentialsPath = $locator->locate('calendar-api-quickstart.json');
     // Get the API client and construct the service object.
     $client = new \Google_Client();
     $client->setApplicationName('Google Calendar API Quickstart');
     $client->setScopes(implode(' ', array(\Google_Service_Calendar::CALENDAR_READONLY)));
     $client->setAuthConfigFile($clientSecret);
     $client->setAccessType('offline');
     // Load previously authorized credentials from a file.
     if (file_exists($credentialsPath)) {
         $accessToken = file_get_contents($credentialsPath);
     } else {
         //TODO this should be accomplished with an error status
         return $this->render('TechlancasterWebBundle:Default:calendar.html.twig', array('message' => 'Invalid Credentials'));
     }
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($credentialsPath, $client->getAccessToken());
     }
     $service = new \Google_Service_Calendar($client);
     $calendarId = '*****@*****.**';
     $optParams = array('maxResults' => 29, 'orderBy' => 'startTime', 'singleEvents' => true, 'timeMin' => date('c'));
     $results = $service->events->listEvents($calendarId, $optParams);
     $events = array();
     $connection = $em->getConnection();
     $platform = $connection->getDatabasePlatform();
     $connection->executeUpdate($platform->getTruncateTableSQL('event', false));
     /**
      * @var $googleEvent Google_Service_Calendar_Event
      */
     foreach ($results->getItems() as $googleEvent) {
         $event = new Event();
         $event->setId($googleEvent->getId());
         $event->setDescription($googleEvent->getDescription());
         $event->setLocation($googleEvent->getLocation());
         $event->setStart(new \DateTime($googleEvent->getStart()->dateTime));
         $event->setEnd(new \DateTime($googleEvent->getEnd()->dateTime));
         $event->setSummary($googleEvent->getSummary());
         $em->persist($event);
         $events[] = $event;
     }
     $em->flush();
     return $this->render('TechlancasterWebBundle:Default:calendar.html.twig', array('message' => json_encode($events)));
 }
 public function __construct(array $options = [])
 {
     $this->_client = new \Google_Client();
     $this->_client->setClientId($options['client_id']);
     $this->_client->setClientSecret($options['client_secret']);
     touch(sys_get_temp_dir() . '/googleplay_access_token.txt');
     chmod(sys_get_temp_dir() . '/googleplay_access_token.txt', 0777);
     try {
         $this->_client->setAccessToken(file_get_contents(sys_get_temp_dir() . '/googleplay_access_token.txt'));
     } catch (\Exception $e) {
         // skip exceptions when the access token is not valid
     }
     try {
         if ($this->_client->isAccessTokenExpired()) {
             $this->_client->refreshToken($options['refresh_token']);
             file_put_contents(sys_get_temp_dir() . '/googleplay_access_token.txt', $this->_client->getAccessToken());
         }
     } catch (\Exception $e) {
         throw new RuntimeException('Failed refreshing access token - ' . $e->getMessage());
     }
     $this->_androidPublisherService = new \Google_Service_AndroidPublisher($this->_client);
 }
 /**
  * This function connect with google and return the service
  * @param ExternalCalendarUser $user
  * @return Google_Service_Calendar
  */
 private function connect_with_google_calendar($user)
 {
     $client = new Google_Client();
     $client->setAccessToken($user->getAuthPass());
     //if isAccessTokenExpired then refresh the token and store it
     if ($client->isAccessTokenExpired()) {
         $credentials = json_decode($user->getAuthPass());
         $client->refreshToken($credentials->refresh_token);
         $user->setAuthPass($client->getAccessToken());
         $user->save();
     }
     $service = new Google_Service_Calendar($client);
     return $service;
 }
Example #18
0
 /**
  * Authenticate
  * @param int $type
  * @throws Exception
  */
 public function auth($type = self::AUTH_TYPE_CMD_LINE)
 {
     if ($this->accessToken !== null) {
         // Already got an auth token
         $this->getLogger()->debug('Using existing accessToken');
         $this->client->setAccessToken($this->accessToken);
         if (!$this->client->isAccessTokenExpired()) {
             return;
         }
         $this->getLogger()->info('Existing accessToken no longer valid');
         if ($this->refreshToken !== null) {
             $this->getLogger()->debug('Using refreshToken');
             $this->client->refreshToken($this->refreshToken);
             return;
         }
     }
     switch ($type) {
         case self::AUTH_TYPE_CMD_LINE:
             $this->cmdLineAuth();
             break;
         default:
             throw new Exception('Auth Type not valid');
     }
 }
 public function createCalendarService(){
     $this->load->model('EILIB/Mdl_eilib_common_function');
     $arrClientId= $this->Mdl_eilib_common_function->getCalendarIdCilentIdService();
     $drive = new Google_Client();
     $drive->setClientId($arrClientId[0]);
     $drive->setClientSecret($arrClientId[1]);
     $drive->setRedirectUri($arrClientId[2]);
     $drive->setScopes(array($arrClientId[3],$arrClientId[4]));
     $drive->setAccessType('online');
     $authUrl = $drive->createAuthUrl();
     $refresh_token= $arrClientId[5];
     $drive->refreshToken($refresh_token);
     $cal = new Google_Service_Calendar($drive);
     return $cal;
 }
    public function createCalendarService($ClientId,$ClientSecret,$RedirectUri,$DriveScopes,$CalenderScopes,$Refresh_Token){
//create start event
        $drive = new Google_Client();
        $drive->setClientId($ClientId);
        $drive->setClientSecret($ClientSecret);
        $drive->setRedirectUri($RedirectUri);
        $drive->setScopes(array($DriveScopes,$CalenderScopes));
        $drive->setAccessType('online');
        $authUrl = $drive->createAuthUrl();
        $access_token=$drive->getAccessToken();
        $refresh_token=$Refresh_Token;
        $drive->refreshToken($refresh_token);
        $service = new Google_Service_Drive($drive);
        return $service;
    }
Example #21
0
 protected function refreshToken(Google_Client $client)
 {
     /** @var Google_Auth_OAuth2 $auth */
     $auth = $client->getAuth();
     $refreshToken = $auth->getRefreshToken();
     if ($refreshToken) {
         try {
             $client->refreshToken($refreshToken);
         } catch (Google_Auth_Exception $e) {
             $GLOBALS['log']->error($e->getMessage());
             return;
         }
         $token = $client->getAccessToken();
         $this->saveToken($token);
     }
 }
Example #22
0
 public static function getClient()
 {
     $config = self::loadConfig();
     $client = new \Google_Client();
     $client->setApplicationName('Rapid Web Google Contacts API');
     $client->setScopes(array('https://www.google.com/m8/feeds/'));
     $client->setClientId($config->clientID);
     $client->setClientSecret($config->clientSecret);
     $client->setRedirectUri($config->redirectUri);
     $client->setAccessType('offline');
     $client->setApprovalPrompt('force');
     $client->setDeveloperKey($config->developerKey);
     if (isset($config->refreshToken) && $config->refreshToken) {
         $client->refreshToken($config->refreshToken);
     }
     return $client;
 }
 /**
  * Returns an authorized API client.
  * @return \Google_Client the authorized client object
  */
 public function __construct()
 {
     $client = new \Google_Client();
     $client->setApplicationName(APPLICATION_NAME);
     $client->setScopes(SCOPES);
     $client->setAuthConfigFile(CLIENT_SECRET_PATH);
     $client->setAccessType('offline');
     if (!file_exists(CREDENTIALS_PATH)) {
         throw new \Exception('No credentials set');
     }
     $accessToken = file_get_contents(CREDENTIALS_PATH);
     $client->setAccessToken($accessToken);
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents(CREDENTIALS_PATH, $client->getAccessToken());
     }
     $this->client = $client;
     $this->service = new \Google_Service_Calendar($client);
 }
Example #24
0
 /**
  * Returns oauth provider object from saved token.
  *
  * @return \Google_Client
  */
 public function providerFromToken()
 {
     if (empty($this->token)) {
         throw new MissingTokenException('Token not Found');
     }
     try {
         $google = new \Google_Client();
         $google->setClientId(array_get($this->config, 'client_id'));
         $google->setClientSecret(array_get($this->config, 'client_secret'));
         $google->setScopes(array_get($this->config, 'scopes'));
         $google->setAccessType('offline');
         $redirUrl = route('package.Userdesk.submission.authenticate', ['website' => 'youtube']);
         $google->setRedirectUri($redirUrl);
         $google->refreshToken($this->token->getRefreshToken());
         return $google;
     } catch (Exception $e) {
         throw new InvalidTokenException('Cannot verify saved token. User has either revoked the priveleges or created a new token.');
     }
 }
    public function startClient()
    {
        if ($this->accessToken === false) {
            die;
        }
        try {
            $token = $this->accessToken;
            $this->client->setAccessToken($token);
            if ($this->client->isAccessTokenExpired()) {
                $tokenobj = json_decode($token);
                if (isset($tokenobj->refresh_token)) {
                    try {
                        $this->client->refreshToken($tokenobj->refresh_token);
                    } catch (Exception $e) {
                        $this->settings['googledrive_app_current_token'] = '';
                        $this->settings['googledrive_app_refresh_token'] = '';
                        update_option('use_your_drive_settings', $this->settings);
                        if ($this->settings['lostauthorization_notification'] !== 'No') {
                            $subject = get_bloginfo() . ' | ' . __('Use-your-Drive authorization', 'useyourdrive');
                            $message = 'Hi!

The Use-your-Drive plugin has lost its authorization to Box. Without authorization the plugin cannot longer function. Please authorize the plugin again to make sure that your visitors can access your files.';
                            $message .= "<br>********<br>" . $e->getMessage() . '<br>********';
                            $result = wp_mail($this->settings['lostauthorization_notification'], $subject, $message);
                        }
                        return new WP_Error('broke', __("Use-your-Drive isn't ready to run", 'useyourdrive') . $e->getMessage());
                    }
                    $this->accessToken = $this->client->getAccessToken();
                    $this->settings['googledrive_app_current_token'] = $this->accessToken;
                    update_option('use_your_drive_settings', $this->settings);
                } else {
                    $this->settings['googledrive_app_current_token'] = '';
                    $this->settings['googledrive_app_refresh_token'] = '';
                    update_option('use_your_drive_settings', $this->settings);
                    return new WP_Error('broke', __("Use-your-Drive isn't ready to run", 'useyourdrive'));
                }
            }
        } catch (Exception $e) {
            return new WP_Error('broke', __("Couldn't connect to Google API: ", 'useyourdrive') . $e->getMessage());
        }
        return $this->client;
    }
Example #26
0
 /**
  * Deletes a video from the account specified by the Access Token
  * Attempts to automatically refresh the token if it's expired.
  *
  * @param $id of the video to delete
  * @return true if the video was deleted and false if it was not
  * @throws \Exception
  */
 public function delete($video_id)
 {
     $accessToken = $this->client->getAccessToken();
     if (is_null($accessToken)) {
         throw new \Exception('You need an access token to delete.');
     }
     // Attempt to refresh the access token if it's expired and save the new one in the database
     if ($this->client->isAccessTokenExpired()) {
         $accessToken = json_decode($accessToken);
         $refreshToken = $accessToken->refresh_token;
         $this->client->refreshToken($refreshToken);
         $newAccessToken = $this->client->getAccessToken();
         $this->saveAccessTokenToDB($newAccessToken);
     }
     $result = $this->youtube->videos->delete($video_id);
     if (!$result) {
         throw new \Exception("Couldn't delete the video from the youtube account.");
     }
     return $result->getId();
 }
Example #27
0
 /**
  * Uploads the passed video to the YouTube account identified by the access token in the DB and returns the
  * uploaded video's YouTube Video ID. Attempts to automatically refresh the token if it's expired.
  *
  * @param array $data As is returned from \Input::all() given a form as per the one in views/example.blade.php
  * @return string The ID of the uploaded video
  * @throws \Exception
  */
 public function upload(array $data)
 {
     $accessToken = $this->client->getAccessToken();
     if (is_null($accessToken)) {
         throw new \Exception('You need an access token to upload');
     }
     // Attempt to refresh the access token if it's expired and save the new one in the database
     if ($this->client->isAccessTokenExpired()) {
         $accessToken = json_decode($accessToken);
         $refreshToken = $accessToken->refresh_token;
         $this->client->refreshToken($refreshToken);
         $newAccessToken = $this->client->getAccessToken();
         $this->saveAccessTokenToDB($newAccessToken);
     }
     $snippet = new \Google_Service_YouTube_VideoSnippet();
     if (array_key_exists('title', $data)) {
         $snippet->setTitle($data['title']);
     }
     if (array_key_exists('description', $data)) {
         $snippet->setDescription($data['description']);
     }
     if (array_key_exists('tags', $data)) {
         $snippet->setTags($data['tags']);
     }
     if (array_key_exists('category_id', $data)) {
         $snippet->setCategoryId($data['category_id']);
     }
     $status = new \Google_Service_YouTube_VideoStatus();
     if (array_key_exists('status', $data)) {
         $status->privacyStatus = $data['status'];
     }
     $video = new \Google_Service_YouTube_Video();
     $video->setSnippet($snippet);
     $video->setStatus($status);
     $result = $this->youtube->videos->insert('status,snippet', $video, array('data' => file_get_contents($data['video']->getRealPath()), 'mimeType' => $data['video']->getMimeType(), 'uploadType' => 'multipart'));
     if (!$result instanceof \Google_Service_YouTube_Video) {
         throw new \Exception('Expecting instance of Google_Service_YouTube_Video, got:' . $result);
     }
     return $result->getId();
 }
 public function setAuthorization()
 {
     $client = new \Google_Client();
     $client->setAccessType('offline');
     $client->setApplicationName(GoogleShopping::getConfigValue('application_name'));
     $client->setClientId(GoogleShopping::getConfigValue('client_id'));
     $client->setClientSecret(GoogleShopping::getConfigValue('client_secret'));
     $client->setRedirectUri(URL::getInstance()->absoluteUrl('/googleshopping/oauth2callback'));
     $client->setScopes('https://www.googleapis.com/auth/content');
     $oAuthToken = GoogleShopping::getConfigValue('oauth_access_token');
     $code = $this->getRequest()->query->get('code');
     $redirection = '/admin/module/GoogleShopping';
     //Manage redirection after auth
     if ($url = $this->getRequest()->query->get('redirect')) {
         $redirection = $url;
         $this->getSession()->set('google_action_url', $redirection);
     }
     if (isset($oAuthToken)) {
         $client->setAccessToken($oAuthToken);
         if ($client->isAccessTokenExpired()) {
             $client->refreshToken(GoogleShopping::getConfigValue('oauth_refresh_token'));
             $newToken = $client->getAccessToken();
             GoogleShopping::setConfigValue('oauth_access_token', $newToken);
         }
         return $this->generateRedirect($redirection);
     } elseif (isset($code)) {
         $client->authenticate($code);
         $token = $client->getAccessToken();
         $refreshToken = $client->getRefreshToken();
         GoogleShopping::setConfigValue('oauth_access_token', $token);
         if ($refreshToken) {
             GoogleShopping::setConfigValue('oauth_refresh_token', $refreshToken);
         }
         return $this->generateRedirect($redirection);
     } else {
         return $this->generateRedirect($client->createAuthUrl());
     }
 }
Example #29
0
 /**
  * Returns an authorized API client.
  * @return Google_Client the authorized client object
  */
 function getClient()
 {
     $client = new Google_Client();
     $client->setApplicationName(APPLICATION_NAME);
     $client->setScopes(SCOPES);
     $client->setAuthConfigFile(CLIENT_SECRET_PATH);
     $client->setAccessType('offline');
     // Load previously authorized credentials from a file.
     $credentialsPath = $this->expandHomeDirectory(CREDENTIALS_PATH);
     //$credentialsPath = '/root/.credentials/calendar-php-quickstart.json';
     var_dump(CREDENTIALS_PATH);
     var_dump($credentialsPath);
     if (file_exists($credentialsPath)) {
         $accessToken = file_get_contents($credentialsPath);
     } else {
         // Request authorization from the user.
         $authUrl = $client->createAuthUrl();
         printf("Open the following link in your browser:\n%s\n", $authUrl);
         print 'Enter verification code: ';
         //$authCode = '4/baev8vvxfmBSuzvgTG0YGgXf2PsPviyxu2lUnqRN1Es';
         $authCode = '4/4FWQ2Ib5_5iTnlwep_Zr_xlbm9UAkh3R6lSI8s-uQAc';
         // Exchange authorization code for an access token.
         $accessToken = $client->authenticate($authCode);
         // Store the credentials to disk.
         if (!file_exists(dirname($credentialsPath))) {
             mkdir(dirname($credentialsPath), 0700, true);
         }
         file_put_contents($credentialsPath, $accessToken);
         printf("Credentials saved to %s\n", $credentialsPath);
     }
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($credentialsPath, $client->getAccessToken());
     }
     return $client;
 }
function generateClient($expectedAccessToken)
{
    global $path;
    # Get OAuth2 information
    $oauthFile = fopen($path . "oauthinfo.json", "r");
    $rawJson = fread($oauthFile, filesize($path . "oauthinfo.json"));
    $decodedJson = json_decode($rawJson, true)['web'];
    # Decode information
    $clientID = $decodedJson['client_id'];
    # pull from json sheet
    $clientSecret = $decodedJson['client_secret'];
    # also pull from json sheet
    $redirectUri = 'http://localhost/admin.php';
    # change this every time we install application, this uri MUST be registed in the google decelopers console
    $client = new Google_Client();
    $client->setClientId($clientID);
    $client->setClientSecret($clientSecret);
    $client->setRedirectUri($redirectUri);
    $client->setScopes(array('https://spreadsheets.google.com/feeds'));
    $client->setAccessType("offline");
    if (filesize($path . "accessToken.json") != 0) {
        # If accessToken.json has information
        $credFile = fopen($path . "accessToken.json", "r");
        $accessArray = fread($credFile, filesize($path . "accessToken.json"));
        $client->setAccessToken($accessArray);
        $client->refreshToken($client->getRefreshToken());
        $credFile = fopen($path . "accessToken.json", "w");
        fwrite($credFile, $client->getAccessToken());
        return $client;
    } else {
        if ($expectedAccessToken) {
            print "Site has been invalidly configured, please contact your webmaster";
            exit;
        } else {
            return $client;
        }
    }
}