Example #1
0
 /**
  * Login to facebook and get the associated cloudrexx user.
  */
 public function login()
 {
     $client = new \Google_Client();
     $client->setApplicationName('Contrexx Login');
     $client->setClientId($this->applicationData[0]);
     $client->setClientSecret($this->applicationData[1]);
     $client->setRedirectUri(\Cx\Lib\SocialLogin::getLoginUrl(self::OAUTH_PROVIDER));
     $client->setDeveloperKey($this->applicationData[2]);
     $client->setUseObjects(true);
     $client->setApprovalPrompt('auto');
     $client->setScopes(self::$scopes);
     self::$google = new \Google_Oauth2Service($client);
     self::$googleplus = new \Google_PlusService($client);
     if (isset($_GET['code'])) {
         try {
             $client->authenticate();
         } catch (\Google_AuthException $e) {
         }
     }
     if (!$client->getAccessToken()) {
         \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $client->createAuthUrl());
         exit;
     }
     self::$userdata = $this->getUserData();
     $this->getContrexxUser(self::$userdata['oauth_id']);
 }
 /**
  * @return object | $service | Google Analytics Service Object used to run queries 
  **/
 private function createAnalyticsService()
 {
     /** 
      * Create and Authenticate Google Analytics Service Object
      **/
     $client = new Google_Client();
     $client->setApplicationName(GOOGLE_API_APP_NAME);
     /**
      * Makes sure Private Key File exists and is readable. If you get an error, check path in apiConfig.php
      **/
     if (!file_exists(GOOGLE_API_PRIVATE_KEY_FILE)) {
         array_push($GLOBALS['criticalErrors'], "CRITICAL-ERROR: Unable to find GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE);
         criticalErrorOccurred($criticalErrors, $errors);
         exit("CRITICAL-ERROR: Unable to find GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE . ' Backup aborted.');
     } elseif (!is_readable(GOOGLE_API_PRIVATE_KEY_FILE)) {
         array_push($GLOBALS['criticalErrors'], "CRITICAL-ERROR: Unable to read GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE);
         criticalErrorOccurred($criticalErrors, $errors);
         exit("CRITICAL-ERROR: Unable to read GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE . ' Backup aborted.');
     }
     $client->setAssertionCredentials(new Google_AssertionCredentials(GOOGLE_API_SERVICE_EMAIL, array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents(GOOGLE_API_PRIVATE_KEY_FILE)));
     $client->setClientId(GOOGLE_API_SERVICE_CLIENT_ID);
     $client->setUseObjects(true);
     $service = new Google_AnalyticsService($client);
     return $service;
 }
Example #3
0
 public function testSettersGetters()
 {
     $client = new Google_Client();
     $client->setClientId("client1");
     $client->setClientSecret('client1secret');
     $client->setState('1');
     $client->setApprovalPrompt('force');
     $client->setAccessType('offline');
     global $apiConfig;
     $this->assertEquals('client1', $apiConfig['oauth2_client_id']);
     $this->assertEquals('client1secret', $apiConfig['oauth2_client_secret']);
     $client->setRedirectUri('localhost');
     $client->setApplicationName('me');
     $client->setUseObjects(false);
     $this->assertEquals('object', gettype($client->getAuth()));
     $this->assertEquals('object', gettype($client->getCache()));
     $this->assertEquals('object', gettype($client->getIo()));
     $client->setAuthClass('Google_AuthNone');
     $client->setAuthClass('Google_OAuth2');
     try {
         $client->setAccessToken(null);
         die('Should have thrown an Google_AuthException.');
     } catch (Google_AuthException $e) {
         $this->assertEquals('Could not json decode the token', $e->getMessage());
     }
     $token = json_encode(array('access_token' => 'token'));
     $client->setAccessToken($token);
     $this->assertEquals($token, $client->getAccessToken());
 }
Example #4
0
 /**
  * @return \Google_Client
  */
 protected function getGoogleClient($redirectUrl)
 {
     if (!$this->_googleClient) {
         $this->_googleClient = new \Google_Client();
         $this->_googleClient->setUseObjects(TRUE);
         $this->_googleClient->setApplicationName($this->applicationName);
         $this->_googleClient->setAssertionCredentials(new \Google_AssertionCredentials($this->clientMail, array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents($this->keyFile)));
         $this->_googleClient->setClientId($this->clientId);
         $this->_googleClient->setRedirectUri($redirectUrl);
     }
     return $this->_googleClient;
 }
Example #5
0
 /**
  * This method is used to process the second part of authentication workflow, after redirect
  *
  * @return array Array with status and user details
  */
 public function processAuth()
 {
     $ngConnectINI = eZINI::instance('ngconnect.ini');
     $http = eZHTTPTool::instance();
     $clientID = trim($ngConnectINI->variable('LoginMethod_google', 'GoogleClientID'));
     $clientSecret = trim($ngConnectINI->variable('LoginMethod_google', 'GoogleClientSecret'));
     if (empty($clientID) || empty($clientSecret)) {
         return array('status' => 'error', 'message' => 'Google client ID or Google client secret undefined.');
     }
     $code = trim($http->getVariable('code', ''));
     $state = trim($http->getVariable('state', ''));
     if (empty($code) || empty($state)) {
         return array('status' => 'error', 'message' => 'code or state GET parameters undefined.');
     }
     if (!$http->hasSessionVariable('NGConnectOAuthState') || $state != $http->sessionVariable('NGConnectOAuthState')) {
         $http->removeSessionVariable('NGConnectOAuthState');
         return array('status' => 'error', 'message' => 'State parameter does not match stored value.');
     } else {
         $http->removeSessionVariable('NGConnectOAuthState');
     }
     $callbackUri = self::CALLBACK_URI_PART;
     $loginWindowType = trim($ngConnectINI->variable('ngconnect', 'LoginWindowType'));
     if ($loginWindowType == 'popup') {
         $callbackUri = '/layout/set/ngconnect' . self::CALLBACK_URI_PART;
     }
     eZURI::transformURI($callbackUri, false, 'full');
     $scope = self::SCOPE;
     $userScope = trim($ngConnectINI->variable('LoginMethod_google', 'Scope'));
     if (!empty($userScope)) {
         $scope = $userScope . ' ' . $scope;
     }
     $client = new Google_Client();
     $client->setApplicationName(trim($ngConnectINI->variable('LoginMethod_google', 'MethodName')));
     $client->setScopes($scope);
     $client->setClientId($clientID);
     $client->setClientSecret($clientSecret);
     $client->setRedirectUri($callbackUri);
     $client->setUseObjects(true);
     $plus = new Google_PlusService($client);
     $authString = $client->authenticate();
     $accessToken = $client->getAccessToken();
     if (empty($authString) || empty($accessToken)) {
         return array('status' => 'error', 'message' => 'Unable to authenticate to Google.');
     }
     $me = $plus->people->get('me');
     if (!$me instanceof Google_Person) {
         return array('status' => 'error', 'message' => 'Invalid Google user.');
     }
     $result = array('status' => 'success', 'login_method' => 'google', 'id' => $me->id, 'first_name' => !empty($me->name->givenName) ? $me->name->givenName : '', 'last_name' => !empty($me->name->familyName) ? $me->name->familyName : '', 'email' => !empty($me->emails[0]['value']) ? $me->emails[0]['value'] : '', 'picture' => !empty($me->image->url) ? $me->image->url : '');
     return $result;
 }
Example #6
0
 public function __construct()
 {
     parent::__construct();
     $this->callbackurl = 'http://tiny4cocoa.com/homeadmin/settongji/';
     $client = new Google_Client();
     $client->setClientId('70232315343-0nikjc44hcpfk5qt93pe0e21sc2u3ntm.apps.googleusercontent.com');
     $client->setClientSecret('8I4c4toq6hYE6i3BhHhjRrIc');
     $client->setRedirectUri($this->callbackurl);
     $client->setDeveloperKey('AIzaSyBE9EKeqtgJntWuNbDekaPSNvu9ZalXFpE');
     $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
     $client->setUseObjects(true);
     $service = new Google_AnalyticsService($client);
     $this->client = $client;
     $this->service = $service;
 }
Example #7
0
 public function __construct($params)
 {
     if (isset($params['configured']) && $params['configured'] === 'true' && isset($params['client_id']) && isset($params['client_secret']) && isset($params['token'])) {
         $client = new \Google_Client();
         $client->setClientId($params['client_id']);
         $client->setClientSecret($params['client_secret']);
         $client->setScopes(array('https://www.googleapis.com/auth/drive'));
         $client->setUseObjects(true);
         $client->setAccessToken($params['token']);
         $this->service = new \Google_DriveService($client);
         $token = json_decode($params['token'], true);
         $this->id = 'google::' . substr($params['client_id'], 0, 30) . $token['created'];
     } else {
         throw new \Exception('Creating \\OC\\Files\\Storage\\Google storage failed');
     }
 }
function get_google_api_client()
{
    global $api_client_id, $api_client_secret, $api_simple_key, $base_url;
    // Set your cached access token. Remember to replace $_SESSION with a
    // real database or memcached.
    session_start();
    $client = new Google_Client();
    $client->setUseObjects(true);
    $client->setApplicationName('Google Mirror API PHP Quick Start');
    // These are set in config.php
    $client->setClientId($api_client_id);
    $client->setClientSecret($api_client_secret);
    $client->setRedirectUri($base_url . "/oauth2callback.php");
    $client->setScopes(array('https://www.googleapis.com/auth/glass.timeline', 'https://www.googleapis.com/auth/glass.location', 'https://www.googleapis.com/auth/userinfo.profile'));
    return $client;
}
Example #9
0
 public static function getBaseClient($state = null)
 {
     if (!self::$_baseClient) {
         $cfg = self::_getApiConfig();
         $client = new Google_Client();
         $client->setApplicationName($cfg['appName']);
         $client->setClientId($cfg['clientId']);
         $client->setClientSecret($cfg['clientSecret']);
         $client->setRedirectUri(self::_getRedirectUrl());
         $client->setAccessType($cfg['accessType']);
         $client->setUseObjects($cfg['useObjects']);
         if ($state) {
             $client->setState($state);
         }
         self::$_baseClient = $client;
     }
     return self::$_baseClient;
 }
Example #10
0
 public function getClient(Scalr_Environment $environment, $cloudLocation)
 {
     $client = new Google_Client();
     $client->setApplicationName("Scalr GCE");
     $client->setScopes(array('https://www.googleapis.com/auth/compute'));
     $key = base64_decode($environment->getPlatformConfigValue(self::KEY));
     $client->setAssertionCredentials(new Google_AssertionCredentials($environment->getPlatformConfigValue(self::SERVICE_ACCOUNT_NAME), array('https://www.googleapis.com/auth/compute'), $key));
     $client->setUseObjects(true);
     $client->setClientId($environment->getPlatformConfigValue(self::CLIENT_ID));
     $gce = new Google_ComputeService($client);
     //**** Store access token ****//
     $jsonAccessToken = $environment->getPlatformConfigValue(self::ACCESS_TOKEN);
     $accessToken = @json_decode($jsonAccessToken);
     if ($accessToken && $accessToken->created + $accessToken->expires_in > time()) {
         $client->setAccessToken($jsonAccessToken);
     } else {
         $gce->zones->listZones($environment->getPlatformConfigValue(self::PROJECT_ID));
         $token = $client->getAccessToken();
         $environment->setPlatformConfig(array(self::ACCESS_TOKEN => $token));
     }
     return $gce;
 }
Example #11
0
File: Gce.php Project: recipe/scalr
 public function xGetMachineTypesAction()
 {
     $p = PlatformFactory::NewPlatform(SERVER_PLATFORMS::GCE);
     $client = new Google_Client();
     $client->setApplicationName("Scalr GCE");
     $client->setScopes(array('https://www.googleapis.com/auth/compute'));
     $key = base64_decode($this->environment->getPlatformConfigValue(Modules_Platforms_GoogleCE::KEY));
     $client->setAssertionCredentials(new Google_AssertionCredentials($this->environment->getPlatformConfigValue(Modules_Platforms_GoogleCE::SERVICE_ACCOUNT_NAME), array('https://www.googleapis.com/auth/compute'), $key));
     $client->setUseObjects(true);
     $client->setClientId($this->environment->getPlatformConfigValue(Modules_Platforms_GoogleCE::CLIENT_ID));
     $projectId = $this->environment->getPlatformConfigValue(Modules_Platforms_GoogleCE::PROJECT_ID);
     $gceClient = new Google_ComputeService($client);
     $data['types'] = array();
     $data['dbTypes'] = array();
     $types = $gceClient->machineTypes->listMachineTypes($projectId, $this->getParam('cloudLocation'));
     foreach ($types->items as $item) {
         $isEphemeral = substr($item->name, -2) == '-d';
         if (!$isEphemeral) {
             $data['types'][] = array('name' => $item->name, 'description' => "{$item->name} ({$item->description})");
         }
     }
     $this->response->data(array('data' => $data));
 }
Example #12
0
function getGoogleClient()
{
    require_once 'google-api-php-client/src/Google_Client.php';
    require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
    global $google_api;
    extract($google_api);
    $client = new Google_Client();
    $client->setUseObjects(true);
    $client->setAccessType('offline');
    $client->setApplicationName($ApplicationName);
    $client->setClientId($ClientId);
    $client->setClientSecret($ClientSecret);
    $client->setRedirectUri($RedirectUri);
    $client->refreshToken($accessToken);
    $cal = new Google_CalendarService($client);
    return $cal;
}
Example #13
0
 /**
  * Send a request to the UserInfo API to retrieve the user's information.
  *
  * @param String credentials OAuth 2.0 credentials to authorize the request.
  * @return Userinfo User's information.
  */
 public static function getUserInfo($credentials, $client_id, $client_secret)
 {
     require_once CASH_PLATFORM_ROOT . '/lib/google/Google_Client.php';
     require_once CASH_PLATFORM_ROOT . '/lib/google/contrib/Google_Oauth2Service.php';
     $client = new Google_Client();
     $client->setUseObjects(false);
     $client->setClientId($client_id);
     $client->setClientSecret($client_secret);
     $client->setAccessToken($credentials);
     $service = new Google_Oauth2Service($client);
     $user_info = null;
     try {
         $user_info = $service->userinfo->get();
     } catch (Google_Exception $e) {
         // $this->error_message = 'An error occurred: ' . $e->getMessage();
         return false;
     }
     if (is_array($user_info)) {
         return $user_info;
     } else {
         return false;
     }
 }
 public function buildService($userEmail)
 {
     session_start();
     $DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
     $SERVICE_ACCOUNT_EMAIL = '*****@*****.**';
     $SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/Users/shwetasabne/aboutme/shwetasabne/public/resources/API Project-ba0bc0c8779d.p12';
     $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
     $auth = new Google_AssertionCredentials($SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), $key);
     $auth->sub = '*****@*****.**';
     $client = new Google_Client();
     $client->setUseObjects(true);
     $client->setAssertionCredentials($auth);
     //var_dump(new Google_DriveService($client));
     return new Google_DriveService($client);
 }
Example #15
0
function ga_dash_content()
{
    require_once 'functions.php';
    if (!get_option('ga_dash_cachetime') or get_option('ga_dash_cachetime') == 10) {
        update_option('ga_dash_cachetime', "900");
    }
    if (!class_exists('Google_Exception')) {
        require_once 'src/Google_Client.php';
    }
    require_once 'src/contrib/Google_AnalyticsService.php';
    //$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
    $client = new Google_Client();
    $client->setAccessType('offline');
    $client->setApplicationName('Google Analytics Dashboard');
    $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
    if (get_option('ga_dash_userapi')) {
        $client->setClientId(get_option('ga_dash_clientid'));
        $client->setClientSecret(get_option('ga_dash_clientsecret'));
        $client->setDeveloperKey(get_option('ga_dash_apikey'));
    } else {
        $client->setClientId('65556128781.apps.googleusercontent.com');
        $client->setClientSecret('Kc7888wgbc_JbeCpbFjnYpwE');
        $client->setDeveloperKey('AIzaSyBG7LlUoHc29ZeC_dsShVaBEX15SfRl_WY');
    }
    $service = new Google_AnalyticsService($client);
    if (ga_dash_get_token()) {
        $token = ga_dash_get_token();
        $client->setAccessToken($token);
    }
    if (!$client->getAccessToken()) {
        $authUrl = $client->createAuthUrl();
        if (!isset($_REQUEST['ga_dash_authorize'])) {
            if (!current_user_can('manage_options')) {
                _e("Ask an admin to authorize this Application", 'ga-dash');
                return;
            }
            echo '<div style="padding:20px;">' . __("Use this link to get your access code:", 'ga-dash') . ' <a href="' . $authUrl . '" target="_blank">' . __("Get Access Code", 'ga-dash') . '</a>';
            echo '<form name="input" action="#" method="get">
						<p><b>' . __("Access Code:", 'ga-dash') . ' </b><input type="text" name="ga_dash_code" value="" size="61"></p>
						<input type="submit" class="button button-primary" name="ga_dash_authorize" value="' . __("Save Access Code", 'ga-dash') . '"/>
					</form>
				</div>';
            return;
        } else {
            if ($_REQUEST['ga_dash_code']) {
                $client->authenticate($_REQUEST['ga_dash_code']);
                ga_dash_store_token($client->getAccessToken());
            } else {
                $adminurl = admin_url("#ga-dash-widget");
                echo '<script> window.location="' . $adminurl . '"; </script> ';
            }
        }
    }
    if (current_user_can('manage_options')) {
        if (isset($_REQUEST['ga_dash_profiles'])) {
            update_option('ga_dash_tableid', $_REQUEST['ga_dash_profiles']);
        }
        try {
            $client->setUseObjects(true);
            $profile_switch = "";
            $serial = 'gadash_qr1';
            $transient = get_transient($serial);
            if (empty($transient)) {
                $profiles = $service->management_profiles->listManagementProfiles('~all', '~all');
                set_transient($serial, $profiles, 60 * 60 * 24);
            } else {
                $profiles = $transient;
            }
            //print_r($profiles);
            $items = $profiles->getItems();
            $profile_switch .= '<form><select id="ga_dash_profiles" name="ga_dash_profiles" onchange="this.form.submit()">';
            if (count($items) != 0) {
                $ga_dash_profile_list = "";
                foreach ($items as &$profile) {
                    if (!get_option('ga_dash_tableid')) {
                        update_option('ga_dash_tableid', $profile->getId());
                    }
                    $profile_switch .= '<option value="' . $profile->getId() . '"';
                    if (get_option('ga_dash_tableid') == $profile->getId()) {
                        $profile_switch .= "selected='yes'";
                    }
                    $profile_switch .= '>' . ga_dash_get_profile_domain($profile->getwebsiteUrl()) . '</option>';
                    $ga_dash_profile_list[] = array($profile->getName(), $profile->getId(), $profile->getwebPropertyId(), $profile->getwebsiteUrl());
                }
                update_option('ga_dash_profile_list', $ga_dash_profile_list);
            }
            $profile_switch .= "</select></form><br />";
            $client->setUseObjects(false);
        } catch (Google_ServiceException $e) {
            echo ga_dash_pretty_error($e);
            return;
        }
    }
    if (current_user_can('manage_options')) {
        if (get_option('ga_dash_jailadmins')) {
            if (get_option('ga_dash_tableid_jail')) {
                $projectId = get_option('ga_dash_tableid_jail');
            } else {
                _e("Ask an admin to asign a Google Analytics Profile", 'ga-dash');
                return;
            }
        } else {
            echo $profile_switch;
            $projectId = get_option('ga_dash_tableid');
        }
    } else {
        if (get_option('ga_dash_tableid_jail')) {
            $projectId = get_option('ga_dash_tableid_jail');
        } else {
            _e("Ask an admin to asign a Google Analytics Profile", 'ga-dash');
            return;
        }
    }
    if (isset($_REQUEST['query'])) {
        $query = $_REQUEST['query'];
    } else {
        $query = "visits";
    }
    if (isset($_REQUEST['period'])) {
        $period = $_REQUEST['period'];
    } else {
        $period = "last30days";
    }
    switch ($period) {
        case 'today':
            $from = date('Y-m-d');
            $to = date('Y-m-d');
            break;
        case 'yesterday':
            $from = date('Y-m-d', time() - 24 * 60 * 60);
            $to = date('Y-m-d', time() - 24 * 60 * 60);
            break;
        case 'last7days':
            $from = date('Y-m-d', time() - 7 * 24 * 60 * 60);
            $to = date('Y-m-d');
            break;
        case 'last14days':
            $from = date('Y-m-d', time() - 14 * 24 * 60 * 60);
            $to = date('Y-m-d');
            break;
        default:
            $from = date('Y-m-d', time() - 30 * 24 * 60 * 60);
            $to = date('Y-m-d');
            break;
    }
    switch ($query) {
        case 'visitors':
            $title = __("Visitors", 'ga-dash');
            break;
        case 'pageviews':
            $title = __("Page Views", 'ga-dash');
            break;
        case 'visitBounceRate':
            $title = __("Bounce Rate", 'ga-dash');
            break;
        case 'organicSearches':
            $title = __("Organic Searches", 'ga-dash');
            break;
        default:
            $title = __("Visits", 'ga-dash');
    }
    $metrics = 'ga:' . $query;
    $dimensions = 'ga:year,ga:month,ga:day';
    try {
        $serial = 'gadash_qr2' . str_replace(array('ga:', ',', '-', date('Y')), "", $projectId . $from . $to . $metrics);
        $transient = get_transient($serial);
        if (empty($transient)) {
            $data = $service->data_ga->get('ga:' . $projectId, $from, $to, $metrics, array('dimensions' => $dimensions));
            set_transient($serial, $data, get_option('ga_dash_cachetime'));
        } else {
            $data = $transient;
        }
    } catch (Google_ServiceException $e) {
        echo ga_dash_pretty_error($e);
        return;
    }
    $ga_dash_statsdata = "";
    for ($i = 0; $i < $data['totalResults']; $i++) {
        $ga_dash_statsdata .= "['" . $data['rows'][$i][0] . "-" . $data['rows'][$i][1] . "-" . $data['rows'][$i][2] . "'," . round($data['rows'][$i][3], 2) . "],";
    }
    $ga_dash_statsdata = rtrim($ga_dash_statsdata, ',');
    $metrics = 'ga:visits,ga:visitors,ga:pageviews,ga:visitBounceRate,ga:organicSearches,ga:timeOnSite';
    $dimensions = 'ga:year';
    try {
        $serial = 'gadash_qr3' . str_replace(array('ga:', ',', '-', date('Y')), "", $projectId . $from . $to);
        $transient = get_transient($serial);
        if (empty($transient)) {
            $data = $service->data_ga->get('ga:' . $projectId, $from, $to, $metrics, array('dimensions' => $dimensions));
            set_transient($serial, $data, get_option('ga_dash_cachetime'));
        } else {
            $data = $transient;
        }
    } catch (Google_ServiceException $e) {
        echo ga_dash_pretty_error($e);
        return;
    }
    if (get_option('ga_dash_style') == "light") {
        $css = "colors:['gray','darkgray'],";
        $colors = "black";
    } else {
        $css = "";
        $colors = "blue";
    }
    $code = '<script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(ga_dash_callback);

	  function ga_dash_callback(){
			ga_dash_drawstats();
			if(typeof ga_dash_drawmap == "function"){
				ga_dash_drawmap();
			}
			if(typeof ga_dash_drawpgd == "function"){
				ga_dash_drawpgd();
			}			
			if(typeof ga_dash_drawrd == "function"){
				ga_dash_drawrd();
			}
			if(typeof ga_dash_drawsd == "function"){
				ga_dash_drawsd();
			}
			if(typeof ga_dash_drawtraffic == "function"){
				ga_dash_drawtraffic();
			}			
	  }	

      function ga_dash_drawstats() {
        var data = google.visualization.arrayToDataTable([' . "\n          ['" . __("Date", 'ga-dash') . "', '" . $title . "']," . $ga_dash_statsdata . "  \n        ]);\n\n        var options = {\n\t\t  legend: {position: 'none'},\t\n\t\t  pointSize: 3," . $css . "\n          title: '" . $title . "',\n\t\t  chartArea: {width: '85%'},\n          hAxis: { title: '" . __("Date", 'ga-dash') . "',  titleTextStyle: {color: '" . $colors . "'}, showTextEvery: 5}\n\t\t};\n\n        var chart = new google.visualization.AreaChart(document.getElementById('ga_dash_statsdata'));\n\t\tchart.draw(data, options);\n\t\t\n      }";
    if (get_option('ga_dash_map')) {
        $ga_dash_visits_country = ga_dash_visits_country($service, $projectId, $from, $to);
        if ($ga_dash_visits_country) {
            $code .= '
			google.load("visualization", "1", {packages:["geochart"]})
			function ga_dash_drawmap() {
			var data = google.visualization.arrayToDataTable([' . "\n\t\t\t  ['" . __("Country", 'ga-dash') . "', '" . __("Visits", 'ga-dash') . "']," . $ga_dash_visits_country . "  \n\t\t\t]);\n\t\t\t\n\t\t\tvar options = {\n\t\t\t\tcolors: ['white', '" . $colors . "']\n\t\t\t};\n\t\t\t\n\t\t\tvar chart = new google.visualization.GeoChart(document.getElementById('ga_dash_mapdata'));\n\t\t\tchart.draw(data, options);\n\t\t\t\n\t\t  }";
        }
    }
    if (get_option('ga_dash_traffic')) {
        $ga_dash_traffic_sources = ga_dash_traffic_sources($service, $projectId, $from, $to);
        $ga_dash_new_return = ga_dash_new_return($service, $projectId, $from, $to);
        if ($ga_dash_traffic_sources and $ga_dash_new_return) {
            $code .= '
			google.load("visualization", "1", {packages:["corechart"]})
			function ga_dash_drawtraffic() {
			var data = google.visualization.arrayToDataTable([' . "\n\t\t\t  ['" . __("Source", 'ga-dash') . "', '" . __("Visits", 'ga-dash') . "']," . $ga_dash_traffic_sources . '  
			]);

			var datanvr = google.visualization.arrayToDataTable([' . "\n\t\t\t  ['" . __("Type", 'ga-dash') . "', '" . __("Visits", 'ga-dash') . "']," . $ga_dash_new_return . "  \n\t\t\t]);\n\t\t\t\n\t\t\tvar chart = new google.visualization.PieChart(document.getElementById('ga_dash_trafficdata'));\n\t\t\tchart.draw(data, {\n\t\t\t\tis3D: true,\n\t\t\t\ttooltipText: 'percentage',\n\t\t\t\tlegend: 'none',\n\t\t\t\ttitle: '" . __("Traffic Sources", 'ga-dash') . "'\n\t\t\t});\n\t\t\t\n\t\t\tvar chart1 = new google.visualization.PieChart(document.getElementById('ga_dash_nvrdata'));\n\t\t\tchart1.draw(datanvr,  {\n\t\t\t\tis3D: true,\n\t\t\t\ttooltipText: 'percentage',\n\t\t\t\tlegend: 'none',\n\t\t\t\ttitle: '" . __("New vs. Returning", 'ga-dash') . "'\n\t\t\t});\n\t\t\t\n\t\t  }";
        }
    }
    if (get_option('ga_dash_pgd')) {
        $ga_dash_top_pages = ga_dash_top_pages($service, $projectId, $from, $to);
        if ($ga_dash_top_pages) {
            $code .= '
			google.load("visualization", "1", {packages:["table"]})
			function ga_dash_drawpgd() {
			var data = google.visualization.arrayToDataTable([' . "\n\t\t\t  ['" . __("Top Pages", 'ga-dash') . "', '" . __("Visits", 'ga-dash') . "']," . $ga_dash_top_pages . "  \n\t\t\t]);\n\t\t\t\n\t\t\tvar options = {\n\t\t\t\tpage: 'enable',\n\t\t\t\tpageSize: 6,\n\t\t\t\twidth: '100%'\n\t\t\t};        \n\t\t\t\n\t\t\tvar chart = new google.visualization.Table(document.getElementById('ga_dash_pgddata'));\n\t\t\tchart.draw(data, options);\n\t\t\t\n\t\t  }";
        }
    }
    if (get_option('ga_dash_rd')) {
        $ga_dash_top_referrers = ga_dash_top_referrers($service, $projectId, $from, $to);
        if ($ga_dash_top_referrers) {
            $code .= '
			google.load("visualization", "1", {packages:["table"]})
			function ga_dash_drawrd() {
			var datar = google.visualization.arrayToDataTable([' . "\n\t\t\t  ['" . __("Top Referrers", 'ga-dash') . "', '" . __("Visits", 'ga-dash') . "']," . $ga_dash_top_referrers . "  \n\t\t\t]);\n\t\t\t\n\t\t\tvar options = {\n\t\t\t\tpage: 'enable',\n\t\t\t\tpageSize: 6,\n\t\t\t\twidth: '100%'\n\t\t\t};        \n\t\t\t\n\t\t\tvar chart = new google.visualization.Table(document.getElementById('ga_dash_rdata'));\n\t\t\tchart.draw(datar, options);\n\t\t\t\n\t\t  }";
        }
    }
    if (get_option('ga_dash_sd')) {
        $ga_dash_top_searches = ga_dash_top_searches($service, $projectId, $from, $to);
        if ($ga_dash_top_searches) {
            $code .= '
			google.load("visualization", "1", {packages:["table"]})
			function ga_dash_drawsd() {
			
			var datas = google.visualization.arrayToDataTable([' . "\n\t\t\t  ['" . __("Top Searches", 'ga-dash') . "', '" . __("Visits", 'ga-dash') . "']," . $ga_dash_top_searches . "  \n\t\t\t]);\n\t\t\t\n\t\t\tvar options = {\n\t\t\t\tpage: 'enable',\n\t\t\t\tpageSize: 6,\n\t\t\t\twidth: '100%'\n\t\t\t};        \n\t\t\t\n\t\t\tvar chart = new google.visualization.Table(document.getElementById('ga_dash_sdata'));\n\t\t\tchart.draw(datas, options);\n\t\t\t\n\t\t  }";
        }
    }
    $code .= "</script>";
    $code .= "</script>";
    $ga_button_style = get_option('ga_dash_style') == 'light' ? 'button' : 'gabutton';
    $code .= '<div id="ga-dash">
	<center>
		<div id="buttons_div">
		
			<input class="' . $ga_button_style . '" type="button" value="' . __("Today", 'ga-dash') . '" onClick="window.location=\'?period=today&query=' . $query . '\'" />
			<input class="' . $ga_button_style . '" type="button" value="' . __("Yesterday", 'ga-dash') . '" onClick="window.location=\'?period=yesterday&query=' . $query . '\'" />
			<input class="' . $ga_button_style . '" type="button" value="' . __("Last 7 days", 'ga-dash') . '" onClick="window.location=\'?period=last7days&query=' . $query . '\'" />
			<input class="' . $ga_button_style . '" type="button" value="' . __("Last 14 days", 'ga-dash') . '" onClick="window.location=\'?period=last14days&query=' . $query . '\'" />
			<input class="' . $ga_button_style . '" type="button" value="' . __("Last 30 days", 'ga-dash') . '" onClick="window.location=\'?period=last30days&query=' . $query . '\'" />
		
		</div>
		
		<div id="ga_dash_statsdata"></div>
		<div id="details_div">
			
			<table class="gatable" cellpadding="4">
			<tr>
			<td width="24%">' . __("Visits:", 'ga-dash') . '</td>
			<td width="12%" class="gavalue"><a href="?query=visits&period=' . $period . '" class="gatable">' . $data['rows'][0][1] . '</td>
			<td width="24%">' . __("Visitors:", 'ga-dash') . '</td>
			<td width="12%" class="gavalue"><a href="?query=visitors&period=' . $period . '" class="gatable">' . $data['rows'][0][2] . '</a></td>
			<td width="24%">' . __("Page Views:", 'ga-dash') . '</td>
			<td width="12%" class="gavalue"><a href="?query=pageviews&period=' . $period . '" class="gatable">' . $data['rows'][0][3] . '</a></td>
			</tr>
			<tr>
			<td>' . __("Bounce Rate:", 'ga-dash') . '</td>
			<td class="gavalue"><a href="?query=visitBounceRate&period=' . $period . '" class="gatable">' . round($data['rows'][0][4], 2) . '%</a></td>
			<td>' . __("Organic Search:", 'ga-dash') . '</td>
			<td class="gavalue"><a href="?query=organicSearches&period=' . $period . '" class="gatable">' . $data['rows'][0][5] . '</a></td>
			<td>' . __("Pages per Visit:", 'ga-dash') . '</td>
			<td class="gavalue"><a href="#" class="gatable">' . ($data['rows'][0][1] ? round($data['rows'][0][3] / $data['rows'][0][1], 2) : '0') . '</a></td>
			</tr>
			</table>
					
		</div>';
    if (get_option('ga_dash_map')) {
        $code .= '<br /><h3>' . __("Visits by Country", 'ga-dash') . '</h3>
		<div id="ga_dash_mapdata"></div>';
    }
    if (get_option('ga_dash_traffic')) {
        $code .= '<br /><h3>' . __("Traffic Overview", 'ga-dash') . '</h3>
		<table width="100%"><tr><td width="50%"><div id="ga_dash_trafficdata"></div></td><td width="50%"><div id="ga_dash_nvrdata"></div></td></tr></table>';
    }
    $code .= '</center>		
	</div>';
    if (get_option('ga_dash_pgd')) {
        $code .= '<div id="ga_dash_pgddata"></div>';
    }
    if (get_option('ga_dash_rd')) {
        $code .= '<div id="ga_dash_rdata"></div>';
    }
    if (get_option('ga_dash_sd')) {
        $code .= '<div id="ga_dash_sdata"></div>';
    }
    echo $code;
}
Example #16
0
 public function deleteGoogleCalendarEvent($action)
 {
     try {
         // catch google exceptions so the whole app doesn't crash if google has a problem syncing
         $admin = Yii::app()->settings;
         if ($admin->googleIntegration) {
             if (isset($this->syncGoogleCalendarId) && $this->syncGoogleCalendarId) {
                 // Google Calendar Libraries
                 $timezone = date_default_timezone_get();
                 require_once "protected/extensions/google-api-php-client/src/Google_Client.php";
                 require_once "protected/extensions/google-api-php-client/src/contrib/Google_CalendarService.php";
                 date_default_timezone_set($timezone);
                 $client = new Google_Client();
                 $client->setClientId($admin->googleClientId);
                 $client->setClientSecret($admin->googleClientSecret);
                 //$client->setDeveloperKey($admin->googleAPIKey);
                 $client->setAccessToken($this->syncGoogleCalendarAccessToken);
                 $client->setUseObjects(true);
                 // return objects instead of arrays
                 $googleCalendar = new Google_CalendarService($client);
                 $googleCalendar->events->delete($this->syncGoogleCalendarId, $action->syncGoogleCalendarEventId);
             }
         }
     } catch (Exception $e) {
         // We may want to look into handling this better, or bugs will cause silent failures.
     }
 }
 function GoogleAPI_get_service()
 {
     $client_id = GOOGLE_API_CLIENT_ID;
     $service_account_name = GOOGLE_API_ACCOUNT_NAME;
     $key_file = GOOGLE_API_KEY_FILE;
     $service = null;
     $profile_id = null;
     try {
         $client = new \Google_Client();
         $client->setApplicationName("Test API App");
         $key = file_get_contents($key_file);
         $client->setAssertionCredentials(new \Google_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/analytics.readonly'), $key));
         $client->setClientId($client_id);
         $client->setUseObjects(true);
         $service = new \Google_AnalyticsService($client);
         $profile_id = $this->GoogleAPI_get_first_profile_id($service);
     } catch (Exception $e) {
     }
     if ($service && $profile_id) {
         return array($service, $profile_id);
     } else {
         echo "There was a problem connecting to the Google API\n";
         return array(null, null);
     }
 }
    function gglnltcs_authenticate()
    {
        global $gglnltcs_options, $gglnltcs_plugin_info;
        require_once 'google-api-php-client/api-code/Google_Client.php';
        require_once 'google-api-php-client/api-code/contrib/Google_AnalyticsService.php';
        $client = new Google_Client();
        $client->setApplicationName('Google Analytics by BestWebSoft');
        $client->setClientId('714548546682-ai821bsdfn2th170q8ofprgfmh5ch7cn.apps.googleusercontent.com');
        $client->setClientSecret('pyBXulcOqPhQGzKiW4kehZZB');
        $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
        $client->setDeveloperKey('AIzaSyDA7L2CZgY4ud4vv6rw0Yu4GUDyfbRw0f0');
        $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
        $client->setUseObjects(true);
        /* If getAccessToken() was successful */
        /* We have an authorized user and can display his website stats.*/
        $analytics = new Google_AnalyticsService($client);
        /* This will be executed if user get on the page in the first time. */
        if (isset($_POST['code'])) {
            if (empty($_POST['code'])) {
                $redirect = false;
            } else {
                /* This will be executed after user has submitted the form. The post['code'] is set.*/
                try {
                    /* We got here from the redirect from a successful authorization grant,
                     * try to fetch the access token. */
                    $client->authenticate(stripslashes(esc_html($_POST['code'])));
                    $redirect = true;
                } catch (Google_AuthException $e) {
                    /* If user passes invalid Google Authentication Code. */
                    $redirect = false;
                }
                /* Save Access Token to the database and reload the page. */
                if ($redirect && check_admin_referer(plugin_basename(__FILE__), 'gglnltcs_nonce_name')) {
                    $gglnltcs_options['token'] = $client->getAccessToken();
                    update_option('gglnltcs_options', $gglnltcs_options);
                    gglnltcs_line_chart_tab($analytics);
                }
            }
        }
        /* Enter your Google Authentication Code in this box. */
        if (!isset($_POST['code']) || isset($_POST['code']) && $redirect === false) {
            /*The post['code'] has not been passed yet, so let us offer the user to enter the Google Authentication Code.
             * First we need to redirect user to the Google Authorization page.
             * For this reason we create an URL to obtain user authorization. */
            $authUrl = $client->createAuthUrl();
            ?>
			<div class="gglnltcs-text-information">
				<p><?php 
            _e("In order to use Google Analytics by BestWebSoft plugin, you must be signed in with a registered Google Account email address and password. If you don't have Google Account you can create it", 'bws-google-analytics');
            ?>
 <a href="https://www.google.com/accounts/NewAccount" target="_blank"><?php 
            _e('here', 'bws-google-analytics');
            ?>
.</a></p>
				<input id="gglnltcs-google-sign-in" type="button" class="button-primary" onclick="window.open('<?php 
            echo $authUrl;
            ?>
', 'activate','width=640, height=480, menubar=0, status=0, location=0, toolbar=0')" value="<?php 
            _e('Authenticate with your Google Account', 'bws-google-analytics');
            ?>
">
				<noscript>
					<div class="button-primary gglnltcs-google-sign-in">
						<a href="<?php 
            echo $authUrl;
            ?>
" target="_blanket"><?php 
            _e('Or Click Here If You Have Disabled Javascript', 'bws-google-analytics');
            ?>
</a>
					</div>
				</noscript>
				<p class="gglnltcs-authentication-instructions"><?php 
            _e('When you finish authorization process you will get Google Authentication Code. You must enter this code in the field below and press "Start Plugin" button. This code will be used to get an Authentication Token so you can access your website stats.', 'bws-google-analytics');
            ?>
</p>
				<form id="gglnltcs-authentication-form" method="post" action="admin.php?page=bws-google-analytics.php">
					<?php 
            wp_nonce_field(plugin_basename(__FILE__), 'gglnltcs_nonce_name');
            ?>
					<p><input id="gglnltcs-authentication-code-input" type="text" name="code"><input type="submit" class="button-primary" value="<?php 
            _e('Start Plugin', 'bws-google-analytics');
            ?>
"></p>
				</form>
			</div><?php 
            /* This message will appear if user enter invalid Google Authentication Code.
             * Invalid code will cause exception in the $client->authenticate method. */
            if (isset($_POST['code']) && $redirect === false) {
                ?>
				<p><span class="gglnltcs-unsuccess-message"><?php 
                _e('Invalid code. Please, try again.', 'bws-google-analytics');
                ?>
</span></p><?php 
            }
            bws_plugin_reviews_block($gglnltcs_plugin_info['Name'], 'bws-google-analytics');
        }
    }
function cloud_scrivi_calendar($evento_descr, $evento_start, $evento_durata = '+2 hours', $evento_location = '', $event_id = null)
{
    $evento_descr = $evento_descr;
    $evento_start1 = strtotime($evento_start);
    $evento_end1 = strtotime($evento_start . $evento_durata);
    $evento_location = $evento_location;
    /*************** DA QUI IN GIU NON TOCCHEREI PIU NULLA...  ******************/
    $app_name = 'allarrembaggio';
    $client_id = '1034795448812-gghclbbghnvnmotg6as7524fraeojfnh.apps.googleusercontent.com';
    $email_address = '*****@*****.**';
    $key_file = plugin_dir_path(__FILE__) . 'google-api-php-client/allarrembaggio-85318f0a4e9d.p12';
    $calendar_id = '*****@*****.**';
    $evento_start = gmdate('Y-m-d\\TH:i:s', $evento_start1);
    $evento_end = gmdate('Y-m-d\\TH:i:s', $evento_end1);
    require_once "google-api-php-client/src/Google_Client.php";
    require_once "google-api-php-client/src/contrib/Google_CalendarService.php";
    $client = new Google_Client();
    $client->setUseObjects(true);
    $client->setApplicationName($app_name);
    $client->setClientId($client_id);
    $client->setAssertionCredentials(new Google_AssertionCredentials($email_address, array("https://www.googleapis.com/auth/calendar"), file_get_contents($key_file)));
    //setAssertionCredentials
    $service = new Google_CalendarService($client);
    $event = new Google_Event();
    $event->setSummary($evento_descr);
    $event->setLocation($evento_location);
    $start = new Google_EventDateTime();
    $start->setDateTime($evento_start);
    $start->setTimeZone('Europe/Rome');
    $event->setStart($start);
    $end = new Google_EventDateTime();
    $end->setDateTime($evento_end);
    $end->setTimeZone('Europe/Rome');
    $event->setEnd($end);
    //--prima di crearlo, elimino eventuali eventi
    if ($event_id != null) {
        $service->events->delete($calendar_id, $event_id);
    }
    //--creo l'evento
    $new_event = null;
    try {
        $new_event = $service->events->insert($calendar_id, $event);
        $new_event_id = $new_event->getId();
    } catch (Google_ServiceException $e) {
        syslog(LOG_ERR, $e->getMessage());
    }
    $output = null;
    $output = $service->events->get($calendar_id, $new_event->getId());
    $output = $output->getId();
    return $output;
}
Example #20
0
 public function indexAction()
 {
     ########## Google Settings.. Client ID, Client Secret #############
     $google_client_id = '787369762880-65kvt8cblmlm653k5gcks9uipmn401qo.apps.googleusercontent.com';
     $google_client_secret = 'Ya__r8ROl0oqKO5hb3JpRJlF';
     $google_redirect_url = "http://aliinfotech.com/colinkr/admin/gd/index";
     $page_url_prefix = 'http://aliinfotech.com';
     ########## Google analytics Settings.. #############
     $google_analytics_profile_id = 'ga:106789249';
     //Analytics site Profile ID
     $google_analytics_dimensions = 'ga:fullReferrer,ga:sourceMedium,ga:socialNetwork';
     //no change needed (optional)
     $google_analytics_metrics = 'ga:organicSearches';
     //no change needed (optional)
     $google_analytics_sort_by = '-ga:organicSearches';
     //no change needed (optional)
     //$google_analytics_max_results   = '20'; //no change needed (optional)
     require_once APPLICATION_PATH . '/../library/GoogleClientApi/Google_Client.php';
     require_once APPLICATION_PATH . '/../library/GoogleClientApi/contrib/Google_AnalyticsService.php';
     // Initialise the Google Client object
     $gClient = new Google_Client();
     $gClient->setApplicationName('Colinkr');
     $gClient->setClientId($google_client_id);
     $gClient->setClientSecret($google_client_secret);
     $gClient->setRedirectUri($google_redirect_url);
     $gClient->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
     $gClient->setUseObjects(true);
     $val = $this->_request->getParam("logout");
     if ($val == "1") {
         unset($_SESSION['token']);
     }
     //authenticate user
     if (isset($_GET['code'])) {
         $gClient->authenticate();
         $token = $gClient->getAccessToken();
         $_SESSION["token"] = $token;
         header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
     }
     if (!$gClient->getAccessToken() && !isset($_SESSION['token'])) {
         $authUrl = $gClient->createAuthUrl();
         $this->view->authUrl = $authUrl;
     }
     //check for session variable
     if (isset($_SESSION["token"])) {
         //set start date to previous month
         $start_date = date("Y-m-d", strtotime("-1 month"));
         //end date as today
         $end_date = date("Y-m-d");
         try {
             //set access token
             $gClient->setAccessToken($_SESSION["token"]);
             //create analytics services object
             $service = new Google_AnalyticsService($gClient);
             //analytics parameters (check configuration file)
             $params = array('dimensions' => $google_analytics_dimensions, 'sort' => $google_analytics_sort_by);
             //'filters' => 'ga:medium==organic','max-results' => $google_analytics_max_results);
             //get results from google analytics
             $by_search = $service->data_ga->get($google_analytics_profile_id, $start_date, $end_date, $google_analytics_metrics, $params);
             $google_analytics_dimensions = 'ga:userType,ga:sessionCount,ga:browser,ga:country,ga:region';
             $google_analytics_metrics = 'ga:users';
             $google_analytics_sort_by = '-ga:users';
             $params = array('dimensions' => $google_analytics_dimensions, 'sort' => $google_analytics_sort_by);
             //,'max-results' => $google_analytics_max_results);
             $by_user_type = $service->data_ga->get($google_analytics_profile_id, $start_date, $end_date, $google_analytics_metrics, $params);
             $google_analytics_dimensions = 'ga:socialInteractionNetwork,ga:socialInteractionAction,ga:socialInteractionTarget';
             $google_analytics_metrics = 'ga:socialInteractions';
             $google_analytics_sort_by = '-ga:socialInteractions';
             $params = array('dimensions' => $google_analytics_dimensions, 'sort' => $google_analytics_sort_by);
             //,'max-results' => $google_analytics_max_results);
             $by_social_interactions = $service->data_ga->get($google_analytics_profile_id, $start_date, $end_date, $google_analytics_metrics, $params);
             $google_analytics_dimensions = 'ga:date,ga:pagePath,ga:operatingSystem,ga:userType,ga:source';
             $google_analytics_metrics = 'ga:pageviews';
             $google_analytics_sort_by = '-ga:date';
             $params = array('dimensions' => $google_analytics_dimensions, 'sort' => $google_analytics_sort_by);
             //,'max-results' => $google_analytics_max_results);
             $by_pageviews = $service->data_ga->get($google_analytics_profile_id, $start_date, $end_date, $google_analytics_metrics, $params);
             //var_dump($by_search->getRows());return;
             $this->view->by_user_type = $by_user_type;
             $this->view->by_search = $by_search;
             $this->view->by_social_interactions = $by_social_interactions;
             $this->view->by_pageviews = $by_pageviews;
         } catch (Exception $e) {
             //do we have an error?
             echo $e->getMessage();
             //display error
         }
     }
 }
Example #21
0
 public function xSaveGceAction()
 {
     $pars = array();
     $enabled = false;
     if ($this->getParam('gce_is_enabled')) {
         $enabled = true;
         $pars[Modules_Platforms_GoogleCE::CLIENT_ID] = trim($this->checkVar(Modules_Platforms_GoogleCE::CLIENT_ID, 'string', "GCE Cient ID required"));
         $pars[Modules_Platforms_GoogleCE::SERVICE_ACCOUNT_NAME] = trim($this->checkVar(Modules_Platforms_GoogleCE::SERVICE_ACCOUNT_NAME, 'string', "GCE email (service account name) required"));
         $pars[Modules_Platforms_GoogleCE::PROJECT_ID] = trim($this->checkVar(Modules_Platforms_GoogleCE::PROJECT_ID, 'password', "GCE Project ID required"));
         $pars[Modules_Platforms_GoogleCE::KEY] = base64_encode($this->checkVar(Modules_Platforms_GoogleCE::KEY, 'file', "GCE Private Key required", null, true));
         if (!count($this->checkVarError)) {
             if ($pars[Modules_Platforms_GoogleCE::CLIENT_ID] != $this->env->getPlatformConfigValue(Modules_Platforms_GoogleCE::CLIENT_ID) or $pars[Modules_Platforms_GoogleCE::SERVICE_ACCOUNT_NAME] != $this->env->getPlatformConfigValue(Modules_Platforms_GoogleCE::SERVICE_ACCOUNT_NAME) or $pars[Modules_Platforms_GoogleCE::PROJECT_ID] != $this->env->getPlatformConfigValue(Modules_Platforms_GoogleCE::PROJECT_ID) or $pars[Modules_Platforms_GoogleCE::KEY] != $this->env->getPlatformConfigValue(Modules_Platforms_GoogleCE::KEY)) {
                 try {
                     $client = new Google_Client();
                     $client->setApplicationName("Scalr GCE");
                     $client->setScopes(array('https://www.googleapis.com/auth/compute'));
                     $key = base64_decode($pars[Modules_Platforms_GoogleCE::KEY]);
                     $client->setAssertionCredentials(new Google_AssertionCredentials($pars[Modules_Platforms_GoogleCE::SERVICE_ACCOUNT_NAME], array('https://www.googleapis.com/auth/compute'), $key));
                     $client->setUseObjects(true);
                     $client->setClientId($pars[Modules_Platforms_GoogleCE::CLIENT_ID]);
                     $gce = new Google_ComputeService($client);
                     $gce->zones->listZones($pars[Modules_Platforms_GoogleCE::PROJECT_ID]);
                 } catch (Exception $e) {
                     throw new Exception(_("Provided GCE credentials are incorrect: ({$e->getMessage()})"));
                 }
             }
         } else {
             $this->response->failure();
             $this->response->data(array('errors' => $this->checkVarError));
             return;
         }
     }
     $this->db->BeginTrans();
     try {
         $this->env->enablePlatform(SERVER_PLATFORMS::GCE, $enabled);
         if ($enabled) {
             $this->env->setPlatformConfig($pars);
         }
         if (!$this->user->getAccount()->getSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED)) {
             $this->user->getAccount()->setSetting(Scalr_Account::SETTING_DATE_ENV_CONFIGURED, time());
         }
         $this->response->success('Environment saved');
         $this->response->data(array('enabled' => $enabled));
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw new Exception(_("Failed to save GCE settings: {$e->getMessage()}"));
     }
     $this->db->CommitTrans();
 }
Example #22
0
 /**
  * Send a request to the UserInfo API to retrieve the user's information.
  *
  * @param String credentials OAuth 2.0 credentials to authorize the request.
  * @return Userinfo User's information.
  * @throws NoUserIdException An error occurred.
  */
 public function getUserInfo($credentials)
 {
     if ($this->_enabled) {
         $apiClient = new Google_Client();
         $apiClient->setUseObjects(true);
         $apiClient->setAccessToken($credentials);
         $userInfoService = new Google_Oauth2Service($apiClient);
         $userInfo = null;
         try {
             $userInfo = $userInfoService->userinfo->get();
         } catch (Google_Exception $e) {
             $this->setErrors($e->getMessage());
         }
         if ($userInfo != null && $userInfo->getId() != null) {
             return $userInfo;
         } else {
             throw new NoUserIdException();
         }
     } else {
         return false;
     }
 }
Example #23
0
 /**
  * Downloads backup file from Google Drive to root folder on local server.
  *
  * @param 	array 	$args	arguments passed to the function
  * [google_drive_token] -> user's Google drive token in json form
  * [google_drive_directory] -> folder on user's Google Drive account which backup file should be downloaded from
  * [google_drive_site_folder] -> subfolder with site name in google_drive_directory which backup file should be downloaded from
  * [backup_file] -> absolute path of backup file on local server
  * @return	bool|array		absolute path to downloaded file is successful, array with error message if not
  */
 function get_google_drive_backup($args)
 {
     extract($args);
     global $mmb_plugin_dir;
     require_once "{$mmb_plugin_dir}/lib/google-api-client/Google_Client.php";
     require_once "{$mmb_plugin_dir}/lib/google-api-client/contrib/Google_DriveService.php";
     try {
         $gdrive_client = new Google_Client();
         $gdrive_client->setUseObjects(true);
         $gdrive_client->setAccessToken($google_drive_token);
     } catch (Exception $e) {
         return array('error' => $e->getMessage());
     }
     $gdrive_service = new Google_DriveService($gdrive_client);
     try {
         $about = $gdrive_service->about->get();
         $root_folder_id = $about->getRootFolderId();
     } catch (Exception $e) {
         return array('error' => $e->getMessage());
     }
     try {
         $list_files = $gdrive_service->files->listFiles(array("q" => "title='{$google_drive_directory}' and '{$root_folder_id}' in parents and trashed = false"));
         $files = $list_files->getItems();
     } catch (Exception $e) {
         return array('error' => $e->getMessage());
     }
     if (isset($files[0])) {
         $managewp_folder = $files[0];
     } else {
         return array('error' => "This file does not exist.");
     }
     if ($google_drive_site_folder) {
         try {
             $subfolder_title = $this->site_name;
             $managewp_folder_id = $managewp_folder->getId();
             $list_files = $gdrive_service->files->listFiles(array("q" => "title='{$subfolder_title}' and '{$managewp_folder_id}' in parents and trashed = false"));
             $files = $list_files->getItems();
         } catch (Exception $e) {
             return array('error' => $e->getMessage());
         }
         if (isset($files[0])) {
             $backup_folder = $files[0];
         }
     } else {
         $backup_folder = $managewp_folder;
     }
     if (isset($backup_folder)) {
         try {
             $backup_folder_id = $backup_folder->getId();
             $list_files = $gdrive_service->files->listFiles(array("q" => "title='{$backup_file}' and '{$backup_folder_id}' in parents and trashed = false"));
             $files = $list_files->getItems();
         } catch (Exception $e) {
             return array('error' => $e->getMessage());
         }
         if (isset($files[0])) {
             try {
                 $download_url = $files[0]->getDownloadUrl();
                 if ($download_url) {
                     $request = new Google_HttpRequest($download_url, 'GET', null, null);
                     $http_request = Google_Client::$io->authenticatedRequest($request);
                     if ($http_request->getResponseHttpCode() == 200) {
                         $stream = $http_request->getResponseBody();
                         $local_destination = ABSPATH . 'mwp_temp_backup.zip';
                         $handle = @fopen($local_destination, 'w+');
                         $result = fwrite($handle, $stream);
                         fclose($handle);
                         if ($result) {
                             return $local_destination;
                         } else {
                             return array('error' => "Write permission error.");
                         }
                     } else {
                         return array('error' => "This file does not exist.");
                     }
                 } else {
                     return array('error' => "This file does not exist.");
                 }
             } catch (Exception $e) {
                 return array('error' => $e->getMessage());
             }
         } else {
             return array('error' => "This file does not exist.");
         }
     } else {
         return array('error' => "This file does not exist.");
     }
     return false;
 }
Example #24
0
$demoErrors = null;
$authUrl = THIS_PAGE . '?action=auth';
$revokeUrl = THIS_PAGE . '?action=revoke';
$helloAnalyticsDemoUrl = THIS_PAGE . '?demo=hello';
$mgmtApiDemoUrl = THIS_PAGE . '?demo=mgmt';
$coreReportingDemoUrl = THIS_PAGE . '?demo=reporting';
// Build a new client object to work with authorization.
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URL);
$client->setApplicationName(APP_NAME);
$client->setScopes(array(ANALYTICS_SCOPE));
// Magic. Returns objects from the Analytics Service
// instead of associative arrays.
$client->setUseObjects(true);
// Build a new storage object to handle and store tokens in sessions.
// Create a new storage object to persist the tokens across sessions.
$storage = new apiSessionStorage();
$authHelper = new AuthHelper($client, $storage, THIS_PAGE);
// Main controller logic.
if ($_GET['action'] == 'revoke') {
    $authHelper->revokeToken();
} else {
    if ($_GET['action'] == 'auth' || $_GET['code']) {
        $authHelper->authenticate();
    } else {
        $authHelper->setTokenFromStorage();
        if ($authHelper->isAuthorized()) {
            $analytics = new Google_AnalyticsService($client);
            if ($_GET['demo'] == 'hello') {
Example #25
0
 function setClientForConnect()
 {
     $client = new Google_Client();
     // Get your credentials from the APIs Console
     $client->setClientId(CLIENT_ID_SIGNUP);
     $client->setClientSecret(CLIENT_SECRET_SIGNUP);
     $client->setRedirectUri(REDIRECT_URI_SIGNUP);
     $client->setDeveloperKey(API_KEY);
     $client->setScopes(array('https://www.googleapis.com/auth/userinfo.profile'));
     $client->setUseObjects(true);
     return $client;
 }
Example #26
0
 /**
  * @param string $type Authentication type "service account" or "User authentication" (serviceAPI or webappAPI) defualt is 'serviceAPI'
  * @return \Google_Client Return the google client object
  * @throws CException Throws exception if type is invalid
  */
 private function createClient($type = null)
 {
     if (!isset($this->authenticationType)) {
         $this->authenticationType = $this->defaultAuthenticationType;
     }
     if (!is_null($type)) {
         if ($type == 'serviceAPI' || $type == 'webappAPI') {
             $this->authenticationType = $type;
         } else {
             throw new CException("Invalid choosen authentication type (" . $type . "). Must be 'serviceAPI' or 'webappAPI'.");
         }
     }
     Yii::import('JGoogleAPISrcAlias.Google_Client');
     $client = new Google_Client();
     $client->setApplicationName(Yii::app()->name);
     $client->setUseObjects($this->useObjects);
     switch ($this->authenticationType) {
         case 'serviceAPI':
             $scopes = array();
             if (isset($this->scopes['serviceAPI'])) {
                 foreach ($this->scopes['serviceAPI'] as $service) {
                     foreach ($service as $scope) {
                         $scopes[] = $scope;
                     }
                 }
             }
             $assertionCredentials = new Google_AssertionCredentials($this->serviceAPI['clientEmail'], $scopes, file_get_contents($this->serviceAPI['keyFilePath']), $this->serviceAPI['privateKeyPassword'], $this->serviceAPI['assertionType'], $this->serviceAPI['prn']);
             $client->setAssertionCredentials($assertionCredentials);
             $client->setClientId($this->serviceAPI['clientId']);
             $this->clientType = 'serviceAPI';
             break;
         case 'webappAPI':
             $scopes = array();
             if (isset($this->scopes['webappAPI'])) {
                 foreach ($this->scopes['webappAPI'] as $service) {
                     foreach ($service as $scope) {
                         $scopes[] = $scope;
                     }
                 }
             }
             $client->setClientId($this->webappAPI['clientId']);
             $client->setClientSecret($this->webappAPI['clientSecret']);
             $client->setRedirectUri($this->webappAPI['redirectUri']);
             $client->setDeveloperKey($this->simpleApiKey);
             $client->setScopes($scopes);
             $this->clientType = 'webappAPI';
             break;
         default:
             throw new CException("Invalid type given for the client authentication. Must be 'serviceAPI' or 'webappAPI'.");
             break;
     }
     return $client;
 }
 /**
  * Build a Drive service object.
  *
  * @param String credentials Json representation of the OAuth 2.0 credentials.
  * @return Google_DriveService service object.
  */
 function buildService($credentials)
 {
     $apiClient = new Google_Client();
     $apiClient->setUseObjects(true);
     $apiClient->setAccessToken($credentials);
     return new Google_DriveService($apiClient);
 }