/**
  * 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;
 }
 /**
  * Initialize the google calendar
  *
  * @throws \KevinDitscheid\KdCalendar\Exception\NoAuthDataException
  */
 public function initializeObject()
 {
     $this->settings = \KevinDitscheid\KdCalendar\Utility\ExtensionUtility::getMergedExtensionConfiguration();
     $this->client = new \Google_Client();
     $this->client->setApplicationName($this->settings['applicationName']);
     $this->client->setScopes(\Google_Service_Calendar::CALENDAR_READONLY);
     if ($this->settings['auth']['jsonFile']) {
         $this->client->setAuthConfigFile($this->settings['auth']['jsonFile']);
     } elseif ($this->settings['auth']['jsonString']) {
         $this->client->setAuthConfig($this->settings['auth']['jsonString']);
     } else {
         throw new \KevinDitscheid\KdCalendar\Exception\NoAuthDataException("No auth data is provided for Google Calendar!", 1454958940);
     }
     $this->client->setAccessType(self::ACCESS_TYPE_OFFLINE);
 }
 private static function getGoogleClient($config)
 {
     $client = new \Google_Client();
     $config = self::getGoogleConfig($config);
     $client->setAuthConfigFile($config);
     $userId = \HttpReceiver\HttpReceiver::get('userId', 'int');
     if (!isset($userId)) {
         $userId = \HttpReceiver\HttpReceiver::get('state', 'int');
     }
     $client->setRedirectUri($config['GOOGLEDRIVE_REDIRECT2']);
     $client->addScope(\Google_Service_Drive::DRIVE);
     return $client;
 }
 public static function getClient()
 {
     $creds = GoogleSessionController::getCreds();
     $client = new Google_Client();
     $env = Config::getEnvironment();
     if ($env == 'local' && $creds->oauth_local_path) {
         $client->setAuthConfigFile($creds->oauth_local_path);
     } else {
         if ($creds->oauth_remote_path) {
             $client->setAuthConfigFile($creds->oauth_remote_path);
         } else {
             $client->setApplicationName($creds->app_name);
             $client->setClientId($creds->client_id);
             $client->setClientSecret($creds->client_secret);
         }
     }
     $client->setRedirectUri(GoogleSessionController::getRedirectURI());
     $hd = Config::get('config.google.hd');
     if ($hd) {
         $client->setHostedDomain($hd);
     }
     $client->setAccessType('offline');
     $client->addScope("https://www.googleapis.com/auth/userinfo.profile");
     $client->addScope("https://www.googleapis.com/auth/userinfo.email");
     $client->setScopes($creds->scopes);
     return $client;
 }
 public function __construct(\Google_Client $googleClient, $clientSecretPath)
 {
     $this->_googleClient = $googleClient;
     $this->_googleClient->setAuthConfigFile($clientSecretPath);
     $this->_googleClient->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/loginGoogle');
     $this->_googleClient->addScope(\Google_Service_Gmail::GMAIL_READONLY);
     $this->_gmailService = new \Google_Service_Gmail($this->_googleClient);
 }
 private function load_google_analytics()
 {
     WooCommerce_Grow::load_google_analytics();
     // We setup the Google Client object
     $this->client = new Google_Client();
     $this->client->setAuthConfigFile(WooCommerce_Grow::get_plugin_path() . '\\ga-config.json');
     $this->client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
     $this->analytics = new Google_Service_Analytics($this->client);
 }
 /**
  * GoogleServiceProvider constructor.
  * @param $config
  */
 public function __construct()
 {
     $this->client = new \Google_Client();
     $this->projectName = config('google_cloud_storage.application');
     $this->projectBucket = config('google_cloud_storage.bucket');
     $this->authJsonFile = config('google_cloud_storage.auth_json_filename');
     $this->client->setApplicationName($this->projectName);
     $this->client->setAuthConfigFile(base_path($this->authJsonFile));
     $this->client->addScope(\Google_Service_Storage::DEVSTORAGE_FULL_CONTROL);
 }
 /**
  * GoogleServiceProvider constructor.
  * @param $config
  */
 public function __construct()
 {
     $this->client = new \Google_Client();
     $this->projectName = config('google_pub_sub.application');
     $this->authJsonFile = config('google_pub_sub.auth_json_filename');
     $this->client->setApplicationName($this->projectName);
     $this->client->setAuthConfigFile(base_path($this->authJsonFile));
     //THIS IS NEEDED FOR CHROME ENV
     //$this->client->useApplicationDefaultCredentials();
     $this->client->addScope(Google_Service_Pubsub::PUBSUB);
 }
Example #9
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;
}
Example #10
0
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName("Study Group Finder");
    $client->setAuthConfigFile(__DIR__ . '/client_secret.json');
    $client->addScope(Google_Service_Calendar::CALENDAR);
    $client->setRedirectUri(current_url());
    if (isset($_SESSION["googleauth"])) {
        $client->setAccessToken($_SESSION["googleauth"]);
        $_SESSION["googleauth"] = NULL;
        return $client;
    }
    if (!isset($_GET['code'])) {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        header("Location: {$authUrl}");
        exit(0);
    }
    $authCode = $_GET['code'];
    // Exchange authorization code for an access token.
    $accessToken = $client->authenticate($authCode);
    $_SESSION["googleauth"] = $accessToken;
    header("Location: calendar.php");
    exit(0);
}
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    global $credentialsPath;
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(GAPI_SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');


    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        die("Please, get token via connect.php");
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client = refreshToken($client);
    }

    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;
}
 /**
  *  get google client
  *  @return Google_Client the authorized client object
  */
 public static function getClient()
 {
     // $scopes = implode(' ', [Google_Service_Gmail::GMAIL_READONLY]);
     /*
         $scopes = [
             'https://www.googleapis.com/auth/gmail.readonly',
             'https://www.googleapis.com/auth/gmail.modify',
             'https://www.googleapis.com/auth/gmail.send',
         ];
     */
     $scopes = ['https://mail.google.com/'];
     $clientSecretFile = conf('gmail.client_secret');
     if (!file_exists($clientSecretFile)) {
         pr('Error: client secret file not found', true);
         pr('Please create "OAuth 2.0 client IDs"');
         pr('login to https://console.developers.google.com/apis/credentials/');
         exit;
     }
     $client = new Google_Client();
     $client->setScopes($scopes);
     $client->setAuthConfigFile($clientSecretFile);
     $client->setAccessType('offline');
     // $client->setApprovalPrompt('force');
     $tokenFile = conf('gmail.access_token');
     $accessToken = self::accessToken($client, $tokenFile);
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($tokenFile, $client->getAccessToken());
     }
     return $client;
 }
Example #14
0
function getClient()
{
    $client = new Google_Client();
    $client->setAuthConfigFile('includes/OAuth2/client_secret.json');
    $client->setAccessToken($_SESSION['access_token']);
    return $client;
}
Example #15
0
 public function __construct(\Google_Client $client)
 {
     $client->setApplicationName("magicpi");
     $client->setScopes([\Google_Service_Calendar::CALENDAR_READONLY]);
     $client->setAuthConfigFile(__DIR__ . "/../config/piauth.json");
     $client->setAccessType('offline');
     $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/auth');
     $this->client = $client;
 }
 /**
  * Returns an authorized API client.
  *
  * @return \Google_Client the authorized client object
  */
 public function getClient()
 {
     $client = new \Google_Client();
     $client->setApplicationName($this->applicationName);
     $client->setScopes(implode(' ', $this->scopes));
     $client->setAuthConfigFile($this->authConfigFile);
     $client->setAccessType('offline');
     $client->setApprovalPrompt('force');
     return $client;
 }
Example #17
0
 private static function getClient()
 {
     $scopes = implode(' ', array(Google_Service_Calendar::CALENDAR));
     $client = new Google_Client();
     $client->setApplicationName('s1704362\'s Study Website');
     $client->setScopes($scopes);
     $client->setAuthConfigFile('app/config/client_secret.json');
     $client->setAccessType('offline');
     return $client;
 }
Example #18
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');
    $client->setRedirectUri('http://localhost/gmail/index.php');
    return $client;
}
 /**
  *
  */
 protected function _setGoogleClient()
 {
     $googleClient = new Google_Client();
     $googleClient->setAuthConfigFile($this->_getConfigFilePath());
     $googleClient->addScope($this->_getScopes());
     $googleClient->setRedirectUri(Router::url(array('plugin' => 'auth_manager', 'controller' => 'media_platform_users', 'action' => 'callback', $this->_getPlatformId()), true));
     // This will force Google to always return the refresh_token.
     $googleClient->setAccessType('offline');
     $googleClient->setApprovalPrompt('force');
     $this->_client = $googleClient;
 }
 private function setGoogleClient()
 {
     $client = new \Google_Client();
     $client->setApplicationName(APPLICATION_NAME);
     $client->setScopes(SCOPES);
     $client->setAuthConfigFile(CLIENT_SECRET_FILE);
     $client->setAccessType('offline');
     $accessToken = file_get_contents(CREDENTIALS_FILE);
     $client->setAccessToken($accessToken);
     $this->refreshAuthToken($client);
     $this->googleClient = $client;
 }
 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)));
 }
 protected function doClean($value)
 {
     $file = parent::doClean($value);
     if ($file instanceof sfValidatedFile) {
         try {
             $client = new Google_Client();
             $client->setAuthConfigFile($file->getTempName());
         } catch (Google_Exception $e) {
             throw new sfValidatorError($this, (string) $e);
         }
     }
     return $file;
 }
function getNewToken()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setHostedDomain('email.wosc.edu');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
    $client->setRedirectUri($GMAIL->callback);
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    global $credentialsPath;
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(GAPI_SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');


    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        $authUrl = $client->createAuthUrl();
        $authCode = false;
        if (isset($_POST['authCode']) && $_POST['authCode']) {
            $authCode = $_POST['authCode'];
        }

        if (!$authCode) {
            printf("Open the following link in your browser:\n<a href='%s' target='_blank'>link</a>\n", $authUrl);
            echo "<form method='post'><input name='authCode'><input type='submit' name='Check auth code'></form>";
            die;
        }

        if ($authCode) {
            // Exchange authorization code for an access token.
            $accessToken = $client->authenticate($authCode);
            if (file_put_contents($credentialsPath, $accessToken)) {
                printf("Credentials saved to %s: " . colorize("SUCCESS", "SUCCESS") . "<br>", $credentialsPath);
            } else {
                printf("Credentials saved to %s: " . colorize("FAILED", "FAILURE") . "<br>", $credentialsPath);
                die;
            }
        } else {
            die("No authCode");
        }
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        echo "Token is Expired. Trying to refresh.. <br>";
        $client = refreshToken($client);
    } else {
        echo "Everything fine<br>";
    }

    return $client;
}
 public static function getClient()
 {
     // $config = self::loadConfig();
     $client = new Google_Client();
     $client->setAuthConfigFile(dirname(__FILE__) . '/client_secret.json');
     $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . FOLDER_APP);
     $client->addScope(Google_Service_Gmail::MAIL_GOOGLE_COM);
     $client->addScope(Google_Service_Gmail::GMAIL_COMPOSE);
     $client->addScope(Google_Service_Gmail::GMAIL_MODIFY);
     $client->addScope('http://www.google.com/m8/feeds/');
     $client->addScope('https://www.googleapis.com/auth/userinfo.email');
     $client->setIncludeGrantedScopes(true);
     $client->setAccessType('offline');
     $client->setApprovalPrompt('force');
     return $client;
 }
function refreshTokenCli()
{
    global $credentialsPath;
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(GAPI_SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
        $client->setAccessToken($accessToken);
    } else {
        logStatusFailure($credentialsPath . " exists");
        closeSession(false);
    }
    refreshToken($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 #28
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;
 }
 /**
  * Create service
  *
  * @param ServiceLocatorInterface $serviceLocator
  *
  * @return mixed
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $client = new \Google_Client();
     $oAuthServiceConfig = $this->getOAuthServiceConfig($serviceLocator, 'google');
     if (isset($oAuthServiceConfig['authConfigFile'])) {
         if (!file_exists($oAuthServiceConfig['authConfigFile'])) {
             throw new GoogleAuthConfigFileNotFound('The file ' . $oAuthServiceConfig['authConfigFile'] . ' was not found.');
         }
         $client->setAuthConfigFile($oAuthServiceConfig['authConfigFile']);
     } else {
         $oAuthServiceConfig = $this->checkRequiredConfigs($serviceLocator, ['clientId', 'clientSecret'], 'google');
         $client->setClientId($oAuthServiceConfig['clientId']);
         $client->setClientSecret($oAuthServiceConfig['clientSecret']);
         /** @var \Zend\Mvc\Router\RouteInterface $router */
         $router = $serviceLocator->get('Router');
         $redirectUri = $router->assemble([], ['name' => 'sta/oAuthConnect/response', 'force_canonical' => true]);
         $client->setRedirectUri($redirectUri);
     }
     return new Google($client);
 }
 function write_to_google_drive($file_name, $content = NULL, $header = NULL, $overwrite = true)
 {
     $fileMetadata = new Google_Service_Drive_DriveFile(array('name' => $file_name, 'mimeType' => 'text/csv'));
     $client = new Google_Client();
     $client->setAuthConfigFile(CLIENT_SECRET_PATH);
     $client->addScope(SCOPES);
     $client->setAccessType("offline");
     $client->setAccessToken($_SESSION['access_token']);
     $service = new Google_Service_Drive($client);
     $sql = "SELECT gdf.id FROM google_drive_files gdf where gdf.name = '" . $file_name . "'";
     error_log($sql);
     $query = $this->db->query($sql);
     $result = current($query->result());
     $file = NULL;
     error_log(json_encode($result));
     if ($result && $result->id) {
         if ($overwrite) {
             $content = $header . $content;
         } else {
             $file_contents = $service->files->get($result->id, array('alt' => 'media'));
             error_log('File Contents: ');
             error_log($file_contents);
             $content = $file_contents . $content;
         }
         error_log('Updating google drive file: ' . $file_name);
         $file = $service->files->update($result->id, $fileMetadata, array('data' => $content, 'mimeType' => 'text/csv', 'uploadType' => 'multipart'));
     } else {
         $content = $header . $content;
         error_log('Creating google drive file: ' . $file_name);
         $file = $service->files->create($fileMetadata, array('data' => $content, 'mimeType' => 'text/csv', 'uploadType' => 'multipart'));
     }
     echo nl2br($content);
     if ($file && $file->id) {
         $sql = "INSERT INTO google_drive_files (id, name) VALUES ('" . $file->id . "', '" . $file_name . "')";
         error_log($sql);
         $query = $this->db->query($sql);
     }
     return $file;
 }