/**
  * 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 oauth2callback()
 {
     $this->tpl_name = "";
     require_once '../tf_app/ext/google/autoload.php';
     session_start();
     // ********************************************************  //
     // Get these values from https://console.developers.google.com
     // Be sure to enable the Analytics API
     // ********************************************************    //
     $client_id = '334086275725-f15a3bl6bm7kbhfkm66u9va1si5bb9ia.apps.googleusercontent.com';
     $client_secret = 'FbKWozz_ZNmlk5PUEXPC2BUO';
     $redirect_uri = 'http://localhost.me:8006/ajax_v3/oauth2callback';
     $client = new Google_Client();
     $client->setApplicationName("test-calendar");
     $client->setClientId($client_id);
     $client->setClientSecret($client_secret);
     $client->setRedirectUri($redirect_uri);
     $client->setAccessType('offline');
     // Gets us our refreshtoken
     $client->setScopes(array('https://www.googleapis.com/auth/calendar'));
     //For loging out.
     if (isset($_GET['logout'])) {
         unset($_SESSION['token']);
     }
     // Step 2: The user accepted your access now you need to exchange it.
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
         $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
         header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
     }
     // $_SESSION["token"]["access_token"] = "ya29.xAFLnfAz9X-h7LWyUF6258cMbOzcUljurQPw0UMPdnpP15fiz5SWY0yJXvKvfaupQuYCPA";
     // Step 1:  The user has not authenticated we give them a link to login
     if (!isset($_SESSION['token'])) {
         $authUrl = $client->createAuthUrl();
         print "<a class='login' href='{$authUrl}'>Connect Me!</a>";
     }
     // Step 3: We have access we can now create our service
     if (isset($_SESSION['token'])) {
         // $client->refreshToken($refreshToken);
         $client->setAccessToken($_SESSION['token']);
         $refresh_token = $client->getRefreshToken();
         $_SESSION['refresh_token'] = $refresh_token;
         $token = json_decode($_SESSION['token']);
         // echo "Access Token = " . $token->access_token . '<br/>';
         // echo "Refresh Token = " . $token->refresh_token . '<br/>';
         // echo "Token type = " . $token->token_type . '<br/>';
         // echo "Expires in = " . $token->expires_in . '<br/>';
         // echo "ID Token = " . $token->id_token . '<br/>';
         // echo "Created = " . $token->created . '<br/>';
         print "<a class='logout' href='http://localhost.me:8006/ajax_v3/oauth2callback?logout=1'>LogOut</a><br>";
         // print_r($_SESSION);
         $service = new Google_Service_Calendar($client);
         $calendarList = $service->calendarList->listCalendarList();
         while (true) {
             foreach ($calendarList->getItems() as $calendarListEntry) {
                 echo $calendarListEntry->getSummary() . "<br>\n";
                 // get events
                 $events = $service->events->listEvents($calendarListEntry->id);
                 foreach ($events->getItems() as $event) {
                     echo "-----" . $event->getSummary() . "<br>";
                 }
             }
             $pageToken = $calendarList->getNextPageToken();
             if ($pageToken) {
                 $optParams = array('pageToken' => $pageToken);
                 $calendarList = $service->calendarList->listCalendarList($optParams);
             } else {
                 break;
             }
         }
         // reservation
         if ($_REQUEST["type"] == "r") {
             $rsv = $this->Space_reserve->list_(1, 1000, 'sr.state = 1 and sr.date > "' . date('Y.m.d', strtotime('-1 month')) . '"');
             $len_rsv = sizeof($rsv);
             for ($r = 0; $r < $len_rsv; $r++) {
                 $rsv[$r]["s"] = substr_replace(date("Y-m-dH:i:00", strtotime(str_replace(".", "-", $rsv[$r]["date"]) . $rsv[$r]["start"])), 'T', 10, 0);
                 $rsv[$r]["e"] = substr_replace(date("Y-m-dH:i:00", strtotime(str_replace(".", "-", $rsv[$r]["date"]) . $rsv[$r]["end"])), 'T', 10, 0);
                 $rsv[$r]["summary"] = "[" . $rsv[$r]["opt"] . "F " . explode_ext($rsv[$r]["name"], '(') . "] " . $rsv[$r]["purpose"];
                 $rsv[$r]["location"] = $rsv[$r]["opt"] . "F " . explode_ext($rsv[$r]["name"], '(');
             }
             $_calId = '*****@*****.**';
             $fo = $rsv;
         }
         // event
         if ($_REQUEST["type"] == "e") {
             $ev = $this->Event->list_(1, 10000, 'e.state = 1 and open = 1 and (e.date > "' . date('Y.m.d', strtotime('-1 month')) . '" or e.date_e > "' . date('Y.m.d', strtotime('-1 month')) . '")');
             $len_ev = sizeof($ev);
             for ($r = 0; $r < $len_ev; $r++) {
                 $ev[$r]["s"] = substr_replace(date("Y-m-dH:i:00", strtotime(str_replace(".", "-", $ev[$r]["date"]) . $ev[$r]["start"])), 'T', 10, 0);
                 $ev[$r]["e"] = substr_replace(date("Y-m-dH:i:00", strtotime(str_replace(".", "-", $ev[$r]["date_e"]) . $ev[$r]["end"])), 'T', 10, 0);
                 $ev[$r]["summary"] = "[Event] " . $ev[$r]["title"];
                 if ($ev[$r]["space_id"] == 0) {
                     $ev[$r]["location"] = $ev[$r]["space_etc"];
                 } else {
                     $ev[$r]["location"] = "D.CAMP " . $ev[$r]["opt"] . "F " . explode_ext($ev[$r]["sname"], '(');
                 }
             }
             $_calId = '*****@*****.**';
             $fo = $ev;
         }
         // office_hours
         if ($_REQUEST["type"] == "o") {
             $off = $this->Office_hours->list_(1, 1000, 'o.status = 1 and o.is_open = 1 and o.e_start > "' . date('Y.m.d', strtotime('-1 month')) . '"');
             $len_off = sizeof($off);
             for ($r = 0; $r < $len_off; $r++) {
                 $off[$r]["s"] = substr_replace(date("Y-m-dH:i:00", strtotime(str_replace(".", "-", str_replace(" ", "", $off[$r]["e_start"])))), 'T', 10, 0);
                 $off[$r]["e"] = substr_replace(date("Y-m-dH:i:00", strtotime(str_replace(".", "-", str_replace(" ", "", $off[$r]["e_end"])))), 'T', 10, 0);
                 $off[$r]["summary"] = "[Office Hours] " . $off[$r]["subject"];
                 $off[$r]["location"] = "D.CAMP " . $off[$r]["place"];
             }
             $_calId = '*****@*****.**';
             $fo = $off;
         }
         // challenge
         if ($_REQUEST["type"] == "c") {
             $ch = $this->Competitions->get_list(1, 1000, 'c.status = 1 and c.open = 1 and (c.date_s > "' . date('Y.m.d', strtotime('-1 month')) . '" or c.date_e > "' . date('Y.m.d', strtotime('-1 month')) . '")');
             $len_ch = sizeof($ch);
             for ($r = 0; $r < $len_ch; $r++) {
                 $ch[$r]["s"] = substr_replace(date("Y-m-dH:i:00", strtotime(str_replace(".", "-", $ch[$r]["date_s"]) . $ch[$r]["time_s"])), 'T', 10, 0);
                 $ch[$r]["e"] = substr_replace(date("Y-m-dH:i:00", strtotime(str_replace(".", "-", $ch[$r]["date_e"]) . $ch[$r]["time_e"])), 'T', 10, 0);
                 $ch[$r]["summary"] = "[Challenge] " . $ch[$r]["subject"];
                 $ch[$r]["location"] = "";
             }
             $_calId = '*****@*****.**';
             $fo = $ch;
         }
         // Remove
         if ($_REQUEST["remove"]) {
             // $primary = '*****@*****.**';
             $events = $service->events->listEvents($_calId);
             while (true) {
                 foreach ($events->getItems() as $event) {
                     echo $event->getSummary();
                     $service->events->delete($_calId, $event->id);
                 }
                 $pageToken = $events->getNextPageToken();
                 if ($pageToken) {
                     $optParams = array('pageToken' => $pageToken);
                     $events = $service->events->listEvents($_calId, $optParams);
                 } else {
                     break;
                 }
             }
         } else {
             if ($fo) {
                 $len_fo = sizeof($fo);
                 for ($i = 0; $i < $len_fo; $i++) {
                     $event = new Google_Service_Calendar_Event(array('summary' => $fo[$i]["summary"], 'location' => $fo[$i]["location"], 'start' => array('dateTime' => $fo[$i]["s"], 'timeZone' => "Asia/Seoul"), 'end' => array('dateTime' => $fo[$i]["e"], 'timeZone' => "Asia/Seoul")));
                     $calendarId = $_calId;
                     $event = $service->events->insert($calendarId, $event);
                     // printf('<br>Event created: %s\n', $event->htmlLink);
                 }
             }
         }
     }
 }
Example #4
0
 /**
  * @return string
  */
 public function isLoggedIn()
 {
     if (\Session::has('token')) {
         $this->client->setAccessToken(\Session::get('token'));
     } else {
         return false;
     }
     if ($this->client->isAccessTokenExpired()) {
         \Session::set('token', $this->client->getRefreshToken());
     }
     return !$this->client->isAccessTokenExpired();
 }
Example #5
0
 /**
  * Auth over command line
  */
 public function cmdLineAuth()
 {
     $authUrl = $this->client->createAuthUrl();
     //Request authorization
     print "Please visit:\n{$authUrl}\n\n";
     print "Please enter the auth code:\n";
     $authCode = trim(fgets(STDIN));
     // Exchange authorization code for access token
     $accessToken = $this->client->authenticate($authCode);
     $this->client->setAccessToken($accessToken);
     $this->accessToken = $accessToken;
     $this->refreshToken = $this->client->getRefreshToken();
 }
 private function refreshAuthToken(\Google_Client $client)
 {
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents(CREDENTIALS_FILE, $client->getAccessToken());
     }
 }
Example #7
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;
}
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;
}
Example #9
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;
 }
 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)));
 }
 /**
  * @param null $code
  * @param User $user
  * @return bool
  */
 public function authenticate($code = null, User $user)
 {
     try {
         $this->client->authenticate($code);
     } catch (\Exception $e) {
         return false;
     }
     $session = new Session();
     $session->set('access_token', $this->getAccessToken());
     $refreshToken = $this->client->getRefreshToken();
     $user->setGoogleRefreshToken($refreshToken);
     $this->em->flush();
     return true;
 }
 /**
  * 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);
 }
 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 #14
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;
        }
    }
}
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function gfGetClient()
{
    $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 = expandHomeDirectory(CREDENTIALS_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        echo $credentialsPath;
        die("Error: User is not authenticated.");
    }
    $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;
}
require_once __DIR__ . '/_siteconfig.php';
require_once __DIR__ . '/vendor/autoload.php';
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(Google_Service_Drive::DRIVE)));
session_start();
$base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$base_url .= '://' . $_SERVER['HTTP_HOST'] . '/grind-members/';
$client = new Google_Client();
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->addScope(SCOPES);
$client->setAccessType('offline');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
    if ($client->isAccessTokenExpired()) {
        error_log("Access Token has expired!");
        $refresh_token = $client->getRefreshToken();
        error_log('Refresh Token: ');
        error_log($refresh_token);
        $client->refreshToken($refresh_token);
        $_SESSION['access_token'] = $client->getAccessToken();
        $client->setAccessToken($_SESSION['access_token']);
    } else {
        $drive_service = new Google_Service_Drive($client);
        if (isset($_SESSION['not_authorized'])) {
            error_log($_SESSION['not_authorized']);
        }
        if (isset($_SESSION['app_request_uri']) && isset($_SESSION['not_authorized']) && $_SESSION['not_authorized']) {
            $request_uri = $_SESSION['app_request_uri'];
            error_log("request_uri: " . $request_uri);
            $_SESSION['app_request_uri'] = NULL;
            $_SESSION['not_authorized'] = 0;
Example #18
0
 } else {
     if ($iniFilename != BECFM_INI_FILENAME) {
         die("<HTML>Error: Requested ini file '{$iniFilename}' not found</HMTL>");
     }
 }
 // We're expecting a code (_GET['code'] which we need to exchange for an access token
 require_once 'vendor/autoload.php';
 $client = new Google_Client();
 $client->setAuthConfigFile($ini['gmail_client_secret_path']);
 $client->setLoginHint($ini['gmail_username']);
 if (isset($_GET['code'])) {
     // Exchange code for access token
     $client->authenticate($_GET['code']);
     $token = $client->getAccessToken();
     $filename = $ini['gmail_credentials_path'];
     if (strlen($client->getRefreshToken()) < 5) {
         /* We've lost the refresh token - it's better to revoke this
          * token now and re-request access from the user.
          */
         $client->revokeToken();
         unlink($filename);
     } else {
         // Save the access token
         if (strlen($token) != file_put_contents($filename, $token)) {
             die("<HTML>Error: Failed to write access token to {$filename}</HTML>");
         }
     }
 }
 /* Re-fetch bec.php - it should find the access token this time if we saved one,
  * or re-request access from the user.
  */
 function getClient()
 {
     $client = new Google_Client();
     $client->setApplicationName(APPLICATION_NAME);
     $client->setScopes(array('https://www.googleapis.com/auth/drive'));
     $client->setClientId('854111737727-shq9f7hus9goo57ve38lpdn1v2v6i5qc.apps.googleusercontent.com');
     $client->setClientSecret('-3pT2W-uRYVGpuGBszHfhoT7');
     $client->setRedirectUri('http://localhost/beta/google-api-php-client/googleDrive.php');
     $client->setAccessType('offline');
     //  $client->setApprovalPrompt('force');
     $credentialsPath = $this->expandHomeDirectory(CREDENTIALS_PATH);
     if (file_exists($credentialsPath)) {
         $accessToken = file_get_contents($credentialsPath);
     } else {
         // Request authorization from the user.
         $authUrl = $client->createAuthUrl();
         if (!isset($_GET['code'])) {
             /*    Location */
             //                header('Location:' . $authUrl);
             return Redirect::to($authUrl);
         }
         $authCode = trim(fgets(STDIN));
         // Exchange authorization code for an access token.
         $accessToken = $client->authenticate($_GET['code']);
         // Store the credentials to disk.
         if (!file_exists(dirname($credentialsPath))) {
             mkdir(dirname($credentialsPath), 0700, true);
         }
         file_put_contents($credentialsPath, $accessToken);
     }
     $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;
 }
 /**
  * Retrieve the client's refresh token
  *
  * @return mixed
  */
 public function getRefreshToken()
 {
     return $this->googleApiClient->getRefreshToken();
 }
Example #21
0
 /**
  * Returns an authorized API client.
  * @return Google_Client the authorized client object
  */
 public function getClient()
 {
     // Check if it is already connected
     if (!$this->clientConnection == FALSE) {
         return $this->clientConnection;
     }
     if (!$this->credential_path || !$this->client_secret_path || !$this->scopes) {
         echo "Google API Credential is not properly set!";
         return false;
     }
     $client = new Google_Client();
     $client->setApplicationName($this->application_name);
     $client->setScopes($this->scopes);
     $client->setAuthConfigFile($this->client_secret_path);
     $client->setAccessType('offline');
     // Load previously authorized credentials from a file.
     $credentialsPath = $this->expandHomeDirectory($this->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%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());
     }
     $this->clientConnection = $client;
     return $client;
 }
Example #22
0
//If user denies authorization
if (isset($_GET['error'])) {
    //Redirect user to error page
    $_SESSION['error'] = "You must allow this tool to access Drive in one of your gmail accounts for this tool to work. " . "Please <a href='Cloud.php'>try again</a>.";
    header('Location: ' . 'https://' . $_SERVER['HTTP_HOST'] . '/afsmigrator/error_page.php');
} else {
    if (!isset($_GET['code'])) {
        //Create and send auth url
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
        try {
            //Trade authorization code for access and refresh token
            $client->authenticate($_GET['code']);
            //Save refresh token to .csv
            $_SESSION['refresh_token'] = $client->getRefreshToken();
            if (!$_SESSION['refresh_token']) {
                $_SESSION['error'] = "Refresh token could not be generated." . "Please revoke access to this app <a href='https://security.google.com/settings/security/permissions?pli=1'>here</> and " . "then <a href='Cloud.php'>try again</a>.";
                header('Location: ' . 'https://' . $_SERVER['HTTP_HOST'] . '/afsmigrator/error_page.php');
                die;
            }
            //Store access token as session variable and redirect to main script
            $_SESSION['access_token'] = $client->getAccessToken();
            $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/afsmigrator/drive/upload_to_drive.php';
            header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        } catch (Exception $e) {
            echo "An error occurred: " . $e->getMessage();
        }
    }
}
?>
 ************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
} else {
    $authUrl = $client->createAuthUrl();
}
echo pageHeader("Google APIs Client Library for PHP with Lifelog");
echo "<p><i>Tested with Google Client v1.1.5</i></p>";
if (isset($authUrl)) {
    echo missingAccessTokenLink($authUrl);
} else {
    echo logoutLink();
    echo '<div style="border: 1px solid grey; padding: 10px; margin: 10px; word-wrap: break-word"><b>DEBUG</b><br />';
    echo "<p>code: " . $_SESSION['auth_code'] . "</p>";
    echo "<p>getAccessToken: " . $client->getAccessToken() . "</p>";
    echo "<p>getRefreshToken: " . $client->getRefreshToken() . "</p>";
    echo '</div>';
    if ($client->isAccessTokenExpired()) {
        echo "<p><b>Access token has expired.</b></p>";
        try {
            //echo "client id." .$client_id .", ". $client->getClassConfig($client, 'client_id');
            //Get a new Access token with help of the Refresh Token
            $client->refreshToken($client->getRefreshToken());
            //Update
            echo "gac: " . $client->getAccessToken();
            echo "upd getAccessCode: " . $client->getAccessToken();
            echo "ac: " . $_SESSION['access_token'];
            echo "<p><b>Access token refreshed</b></p>";
        } catch (Exception $e) {
            echo "<br />Message: " . $e->getMessage();
            echo "<br /><br />Trace: " . $e->getTraceAsString();
Example #24
0
 */
require_once realpath(dirname(__FILE__) . '/../lib/google-api-php-client-master/autoload.php');
/************************************************
  ATTENTION: Fill in these values! Make sure
  the redirect URI is to this page, e.g:
  http://localhost:8080/fileupload.php
 ************************************************/
$client_id = '*****@*****.**';
$client_secret = 'VsiFzxOiNnklKdmtTnmeKEem';
$redirect_uri = 'http://localhost/link_accounts.php?refer=GDrive';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setScopes('https://www.googleapis.com/auth/drive');
$client->setAccessType('offline');
$client->setApprovalPrompt("force");
$service = new Google_Service_Drive($client);
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $token = $client->getAccessToken();
    $refresh = $client->getRefreshToken();
    $permissionId = $service->about->get()->getUser()->getpermissionId();
    $email = $service->about->get()->getUser()->getemailAddress();
    query("INSERT INTO service_accounts(user_id, service_name, service_email, service_id, service_accessToken) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE service_accessToken = ?", $_SESSION["id"], "3", $email, $permissionId, serialize($token), serialize($token));
    redirect("link.php?link=success&service=GDrive");
} else {
    $authUrl = $client->createAuthUrl();
    redirect("{$authUrl}");
}
Example #25
0
function submit_reg_form()
{
    //ReCaptcha
    $recaptcha = new ReCaptcha(RECAPTCHA_SECRET);
    $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
    if (!$resp->isSuccess()) {
        throw new Exception('Invalid captcha!');
    }
    //Get & Process form data
    $valid_inputs = 'name|email|tel|inst|std|day1|day2';
    foreach (get_presentations() as $key => $data) {
        $valid_inputs .= "|{$key}";
    }
    $form_data = getInputsWithKey($valid_inputs);
    //----Pricing
    //Count days
    $days = 0;
    for ($i = 1; $i <= 2; $i++) {
        if ($form_data["day{$i}"] != 'no') {
            $days++;
        }
    }
    $price = $days * 35;
    //    if ($days > 1)
    //        $price -= 10;
    //Discount
    $discount_rate = 0;
    if (isset($form_data['std'])) {
        switch ($form_data['std']) {
            case 'aut':
                $discount_rate = 0.6;
                break;
            case 'std':
                $discount_rate = 0.25;
                break;
        }
    }
    $price *= 1.0 - $discount_rate;
    $price = round($price);
    $form_data['price'] = $price;
    //Tel
    $form_data['tel'] = intval($form_data['tel']);
    //Generate tracking code
    $hashids = new Hashids\Hashids(HASHID_SALT);
    $tracking_code = $hashids->encode(time() . rand(0, 100));
    $form_data['code'] = $tracking_code;
    //Check Google Client Expired
    $token = json_decode(gapi_token, true);
    $client = new Google_Client();
    $client->setClientId(GAPI_CLIENT_ID);
    $client->setClientSecret(GAPI_CLIENT_SECRET);
    $client->setAccessToken(gapi_token);
    if ($client->isAccessTokenExpired()) {
        //Refresh on expire
        $client->refreshToken($client->getRefreshToken());
        foreach (json_decode($client->getAccessToken(), true) as $k => $v) {
            $token[$k] = $v;
        }
        file_put_contents(GAPI_TOKEN_LOCATION, "<?php define('gapi_token','" . json_encode($token) . "');");
    }
    //Get Registration sheet
    $serviceRequest = new DefaultServiceRequest($token['access_token']);
    ServiceRequestFactory::setInstance($serviceRequest);
    $spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
    $sheet = $spreadsheetService->getSpreadsheets()->getByTitle('linuxfest_2015')->getWorksheets()->getByTitle('List');
    //Insert Submitted data
    $sheet->getListFeed()->insert($form_data);
    //Message
    $msg = "\n<div dir='rtl'>\n\n       با تشکر، ثبت نام آنلاین شما با موفقیت انجام شد و مورد بررسی قرار خواهد گرفت.\n        <br>\n        هزینه ی ثبت نام شما : <b>{$price}</b> هزار تومان\n                <br>\n        کد رهگیری شما : <b>{$tracking_code}</b>\n        (این کد را برای مراحل بعدی حتما نگهدارید)<br>\n        <br>\n                لطفا در اسرع وقت با مراجعه‌ی حضوری به دفتر انجمن علمی دانشکده هزینه‌ی دوره‌هایی را که در آن‌ها ثبت نام کرده‌اید پرداخت نمایید. در صورتی که مراجعه‌ی حضوری برایتان مقدور نیست هزینه‌ی ثبت نام را به کارت 5022291100266525 (بانک پاسارگاد به نام آرمین باشی‌زاده) واریز نمایید و کد رهگیری و شماره کارت خود را به آدرس hello@linuxfest.ir ارسال کنید. به دلیل محدود بودن ظرفیت کارگاه‌ها، اولویت با کسانی است که زودتر ثبت نام خود را نهایی کنند.\n<br>\nتهران، چهارراه ولی عصر، روبه‌روی خیابان بزرگمهر، دانشگاه صنعتی امیرکبیر ، دانشکده مهندسی کامپیوتر و فناوری اطلاعات ، دفتر انجمن علمی\n\t<br>\n     در صورت تمایل به ایجاد هرگونه تغییر در وضعیت ثبت نام خود از ثبت نام مجدد <b> جدا خودداری فرمایید</b>. در غیر این صورت ثبت نام شما تایید نخواهد شد.<br>\n      می‌توانید این تغییرات را از دو طریق ایمیل جشنواره hello@linuxfest.ir یا مراجعه‌ی حضوری اعلام فرمایید.\n\n</div>\n    ";
    $msg_2 = "جشنواره لینوکس امیرکبیر\n    هزینه ی ثبت نام : {$price} هزار تومان\n    کد رهگیری شما : {$tracking_code}\n    جهت ثبت نام نهایی در اسرع وقت به دفتر انجمن علمی دانشکده مراجعه فرمایید\n    ";
    //Email
    if (isset($form_data['email'])) {
        sendmail($form_data['email'], $msg);
    }
    //SMS
    if (isset($form_data['tel'])) {
        sendsms($form_data['tel'], $msg_2);
    }
    return $msg;
}
 /**
  * New service client - Authentication google Api
  *
  * @return Google_Service_Client $service API service instance.
  */
 public function serviceClient()
 {
     $client = null;
     if ($this->typeAuthentication == 'webApplication') {
         if (file_exists(PATH_DATA_SITE . $this->accountJson)) {
             $credential = file_get_contents(PATH_DATA_SITE . $this->accountJson);
         } else {
             throw new Exception(G::LoadTranslation('ID_GOOGLE_FILE_JSON_ERROR'));
         }
         $client = new Google_Client();
         $client->setAuthConfig($credential);
         $client->addScope($this->scope);
         if (!empty($_SESSION['google_token'])) {
             $client->setAccessToken($_SESSION['google_token']);
             if ($client->isAccessTokenExpired()) {
                 $client->getRefreshToken();
                 unset($_SESSION['google_token']);
                 $_SESSION['google_token'] = $client->getAccessToken();
             }
         } else {
             if (!empty($_SESSION['CODE_GMAIL'])) {
                 $token = $client->authenticate($_SESSION['CODE_GMAIL']);
                 $_SESSION['google_token'] = $client->getAccessToken();
             } else {
                 $authUrl = $client->createAuthUrl();
                 echo '<script type="text/javascript">
                 var opciones = "width=450,height=480,scrollbars=NO, locatin=NO,toolbar=NO, status=NO, menumbar=NO, top=10%, left=25%";
                 window.open("' . $authUrl . '","Gmail", opciones);
                 </script>';
                 die;
             }
         }
     } else {
         if ($this->typeAuthentication == 'serviceAccount') {
             if (file_exists(PATH_DATA_SITE . $this->serviceAccountP12)) {
                 $key = file_get_contents(PATH_DATA_SITE . $this->serviceAccountP12);
             } else {
                 throw new Exception(G::LoadTranslation('ID_GOOGLE_FILE_P12_ERROR'));
             }
             $assertionCredentials = new Google_Auth_AssertionCredentials($this->serviceAccountEmail, $this->scope, $key);
             $assertionCredentials->sub = $this->user;
             $client = new Google_Client();
             $client->setApplicationName("PMDrive");
             $client->setAssertionCredentials($assertionCredentials);
         } else {
             throw new Exception(G::LoadTranslation('ID_SERVER_COMMUNICATION_ERROR'));
         }
     }
     return $client;
 }
Example #27
0
 /**
  * Returns an authorized API client
  *
  * @return Google_Client the authorized client object
  */
 function getClient()
 {
     global $ini, $verbose;
     static $client = NULL;
     if ($client) {
         return $client;
     }
     if (DEBUG) {
         print "Google APIs application name: {$ini['gmail_application_name']}\n" . "Google Gmail client secret file: {$ini['gmail_client_secret_path']}\n" . "Google Gmail credentials path: {$ini['gmail_credentials_path']}\n";
     }
     try {
         $client = new Google_Client();
         $client->setApplicationName($ini['gmail_application_name']);
         $client->setScopes(GMAIL_SCOPES);
         $client->setAuthConfigFile($ini['gmail_client_secret_path']);
         $client->setLoginHint($ini['gmail_username']);
         // We want access even when the user is not logged in
         $client->setAccessType('offline');
         // Load previously authorized credentials from a file.
         $credentialsPath = expandHomeDirectory($ini['gmail_credentials_path']);
         if (file_exists($credentialsPath)) {
             if (DEBUG) {
                 print "Using existing access token from {$credentialsPath}\n";
             }
             $accessToken = file_get_contents($credentialsPath);
         } else {
             // Request authorisation from the user.
             if (DEBUG) {
                 print "Requesting authorisation\n";
             }
             $authURL = $client->createAuthUrl();
             if (php_sapi_name() != 'cli') {
                 // Re-direct browser to authentication URL
                 header('Location: ' . filter_var($authURL, FILTER_SANITIZE_URL));
             }
             print "Open the following link in your browser:\n{$authURL}\n";
             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);
             if ($verbose > 3) {
                 print "Credentials saved to {$credentialsPath}\n";
             }
         }
         if (DEBUG) {
             print_r($accessToken);
             print "\n";
         }
         $client->setAccessToken($accessToken);
         // Refresh the token if it's expired.
         if ($client->isAccessTokenExpired()) {
             $client->refreshToken($client->getRefreshToken());
             $accessToken = $client->getAccessToken();
             // Check we've not lost the refresh token
             if (FALSE == strstr($accessToken, 'refresh_token')) {
                 die("Error: Refreshed access token no longer contains refresh token used to retrieve it\n");
             }
             if (DEBUG) {
                 print "Refreshed accesss token:\n";
                 print_r($accessToken);
             }
             file_put_contents($credentialsPath, $accessToken);
         }
     } catch (Exception $e) {
         print 'Exception: ' . $e->getMessage();
     }
     return $client;
 }
 /**
  * Refreshes the access token
  *
  * @return void
  */
 public function refreshToken()
 {
     $this->client->refreshToken($this->client->getRefreshToken());
     $this->setCredentials($this->client->getAccessToken());
 }
Example #29
0
require_once __DIR__ . '/vendor/autoload.php';
// Copy your client id and secret from Google developer console
define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret_928537847124-qm8cq61u3j4r3rs88osph5itc6bvn5mm.apps.googleusercontent.com.json');
define('SCOPES', implode(' ', array(Google_Service_Drive::DRIVE, Google_Service_Drive::DRIVE_APPDATA, Google_Service_Drive::DRIVE_APPS_READONLY, Google_Service_Drive::DRIVE_FILE, Google_Service_Plus::USERINFO_EMAIL, 'https://spreadsheets.google.com/feeds')));
define('REDIRECT_URL', 'http://localhost/php-google-oauth');
// -----------------------------------------------------------------------------
// DO NOT EDIT BELOW THIS LINE
// -----------------------------------------------------------------------------
session_start();
$client = new Google_Client();
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->addScope(SCOPES);
$client->setAccessType('offline');
$client->setRedirectUri(REDIRECT_URL);
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    exit;
}
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        $_SESSION['token'] = $client->getAccessToken();
    }
} else {
    print '<a href="' . $client->createAuthUrl() . '">Authenticate</a>';
}
print_r(json_decode($client->getAccessToken(), true));
 private function getGoogleClient()
 {
     $client_id = Configure::read('google_client_id');
     $client_secret = Configure::read('google_client_secret');
     $redirect_uri = Configure::read('google_redirect_url');
     $client = new Google_Client();
     $client->setApplicationName("kdkitchen");
     $client->setClientId($client_id);
     $client->setClientSecret($client_secret);
     $client->setRedirectUri($redirect_uri);
     $client->addScope(implode(' ', array(Google_Service_Calendar::CALENDAR_READONLY)));
     $client->setAccessType("offline");
     $googleApiData = $this->getGoogleApiData();
     if (!empty($googleApiData)) {
         $this->SocialMedia->id = $googleApiData['SocialMedia']['id'];
         $accessToken = $googleApiData['SocialMedia']['data'];
     } else {
         if (isset($_GET['code'])) {
             $authCode = $_GET['code'];
         } else {
             $authUrl = $client->createAuthUrl();
             $_SESSION['redirect'] = $this->request->url;
             header('Location: ' . $authUrl);
             exit;
         }
         $accessToken = $client->authenticate($authCode);
         $this->SocialMedia->create();
         $this->SocialMedia->set('name', 'google_api');
         $this->SocialMedia->set('data', $accessToken);
         $this->SocialMedia->save();
         $redirect = $_SESSION['redirect'];
         unset($_SESSION['redirect']);
         $this->redirect($redirect);
         exit;
     }
     $client->setAccessToken($accessToken);
     if ($client->isAccessTokenExpired()) {
         if (!isset($googleApiData) || empty($googleApiData)) {
             $googleApiData = $this->getGoogleApiData();
             $this->SocialMedia->id = $googleApiData['SocialMedia']['id'];
         }
         $client->refreshToken($client->getRefreshToken());
         $this->SocialMedia->set('data', $client->getAccessToken());
         $this->SocialMedia->save();
     }
     return $client;
 }