Example #1
2
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var \Doctrine\ORM\EntityManager $em */
     $em = $this->getContainer()->get('doctrine.orm.default_entity_manager');
     $campaignRepo = $em->getRepository('VifeedCampaignBundle:Campaign');
     $campaigns = new ArrayCollection($campaignRepo->getActiveCampaigns());
     $hashes = [];
     foreach ($campaigns as $campaign) {
         /** @var Campaign $campaign */
         $hashes[] = $campaign->getHash();
     }
     $hashes = array_unique($hashes);
     $client = new \Google_Client();
     $client->setDeveloperKey($this->getContainer()->getParameter('google.api.key'));
     $youtube = new \Google_Service_YouTube($client);
     /* Опытным путём выяснилось, что ютуб принимает не больше 50 хешей за раз */
     $hash = 'TjvivnmWcn4';
     $request = $youtube->videos->listVideos('status', ['id' => $hash]);
     foreach ($request as $video) {
         /** @var \Google_Service_YouTube_Video $video */
         /** @var \Google_Service_YouTube_VideoStatistics $stats */
         $stats = $video->getStatistics();
         $hash = $video->getId();
         /* не исключается ситуация, что может быть несколько кампаний с одинаковым hash */
         $filteredCampaigns = $campaigns->filter(function (Campaign $campaign) use($hash) {
             return $campaign->getHash() == $hash;
         });
         foreach ($filteredCampaigns as $campaign) {
             $campaign->setSocialData('youtubeViewCount', $stats->getViewCount())->setSocialData('youtubeCommentCount', $stats->getCommentCount())->setSocialData('youtubeFavoriteCount', $stats->getFavoriteCount())->setSocialData('youtubeLikeCount', $stats->getLikeCount())->setSocialData('youtubeDislikeCount', $stats->getDislikeCount());
             $em->persist($campaign);
         }
     }
     $em->flush();
 }
 /**
  * @param string $name
  * @return \League\Flysystem\AdapterInterface
  * @throws \RuntimeException
  */
 public static function make($name)
 {
     $connections = Config::get('storage.connections');
     if (!isset($connections[$name])) {
         throw new \RuntimeException(sprintf('The storage connection %d does not exist.', $name));
     }
     $connection = $connections[$name];
     $connection['adapter'] = strtoupper($connection['adapter']);
     switch ($connection['adapter']) {
         case 'LOCAL':
             return new Local($connection['root_path'], $connection['public_url_base']);
         case 'RACKSPACE':
             $service = isset($connection['service']) ? Config::get($connection['service']) : Config::get('services.rackspace');
             $client = new Rackspace($service['api_endpoint'], array('username' => $service['username'], 'tenantName' => $service['tenant_name'], 'apiKey' => $service['api_key']));
             $store = $client->objectStoreService($connection['store'], $connection['region']);
             $container = $store->getContainer($connection['container']);
             return new RackspaceAdapter($container);
         case 'AWS':
             $service = isset($connection['service']) ? Config::get($connection['service']) : Config::get('services.aws');
             $client = S3Client::factory(array('credentials' => array('key' => $service['access_key'], 'secret' => $service['secret_key']), 'region' => $service['region'], 'version' => 'latest'));
             return new AwsS3Adapter($client, $connection['bucket']);
         case 'GCLOUD':
             $service = isset($connection['service']) ? Config::get($connection['service']) : Config::get('services.google_cloud');
             $credentials = new \Google_Auth_AssertionCredentials($service['service_account'], [\Google_Service_Storage::DEVSTORAGE_FULL_CONTROL], file_get_contents($service['key_file']), $service['secret']);
             $config = new \Google_Config();
             $config->setAuthClass(GoogleAuthOAuth2::class);
             $client = new \Google_Client($config);
             $client->setAssertionCredentials($credentials);
             $client->setDeveloperKey($service['developer_key']);
             $service = new \Google_Service_Storage($client);
             return new GoogleStorageAdapter($service, $connection['bucket']);
     }
     throw new \RuntimeException(sprintf('The storage adapter %s is invalid.', $connection['adapter']));
 }
Example #3
0
 /**
  * Create a new Google  instance.
  *
  * @param array $config
  *
  * @return void
  */
 public function __construct(array $config)
 {
     $this->config = $config;
     $this->client = new \Google_Client();
     $this->client->setApplicationName("Tag media Mrs");
     $this->client->setDeveloperKey($config['developer_key']);
 }
 function __construct($API_SERVER_TOKEN)
 {
     $this->apiClient = new \Google_Client();
     $this->apiClient->setApplicationName("EHF-YouTube-Playlist");
     $this->apiClient->setDeveloperKey($API_SERVER_TOKEN);
     $this->apiService = new \Google_Service_YouTube($this->apiClient);
 }
Example #5
0
 public function __construct(ContainerInterface $container, $api_key, $project_name)
 {
     $this->service_container = $container;
     $this->client = new \Google_Client();
     $this->client->setApplicationName($project_name);
     $this->client->setDeveloperKey($api_key);
     $this->searcher = new \Google_Service_Books($this->client);
 }
Example #6
0
 /**
  * @param \Google_Client $client
  */
 public function __construct(\Google_Client $client)
 {
     $this->client = $client;
     $this->client->setClientId(\Config::get('google.client_id'));
     $this->client->setClientSecret(\Config::get('google.client_secret'));
     $this->client->setDeveloperKey(\Config::get('google.api_key'));
     $this->client->setRedirectUri(\Config::get('app.url') . "/loginCallback");
     $this->client->setScopes(['https://www.googleapis.com/auth/youtube']);
     $this->client->setAccessType('offline');
 }
Example #7
0
 /**
  * Init all the youtube client service stuff.
  *
  * Instead of instantiating the service in the constructor, we delay
  * it until really neeed because it's really memory hungry (2MB). That
  * way the editor or any other artifact requiring repository instantiation
  * can do it in a cheap way. Sort of lazy loading the plugin.
  */
 private function init_youtube_service()
 {
     global $CFG;
     if (!isset($this->service)) {
         require_once $CFG->libdir . '/google/lib.php';
         $this->client = get_google_client();
         $this->client->setDeveloperKey($this->apikey);
         $this->client->setScopes(array(Google_Service_YouTube::YOUTUBE_READONLY));
         $this->service = new Google_Service_YouTube($this->client);
     }
 }
 /**
  * Init all the m27tube client service stuff.
  *
  * Instead of instantiating the service in the constructor, we delay
  * it until really neeed because it's really memory hungry (2MB). That
  * way the editor or any other artifact requiring repository instantiation
  * can do it in a cheap way. Sort of lazy loading the plugin.
  */
 private function init_m27tube_service()
 {
     global $CFG;
     if (!isset($this->service)) {
         require_once $CFG->dirroot . '/repository/m27tube/google/lib.php';
         require_once $CFG->dirroot . '/repository/m27tube/google/Google/Service/YouTube.php';
         $this->client = get_google_client();
         $this->client->setDeveloperKey($this->apikey);
         $this->client->setScopes(array(Google_Service_YouTube::YOUTUBE_READONLY));
         $this->service = new Google_Service_YouTube($this->client);
     }
 }
 public function initializeClient()
 {
     $this->client = new Client();
     $this->client->setAccessType('offline');
     $this->client->setApplicationName('playlister');
     $this->client->setClientId($this->config->get('services.youtube.client_id'));
     $this->client->setClientSecret($this->config->get('services.youtube.client_secret'));
     $this->client->setRedirectUri($this->config->get('services.youtube.redirect'));
     $this->client->setDeveloperKey($this->config->get('services.youtube.api_key'));
     $this->client->addScope('https://www.googleapis.com/auth/youtube.readonly');
     if ($this->auth->check() && $this->request->session()->has('user.token')) {
         $this->setToken($this->request->session()->get('user.token'));
     }
 }
Example #10
0
function newYoutubeService($key)
{
    $client = new Google_Client();
    $client->setDeveloperKey($key);
    $service = new Google_Service_YouTube($client);
    return $service;
}
 public function actionRefresh()
 {
     echo "hi";
     $DEVELOPER_KEY = 'AIzaSyCzTX4jeGnhS1Cvkz0KP-1rFf9EnYhrVJM';
     $client = new \Google_Client();
     $client->setDeveloperKey($DEVELOPER_KEY);
     $youtube = new \Google_Service_YouTube($client);
     try {
         $searchResponse = $youtube->search->listSearch('id,snippet', array('maxResults' => 5));
         $videoResults = array();
         foreach ($searchResponse['items'] as $searchResult) {
             array_push($videoResults, $searchResult['id']['videoId']);
         }
         $videoIds = join(',', $videoResults);
         $videosResponse = $youtube->videos->listVideos('snippet, statistics', array('id' => $videoIds));
         Yii::$app->db->createCommand('TRUNCATE videos')->execute();
         for ($i = 0; $i < sizeof($videosResponse); $i++) {
             $channelsResponse = $youtube->channels->listChannels('statistics', array('id' => $videosResponse[$i]['snippet']['channelId']));
             Yii::$app->db->createCommand()->insert('videos', ['id_video' => $videosResponse[$i]['id'], 'id_channel' => $videosResponse[$i]['snippet']['channelId'], 'video_title' => $videosResponse[$i]['snippet']['title'], 'channel_title' => $videosResponse[$i]['snippet']['channelTitle'], 'video_description' => $videosResponse[$i]['snippet']['description'], 'video_thumbnail' => $videosResponse[$i]['snippet']['thumbnails']['medium']['url'], 'views_count' => $videosResponse[$i]['statistics']['viewCount'], 'comments_count' => $videosResponse[$i]['statistics']['commentCount'], 'likes_count' => $videosResponse[$i]['statistics']['likeCount'], 'dislikes_count' => $videosResponse[$i]['statistics']['dislikeCount'], 'subscribers_count' => $channelsResponse[0]['statistics']['subscriberCount']])->execute();
         }
         return null;
     } catch (Google_Service_Exception $e) {
         echo sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
     } catch (Google_Exception $e) {
         echo sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
     }
 }
Example #12
0
 public function callback()
 {
     $client = new Google_Client();
     $client->setApplicationName($this->__app_name);
     $client->setClientId($this->__client_id);
     $client->setClientSecret($this->__client_secret);
     $client->setRedirectUri($this->__redirect_uri);
     $client->setDeveloperKey($this->__develop_key);
     $client->setScopes('https://www.googleapis.com/auth/calendar');
     $client->setAccessType('offline');
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
         $this->Session->delete('HTTP_REFERER');
         header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
     }
     // 呼び出し先
     if (isset($_SESSION['oauth_referer'])) {
         $url = $_SESSION['oauth_referer'];
         $this->Session->delete('oauth_referer');
     } else {
         $url = 'index';
     }
     $this->redirect('/');
 }
Example #13
0
 /**
  * Show the application dashboard.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
     $client = new \Google_Client();
     $client->setDeveloperKey(getenv('GOOGLE_API_KEY'));
     // Define an object that will be used to make all API requests.
     $youtube = new \Google_Service_YouTube($client);
     $videoIds = "";
     $videos = [];
     foreach (Auth::user()->channels as $channel) {
         // Call the search.list method to retrieve results matching the specified
         // query term.
         $searchResponse = $youtube->search->listSearch('id', array('channelId' => $channel->youtube_id));
         // Add each result to the appropriate list, and then display the lists of
         // matching videos, channels, and playlists.
         foreach ($searchResponse['items'] as $searchResult) {
             if ($searchResult['id']['kind'] == 'youtube#video') {
                 $videoIds .= $searchResult['id']['videoId'] . ",";
             }
         }
     }
     $searchResponse = $youtube->videos->listVideos('snippet,statistics', array('id' => $videoIds));
     foreach ($searchResponse['items'] as $searchResult) {
         $videos[] = new Video(['title' => $searchResult['snippet']['title'], 'videoId' => $searchResult['id'], 'channelId' => $searchResult['snippet']['channelId'], 'channelTitle' => $searchResult['snippet']['channelTitle'], 'description' => $searchResult['snippet']['description'], 'publishedAt' => $searchResult['snippet']['publishedAt'], 'thumbnail' => $searchResult['snippet']['modelData']['thumbnails']['default']['url'], 'thumbnailWidth' => $searchResult['snippet']['modelData']['thumbnails']['default']['width'], 'thumbnailHeight' => $searchResult['snippet']['modelData']['thumbnails']['default']['height'], 'viewCount' => $searchResult['statistics']['viewCount'], 'likeCount' => $searchResult['statistics']['likeCount'], 'dislikeCount' => $searchResult['statistics']['dislikeCount'], 'favoriteCount' => $searchResult['statistics']['favoriteCount'], 'commentCount' => $searchResult['statistics']['commentCount'], 'rawData' => $searchResult]);
     }
     //$videos = usort($videos, [Video::class, "cmp"]);
     return view('home', compact('videos'));
 }
 public function getYouTubeVideos($maxResults = 5)
 {
     $client = new Google_Client();
     $client->setDeveloperKey(self::$apiKey);
     $youtube = new Google_Service_YouTube($client);
     try {
         $searchResponse = $youtube->search->listSearch('id,snippet', array('type' => 'video', 'q' => urlencode($this->keyword), 'maxResults' => $maxResults, 'order' => 'viewCount'));
         $videos = array();
         $videoIds = array();
         foreach ($searchResponse['items'] as $result) {
             array_push($videoIds, $result['id']['videoId']);
             $videos[$result['id']['videoId']] = array('url' => $this->youtubeBaseURL . $result['id']['videoId'], 'thumbnail' => $result['snippet']['thumbnails']['high']['url']);
         }
         $videoResponse = $youtube->videos->listVideos('id,contentDetails,statistics', array('id' => join(',', $videoIds)));
         foreach ($videoResponse['items'] as $videoResult) {
             $duration = $this->getYouTubeDurations($videoResult['contentDetails']['duration']);
             $videos[$videoResult['id']]['duration'] = "{$duration[0]}:{$duration[1]}";
             $videos[$videoResult['id']]['views'] = $videoResult['statistics']['viewCount'];
         }
         return $videos;
     } catch (Google_Service_Exception $e) {
         die(sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())));
     } catch (Google_Exception $e) {
         die(sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())));
     }
     return null;
 }
Example #15
0
 public function googlecallback()
 {
     $ret = null;
     //$google_redirect_url = site_url('user/signup');
     $google_redirect_url = 'http://localhost/punu/punu/index.php/user/signup';
     $client = new Google_Client();
     $client->setClientId($this->google_client_id);
     $client->setClientSecret($this->google_client_secret);
     $client->setDeveloperKey($this->google_api_key);
     $client->setRedirectUri($google_redirect_url);
     $client->addScope($this->google_scope);
     // Send Client Request
     $objOAuthService = new Google_Service_Oauth2($client);
     // Add Access Token to Session
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['google_access_token'] = $client->getAccessToken();
         //header('Location: ' . filter_var($this->google_redirect_url, FILTER_SANITIZE_URL));
     }
     // Set Access Token to make Request
     if (isset($_SESSION['google_access_token']) && $_SESSION['google_access_token']) {
         $client->setAccessToken($_SESSION['google_access_token']);
     }
     // Get User Data from Google and store them in $data
     if ($client->getAccessToken()) {
         $userData = $objOAuthService->userinfo->get();
         //$_SESSION['userData'] = $userData;
         $_SESSION['google_access_token'] = $client->getAccessToken();
         $ret = $userData;
     }
     return $ret;
 }
Example #16
0
 /**
  * Find profiles matching search string 
  */
 public function actionSearch($searchString, $nextPageToken = null)
 {
     $creds = GooglePlusResources::getGooglePlusAPICredentials();
     if (!$creds) {
         throw new CException(Yii::t('app', 'Google+ integration isn\'t configured.'));
     }
     $client = new Google_Client();
     $client->setDeveloperKey($creds['apiKey']);
     $plus = new Google_Service_Plus($client);
     $params = array();
     if ($nextPageToken) {
         $params['pageToken'] = $nextPageToken;
     }
     $params['fields'] = 'nextPageToken,items(displayName,image/url,url,id)';
     try {
         $searchResults = $plus->people->search($searchString, $params);
     } catch (Google_Exception $e) {
         throw new CHttpException(500, Yii::t('app', 'Failed to retrieve Google+ profiles.'));
     }
     $profiles = array();
     foreach ($searchResults->items as $item) {
         $profiles[] = array('displayName' => $item->displayName, 'image' => $item->image ? $item->image->url : null, 'url' => $item->url, 'id' => $item->id);
     }
     echo CJSON::encode(array('profiles' => $profiles, 'nextPageToken' => $searchResults->nextPageToken));
 }
function update_with_api()
{
    error_log("Update triggered...");
    $client = new Google_Client();
    global $api_key;
    $client->setDeveloperKey($api_key);
    $youtube = new Google_Service_YouTube($client);
    global $greyChannelIDs, $bradyChannelIDs;
    $vids = array();
    foreach ($greyChannelIDs as $channelID) {
        $vids = array_merge($vids, getUploads($channelID, $youtube, 1));
    }
    foreach ($bradyChannelIDs as $channelID) {
        $vids = array_merge($vids, getUploads($channelID, $youtube, 20));
    }
    foreach ($vids as $vid) {
        // If this video is already in the database, delete it (we need the updated view count)
        addVideoReplacing($vid);
    }
    // Delete unnecessary videos from both creators.
    deleteExtraneousVids();
    // Record the time
    recordUpdate();
    // Clear the cache (so this update will apply)
    refresh();
    error_log("Updated successfully!");
}
Example #18
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']);
 }
 /**
  * @throws MissingConfigurationException
  * @return \Google_Client
  */
 public function create()
 {
     $client = new \Google_Client();
     $requiredAuthenticationSettings = array('applicationName', 'clientId', 'clientSecret', 'developerKey');
     foreach ($requiredAuthenticationSettings as $key) {
         if (!isset($this->authenticationSettings[$key])) {
             throw new MissingConfigurationException(sprintf('Missing setting "TYPO3.Neos.GoogleAnalytics.authentication.%s"', $key), 1415796352);
         }
     }
     $client->setApplicationName($this->authenticationSettings['applicationName']);
     $client->setClientId($this->authenticationSettings['clientId']);
     $client->setClientSecret($this->authenticationSettings['clientSecret']);
     $client->setDeveloperKey($this->authenticationSettings['developerKey']);
     $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
     $client->setAccessType('offline');
     $accessToken = $this->tokenStorage->getAccessToken();
     if ($accessToken !== NULL) {
         $client->setAccessToken($accessToken);
         if ($client->isAccessTokenExpired()) {
             $refreshToken = $this->tokenStorage->getRefreshToken();
             $client->refreshToken($refreshToken);
         }
     }
     return $client;
 }
 private function createClient()
 {
     $options = ['auth' => 'google_auth', 'exceptions' => false];
     if ($proxy = getenv('HTTP_PROXY')) {
         $options['proxy'] = $proxy;
         $options['verify'] = false;
     }
     // adjust constructor depending on guzzle version
     if (!$this->isGuzzle6()) {
         $options = ['defaults' => $options];
     }
     $httpClient = new GuzzleHttp\Client($options);
     $client = new Google_Client();
     $client->setApplicationName('google-api-php-client-tests');
     $client->setHttpClient($httpClient);
     $client->setScopes(["https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/drive"]);
     if ($this->key) {
         $client->setDeveloperKey($this->key);
     }
     list($clientId, $clientSecret) = $this->getClientIdAndSecret();
     $client->setClientId($clientId);
     $client->setClientSecret($clientSecret);
     $client->setCache($this->getCache());
     return $client;
 }
Example #21
0
 function __construct()
 {
     $google = new Google_Client();
     $google->setApplicationName('Videopedia');
     $google->setDeveloperKey('AIzaSyDxXx4r5Q6ckKjbvhsH3Kn3v7q1cGpdtF8');
     $youtube = new Google_Service_YouTube($google);
     $this->youtube = $youtube;
 }
Example #22
0
 private function get_youtube_list($app_id = 0, $search_key = '', $type = 'video')
 {
     $DEVELOPER_KEY = 'AIzaSyC89E2UzLeeyFJ_i2cByYi-UEaOCe7wftQ';
     $client = new Google_Client();
     $client->setDeveloperKey($DEVELOPER_KEY);
     $youtube = new Google_Service_YouTube($client);
     $this->getDataYoutube($youtube, $app_id, $search_key, $type);
 }
 public function __construct(\Google_Client $googleClient, GoogleBooksAuthorTransformer $transformer, ResultsCleaner $resultsCleaner)
 {
     $googleClient->setApplicationName("BookFeed");
     $googleClient->setDeveloperKey(env('GOOGLE_BOOKS_API_KEY'));
     $this->googleBooksService = new \Google_Service_Books($googleClient);
     $this->googleBooksAuthorTransformer = $transformer;
     $this->resultsCleaner = $resultsCleaner;
 }
Example #24
0
 private function __construct()
 {
     $client = new \Google_Client();
     $client->setApplicationName("Relive");
     $client->setDeveloperKey(getenv("GPLUS_API_KEY"));
     $this->gplus = new \Google_Service_Plus($client);
     $this->provider = \relive\models\Provider::firstOrCreate(['providerName' => 'googleplus', 'providerSite' => 'https://plus.google.com/']);
 }
 public function beforeFilter()
 {
     parent::beforeFilter();
     $DEVELOPER_KEY = 'AIzaSyDOkg-u9jnhP-WnzX5WPJyV1sc5QQrtuyc';
     $client = new Google_Client();
     $client->setDeveloperKey($DEVELOPER_KEY);
     $this->youtube = new Google_YoutubeService($client);
 }
Example #26
0
 public function __construct($config)
 {
     parent::__construct($config);
     $this->Http = new HttpSocket();
     $client = new Google_Client();
     $client->setDeveloperKey($this->config['apiKey']);
     $this->Youtube = new Google_YoutubeService($client);
 }
Example #27
0
function test()
{
    $client = new Google_Client();
    $client->setApplicationName("Amadeus");
    $client->setDeveloperKey(YOUTUBE_API_KEY);
    $youtube = new Google_Service_YouTube($client);
    $searchResponse = $youtube->search->listSearch('id,snippet', array('q' => 'test', 'maxResults' => 25, 'type' => 'video', 'order' => 'relevance', 'videoEmbeddable' => 'true'));
    print_r($searchResponse);
}
Example #28
0
 public function index()
 {
     $this->load->helper('url');
     //For load css from config file
     $ci =& get_instance();
     $header_js = $ci->config->item('css');
     // Include two files from google-php-client library in controller
     require_once APPPATH . "libraries/google-api-php-client-master/src/Google/autoload.php";
     require_once APPPATH . "libraries/google-api-php-client-master/src/Google/Client.php";
     require_once APPPATH . "libraries/google-api-php-client-master/src/Google/Service/Oauth2.php";
     // Store values in variables from project created in Google Developer Console
     $client_id = '180391628117-hf4di0a3l0aaq10c6h933n97p4e1lb2m.apps.googleusercontent.com';
     $client_secret = 'Eg_i_sihLL5E5FMGTnyKSVXK';
     $redirect_uri = 'http://citest.local.com/index.php/login';
     $simple_api_key = 'AIzaSyCSS5nGOzy7OcuSvSMwblVRRPZ9_TFIDnM';
     // Create Client Request to access Google API
     $client = new Google_Client();
     $client->setApplicationName("PHP Google OAuth Login Example");
     $client->setClientId($client_id);
     $client->setClientSecret($client_secret);
     $client->setRedirectUri($redirect_uri);
     $client->setDeveloperKey($simple_api_key);
     $client->addScope("https://www.googleapis.com/auth/userinfo.email");
     // Send Client Request
     $objOAuthService = new Google_Service_Oauth2($client);
     // Add Access Token to Session
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['access_token'] = $client->getAccessToken();
         header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
     }
     // Set Access Token to make Request
     if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
         $client->setAccessToken($_SESSION['access_token']);
     }
     // Get User Data from Google and store them in $data
     if ($client->getAccessToken()) {
         $userData = $objOAuthService->userinfo->get();
         //Save google login user data in database
         $saveData = array('name' => $userData['name'], 'email' => $userData['email'], 'gender' => $userData['gender']);
         $this->user_model->saveUserData($saveData);
         $data['userData'] = $userData;
         $_SESSION['access_token'] = $client->getAccessToken();
     } else {
         $authUrl = $client->createAuthUrl();
         $data['authUrl'] = $authUrl;
     }
     //Load css file added in config file
     $str = '';
     foreach ($header_js as $key => $val) {
         $str .= '<link rel="stylesheet" href="' . base_url() . 'css/' . $val . '" type="text/css" />' . "\n";
     }
     $data['css'] = $str;
     // Load view and send values stored in $data
     $this->load->view('google_authentication', $data);
 }
Example #29
0
 public function testClient()
 {
     $client = new Google_Client();
     $client->setAccessType('foo');
     $this->assertEquals('foo', $client->getAuth()->accessType);
     $client->setDeveloperKey('foo');
     $this->assertEquals('foo', $client->getAuth()->developerKey);
     $client->setAccessToken(json_encode(array('access_token' => '1')));
     $this->assertEquals("{\"access_token\":\"1\"}", $client->getAccessToken());
 }
Example #30
0
 public function getRecomendationData($likes)
 {
     require_once 'Google/Client.php';
     require_once 'Google/Service/YouTube.php';
     $DEVELOPER_KEY = 'REPLACE_ME';
     $client = new Google_Client();
     $client->setDeveloperKey($DEVELOPER_KEY);
     $youtube = new Google_Service_YouTube($client);
     $searchResponse = $youtube->search->listSearch('id,snippet', array('q' => $_GET['q'], 'maxResults' => $_GET['maxResults']));
 }