public function actionToken() { //$this->checkAccess("token"); $client = new \Google_Client(); $client->setClientId(Yii::$app->params['OAUTH2_CLIENT_ID']); $client->setClientSecret(Yii::$app->params['OAUTH2_CLIENT_SECRET']); $client->setScopes('https://www.googleapis.com/auth/youtube'); //$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $client->setRedirectUri(Yii::$app->params['redirectVideo']); if (Yii::$app->request->get('code')) { if (strval(Yii::$app->session->get('state')) !== strval(Yii::$app->request->get('state'))) { die('The session state did not match.'); } $client->authenticate(Yii::$app->request->get('code')); if ($client->getAccessToken()) { $token = $this->getToken(); $token->load(json_decode($client->getAccessToken(), true), ""); $token->save(); return ["token_saved" => $token]; } return ["token_not_saved_code" => Yii::$app->request->get('code')]; } if (!$client->getAccessToken()) { // If the user hasn't authorized the app, initiate the OAuth flow //$state = mt_rand(); $client->setState(Yii::$app->params['stateVideo']); $client->setAccessType("offline"); $client->setApprovalPrompt("force"); Yii::$app->session->set('state', Yii::$app->params['stateVideo']); $authUrl = $client->createAuthUrl(); return ["link" => $authUrl]; } }
public function testSettersGetters() { $client = new Google_Client(); $client->setClientId("client1"); $client->setClientSecret('client1secret'); $client->setState('1'); $client->setApprovalPrompt('force'); $client->setAccessType('offline'); $client->setRedirectUri('localhost'); $client->setApplicationName('me'); $this->assertEquals('object', gettype($client->getAuth())); $this->assertEquals('object', gettype($client->getCache())); $this->assertEquals('object', gettype($client->getIo())); $client->setAuth(new Google_Auth_Simple($client)); $client->setAuth(new Google_Auth_OAuth2($client)); try { $client->setAccessToken(null); die('Should have thrown an Google_Auth_Exception.'); } catch (Google_Auth_Exception $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()); }
$uploadStatus = $media->nextChunk($insertResponse, $chunk); } fclose($handle); $htmlBody .= "<h3>Video Uploaded</h3><ul>"; $htmlBody .= sprintf('<li>%s (%s)</li>', $uploadStatus['snippet']['title'], $uploadStatus['id']); $htmlBody .= '</ul>'; } catch (Google_ServiceException $e) { $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } $_SESSION['token'] = $client->getAccessToken(); } else { // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $htmlBody = <<<END <h3>Authorization Required</h3> <p>You need to <a href="{$authUrl}">authorize access</a> before proceeding.<p> END; } ?> <!doctype html> <html> <head> <title>Video Uploaded</title> </head> <body>
/** * This method is used to process the first part of authentication workflow, before redirect * * @return array Array with status and redirect URI */ public function getRedirectUri() { $ngConnectINI = eZINI::instance('ngconnect.ini'); $http = eZHTTPTool::instance(); $clientID = trim($ngConnectINI->variable('LoginMethod_google', 'GoogleClientID')); if (empty($clientID)) { return array('status' => 'error', 'message' => 'Google client ID undefined.'); } $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'); $state = md5(session_id() . (string) time()); $http->setSessionVariable('NGConnectOAuthState', $state); $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->setRedirectUri($callbackUri); $client->setState($state); return array('status' => 'success', 'redirect_uri' => $client->createAuthUrl()); }
function getClient() { $config = (include __DIR__ . '/ini.php'); $client = new Google_Client(); $client->setApplicationName("Webkameleon"); $client->setClientId($config['oauth2_client_id']); $client->setClientSecret($config['oauth2_client_secret']); $client->setRedirectUri($config['oauth2_redirect_uri']); $client->setScopes($config['oauth2_scopes']); $client->setState('offline'); $client->setAccessType('offline'); $client->setApprovalPrompt('force'); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); die($client->getAccessToken()); } elseif (!isset($config['token'])) { Header('Location: ' . $client->createAuthUrl()); } else { $client->setAccessToken($config['token']); if ($client->isAccessTokenExpired()) { $token = json_decode($config['token'], true); $client->refreshToken($token['refresh_token']); } } return $client; }
/** * Returns a URL the user can visit to grant us permission to access their feed * * @return string */ public function getAuthURL() { $state = mt_rand(); $this->client->setState($state); Session::set($this->stateSessionIdentifier, $state); return $this->client->createAuthUrl(); }
/** * @param $staff_id * @return string */ public function createAuthUrl($staff_id) { $this->client->setRedirectUri($this->generateRedirectURI()); $this->client->addScope('https://www.googleapis.com/auth/calendar'); $this->client->setState(strtr(base64_encode($staff_id), '+/=', '-_,')); $this->client->setApprovalPrompt('force'); $this->client->setAccessType('offline'); return $this->client->createAuthUrl(); }
/** * Render method * @return var $output */ public function render() { session_start(); $OAUTH2_CLIENT_ID = $this->arguments['clientid']; $OAUTH2_CLIENT_SECRET = $this->arguments['clientsecret']; $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); $youtube = new Google_YoutubeService($client); if (isset($_GET['code'])) { if (strval($_SESSION['state']) !== strval($_GET['state'])) { die('The session state did not match.'); } $client->authenticate(); $_SESSION['token'] = $client->getAccessToken(); header('Location: ' . $redirect); } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } if ($client->getAccessToken()) { try { $channelsResponse = $youtube->channels->listChannels('contentDetails', array('mine' => 'true')); $output = ''; foreach ($channelsResponse['items'] as $channel) { $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads']; $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array('playlistId' => $uploadsListId, 'maxResults' => 50)); $output .= "<h3>Videos in list {$uploadsListId}</h3><ul>"; foreach ($playlistItemsResponse['items'] as $playlistItem) { $output .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'], $playlistItem['snippet']['resourceId']['videoId']); } $output .= '</ul>'; } } catch (Google_ServiceException $e) { $output .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $output .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } $_SESSION['token'] = $client->getAccessToken(); } else { $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $output = '<h3>Authorization Required</h3><p>You need to <a href="' . $authUrl . '">authorize access</a> before proceeding.<p>'; } return $output; }
/** * Lets first get an authorization URL to our client, it will forward the client to Google's Concent window * @param String $emailAddress * @param String $state * @return String URL to Google Concent screen */ function getAuthorizationUrl($emailAddress, $state) { global $CLIENT_ID, $REDIRECT_URI, $SCOPES; $client = new Google_Client(); $client->setClientId($CLIENT_ID); $client->setRedirectUri($REDIRECT_URI); $client->setAccessType('offline'); $client->setApprovalPrompt('auto'); $client->setState($state); $client->setScopes($SCOPES); $tmpUrl = parse_url($client->createAuthUrl()); $query = explode('&', $tmpUrl['query']); $query[] = 'user_id=' . urlencode($emailAddress); return $tmpUrl['scheme'] . '://' . $tmpUrl['host'] . $tmpUrl['path'] . '?' . implode('&', $query); }
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; }
public function index() { ini_set("display_errors", 1); $youtubeClientIdAry = $this->M_Configuration->getConfigurationDetails('youtube_clientId'); $youtubeClientSecretAry = $this->M_Configuration->getConfigurationDetails('youtube_clientSecret'); $OAUTH2_CLIENT_ID = $youtubeClientIdAry->configuration_data; $OAUTH2_CLIENT_SECRET = $youtubeClientSecretAry->configuration_data; if (isset($_GET['code'])) { $url = 'https://accounts.google.com/o/oauth2/token'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); $code = $_GET['code']; curl_setopt($ch, CURLOPT_POSTFIELDS, 'code=' . $code . '&' . 'client_id=' . $OAUTH2_CLIENT_ID . '&' . 'client_secret=' . $OAUTH2_CLIENT_SECRET . '&' . 'redirect_uri=' . urlencode('http://mystory.buzz/admin/getRefreshToken') . '&' . 'grant_type=' . 'authorization_code'); $output = curl_exec($ch); curl_close($ch); echo $output; $obj = json_decode($output); $token = $obj->{'refresh_token'}; $insertVal = array('youtube_refreshToken' => $token); $result = $this->M_Configuration->saveDetails($insertVal); exit; } $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); //$client->setClientSecret($OAUTH2_CLIENT_SECRET); //$client->refreshToken('1/ZniNI97r2y14HXQzW15JC-3VeaMCjVFXIbOCFRjVPEUMEudVrK5jSpoR30zcRFq6'); $client->setScopes('https://gdata.youtube.com'); $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $redirect = filter_var('http://mystory.buzz/admin/getRefreshToken', FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $data['authUrl'] = $authUrl; $this->load->view('configuration/v_refreshToken', $data); }
private function initialize_oauth() { $redirecturi = new moodle_url(self::REDIRECTURL); $returnurl = new moodle_url('/portfolio/add.php'); $returnurl->param('postcontrol', 1); $returnurl->param('id', $this->exporter->get('id')); $returnurl->param('sesskey', sesskey()); $clientid = $this->get_config('clientid'); $secret = $this->get_config('secret'); // Setup Google client. $this->client = get_google_client(); $this->client->setClientId($clientid); $this->client->setClientSecret($secret); $this->client->setScopes(array(Google_Service_Drive::DRIVE_FILE)); $this->client->setRedirectUri($redirecturi->out(false)); // URL to be called when redirecting from authentication. $this->client->setState($returnurl->out_as_local_url(false)); // Setup drive upload service. $this->service = new Google_Service_Drive($this->client); }
public function authAction() { $url = Mage::getUrl("adminhtml/googleShoppingApi_oauth/auth"); // /index.php/admin/googleShoppingApi_oauth/auth/ $storeId = $this->getRequest()->getParam('store_id'); $state = $this->getRequest()->getParam('state'); if ($state) { $params = json_decode(base64_decode(urldecode($state))); $storeId = $params->store_id; } else { $state = urlencode(base64_encode(json_encode(array('store_id' => $storeId)))); } $clientId = $this->getConfig()->getConfigData('client_id', $storeId); $clientSecret = $this->getConfig()->getConfigData('client_secret', $storeId); $adminSession = Mage::getSingleton('admin/session'); $service = Mage::getModel('googleshoppingapi/googleShopping'); $client = new Google_Client(); $client->setApplicationName(Weboffice_GoogleShoppingApi_Model_GoogleShopping::APPNAME); $client->setClientId($clientId); $client->setClientSecret($clientSecret); $client->setRedirectUri($url); $client->setScopes('https://www.googleapis.com/auth/content'); $client->setState($state); $accessTokens = $adminSession->getGoogleOAuth2Token(); if (!is_array($accessTokens)) { $accessTokens = array(); } $code = $this->getRequest()->getParam('code'); if ($code) { $accessToken = $client->authenticate($code); $accessTokens[$storeId] = $accessToken; $adminSession->setGoogleOAuth2Token($accessTokens); // unlock flag after successfull authentication $flag = $this->_getFlag(); $flag->unlock(); $this->_redirect('*/googleShoppingApi_items/index', array('store' => $storeId)); return $this; } header('Location: ' . $client->createAuthUrl()); exit; }
function calendar_sinchronization() { $user = ExternalCalendarUsers::findByContactId(); $user_data = array(); $client = new Google_Client(); // Step 2: The user accepted your access now you need to exchange it. $google_code = array_var($_GET, 'google_code', false); if ($google_code) { try { $credentials = $client->authenticate(urldecode(array_var($_GET, 'google_code'))); $google_acces_token = $client->getAccessToken(); $service = new Google_Service_Oauth2($client); $user_info = $service->userinfo->get(); $user_email = ExternalCalendarUsers::findByEmail($user_info['email']); if (!$user_email) { $user_email = new ExternalCalendarUser(); $user_email->setAuthUser($user_info['email']); $user_email->setAuthPass($credentials); $user_email->setContactId(logged_user()->getId()); $user_email->setType("google"); $user_email->save(); $this->update_sync_cron_events(); } else { $user_email->setAuthPass($credentials); $user_email->save(); } } catch (Exception $e) { Logger::log("ERROR Google Sync Step 2"); Logger::log($e->getMessage()); } } $service_is_working = true; if ($user) { //calendars actions $calendars_actions = array(); //1 = start sync $calendars_actions[1] = array(); $calendars_actions[1]['text'] = lang('start sync'); $calendars_actions[1]['function'] = 'og.google_calendar_start_sync_calendar'; //2 = stop sync $calendars_actions[2] = array(); $calendars_actions[2]['text'] = lang('stop sync'); $calendars_actions[2]['function'] = 'og.google_calendar_stop_sync_calendar'; //3 = restart sync $calendars_actions[3] = array(); $calendars_actions[3]['text'] = lang('restart sync'); $calendars_actions[3]['function'] = 'og.google_calendar_start_sync_calendar'; //4 = delete calendar $calendars_actions[4] = array(); $calendars_actions[4]['text'] = lang('delete calendar'); $calendars_actions[4]['function'] = 'og.google_calendar_delete_calendar'; //5 = delete calendar $calendars_actions[5] = array(); $calendars_actions[5]['text'] = lang('classify'); $calendars_actions[5]['function'] = 'og.google_calendar_classify'; tpl_assign('calendars_actions', $calendars_actions); //calendars status //1 = never sync //2 = in sync //3 = not in sync //4 = deleted from google $calendars_status = array(); //1 = never sync $calendars_status[1] = array(); $calendars_status[1]['text'] = lang('never sync'); $calendars_status[1]['actions'] = array(1); //2 = in sync $calendars_status[2] = array(); $calendars_status[2]['text'] = lang('in sync'); $calendars_status[2]['actions'] = array(2, 4, 5); //3 = not in sync $calendars_status[3] = array(); $calendars_status[3]['text'] = lang('not in sync'); $calendars_status[3]['actions'] = array(3, 4); //4 = deleted from google $calendars_status[4] = array(); $calendars_status[4]['text'] = lang('deleted from google'); $calendars_status[4]['actions'] = array(4); //5 = delete calendar $calendars_actions[5] = array(); $calendars_actions[5]['text'] = lang('classify'); $calendars_actions[5]['function'] = 'og.google_calendar_classify'; tpl_assign('calendars_status', $calendars_status); $user_data['id'] = $user->getId(); $user_data['auth_user'] = $user->getAuthUser(); $user_data['sync'] = $user->getSync(); tpl_assign('user', $user_data); // Step 3: We have access we can now create our service try { $service = $this->connect_with_google_calendar($user); $calendarList = $service->calendarList->listCalendarList(); $instalation = explode("/", ROOT_URL); $instalation_name = end($instalation); $feng_calendar_name = lang('feng calendar', $instalation_name); while (true) { foreach ($calendarList->getItems() as $calendarListEntry) { //is feng calendar if ($calendarListEntry->getSummary() == $feng_calendar_name) { continue; } $external_calendars[$calendarListEntry->getId()] = array('original_calendar_id' => $calendarListEntry->getId(), 'title' => $calendarListEntry->getSummary(), 'calendar_status' => 1); } $pageToken = $calendarList->getNextPageToken(); if ($pageToken) { $optParams = array('pageToken' => $pageToken); $calendarList = $service->calendarList->listCalendarList($optParams); } else { break; } } } catch (Exception $e) { $service_is_working = false; } //Calendars status $view_calendars = array(); $calendars = ExternalCalendars::findByExtCalUserId($user->getId(), true); foreach ($calendars as $ext_calendar) { $view_calendar = array(); $view_calendar['original_calendar_id'] = $ext_calendar->getOriginalCalendarId(); $view_calendar['title'] = $ext_calendar->getCalendarName(); $members = array(); $member_ids = explode(",", $ext_calendar->getRelatedTo()); foreach ($member_ids as $member_id) { $members[$member_id] = $member_id; } if (count($members)) { $view_calendar['members'] = json_encode(array(1 => $members)); } $view_calendar['calendar_id'] = $ext_calendar->getId(); //deleted on google $view_calendar['calendar_status'] = 4; if (array_key_exists($ext_calendar->getOriginalCalendarId(), $external_calendars)) { //not in sync $view_calendar['calendar_status'] = 3; if ($ext_calendar->getSync()) { //in sync $view_calendar['calendar_status'] = 2; } unset($external_calendars[$ext_calendar->getOriginalCalendarId()]); } $view_calendars[$ext_calendar->getOriginalCalendarId()] = $view_calendar; } $all_calendars = array_merge($external_calendars, $view_calendars); ksort($all_calendars); tpl_assign('external_calendars', $all_calendars); $sync_from_feng = false; if ($user->getSync() == 1) { $calendar_feng = ExternalCalendars::findFengCalendarByExtCalUserIdValue($user->getId()); if ($calendar_feng instanceof ExternalCalendar && $calendar_feng->getSync() == 0) { $sync_from_feng = false; } else { $sync_from_feng = true; } } if ($sync_from_feng) { $sync_from_feng_action = "og.google_calendar_stop_sync_feng_calendar"; $sync_from_feng_color = "2"; $sync_from_feng_text = lang('stop sync'); } else { $sync_from_feng_action = "og.google_calendar_start_sync_feng_calendar"; $sync_from_feng_color = "3"; $sync_from_feng_text = lang('start sync'); } tpl_assign('sync_from_feng_action', $sync_from_feng_action); tpl_assign('sync_from_feng_color', $sync_from_feng_color); tpl_assign('sync_from_feng_text', $sync_from_feng_text); } if (!$user || !$service_is_working) { // Step 1: The user has not authenticated we give them a link to login if (!$google_code) { $client->setScopes(array('https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile')); $client->setState(ROOT_URL . '/index.php?c=external_calendar&a=calendar_sinchronization'); $authUrl = $client->createAuthUrl(); tpl_assign('auth_url', $authUrl); } } }
public function testSettersGetters() { $client = new Google_Client(); $client->setClientId("client1"); $client->setClientSecret('client1secret'); $client->setState('1'); $client->setApprovalPrompt('force'); $client->setAccessType('offline'); $client->setRedirectUri('localhost'); $client->setConfig('application_name', 'me'); $client->setCache($this->getMock('Psr\\Cache\\CacheItemPoolInterface')); $this->assertEquals('object', gettype($client->getCache())); try { $client->setAccessToken(null); $this->fail('Should have thrown an Exception.'); } catch (InvalidArgumentException $e) { $this->assertEquals('invalid json token', $e->getMessage()); } $token = array('access_token' => 'token'); $client->setAccessToken($token); $this->assertEquals($token, $client->getAccessToken()); }
/** * Upload the video files to youtube * No matter success or fail, the result will be logged in logStatus() * @param String $videoPath Local video path (./1.mp4) * @param String $videoTitle Video Title * @param String $videoDescription Video Description, allow \n characters and links * @param int $videoCategory Video Category ID, Please refer to the list - https://gist.github.com/dgp/1b24bf2961521bd75d6c * @param String[] $videoTags Keyword Tags array */ function uploadYoutube($videoPath, $videoTitle, $videoDescription, $videoCategory, $videoTags) { $OAUTH2_CLIENT_ID = 'XXX.apps.googleusercontent.com'; //TODO: UPDATE YOUR CLIENT ID $OAUTH2_CLIENT_SECRET = 'XXX'; //TODO:UPDATE YOUR CLIENT SECRET $RESULT = array('refreshToken' => 'XXXXXXXXXXXXX'); //TODO:UPDATE YOUR PROPOSED ACCOUNT REFRESH ID $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('http://localhost/authorize/'); $client->setRedirectUri($redirect); $youtube = new Google_Service_YouTube($client); $client->refreshToken($RESULT['refreshToken']); $RESULT['accessToken'] = $client->getAccessToken()['access_token']; $client->authenticate($RESULT['accessToken']); if ($client->getAccessToken()) { try { logStatus('Video Start Upload - ' . $videoTitle); $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($videoTitle); $snippet->setDescription($videoDescription); $snippet->setTags(${$videoTags}); $snippet->setCategoryId($videoCategory); $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = "private"; //TODO: UPDATE YOUR UPLOAD VIDEO STATUS , (private/public) $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); $chunkSizeBytes = 1 * 1024 * 1024; $client->setDefer(true); $insertRequest = $youtube->videos->insert("status,snippet", $video); $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes); $media->setFileSize(filesize($videoPath)); $status = false; $handle = fopen($videoPath, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } fclose($handle); $client->setDefer(false); logStatus('Video Uploaded -' . $status['snippet']['title'] . ' ' . $status['id']); saveYoutubePath($status['id']); } catch (Google_Service_Exception $e) { logStatus($e->getMessage()); exit; } catch (Google_Exception $e) { logStatus($e->getMessage()); exit; } } else { $state = mt_rand(); $client->setState($state); $authUrl = $client->createAuthUrl(); logStatus($authUrl); exit; } }
/** * Get the authentication URL for the googleclient * * @param string $state * @return string */ public function getAuthenticationUrl($state) { $this->googleApiClient->setState($state); return $this->googleApiClient->createAuthUrl(); }
/** * displayEditGoogle * * @return void */ function displayEditGoogle() { $this->displayHeader(); $config = getGoogleConfigData(); $user = getGoogleUserData($this->fcmsUser->id); // Setup url for callbacks $callbackUrl = getDomainAndDir(); $callbackUrl .= 'settings.php?view=google&oauth2callback'; $_SESSION['callback_url'] = $callbackUrl; if (!empty($config['google_client_id']) || !empty($config['google_client_secret'])) { $googleClient = new Google_Client(); $googleClient->setClientId($config['google_client_id']); $googleClient->setClientSecret($config['google_client_secret']); $googleClient->setAccessType('offline'); $googleClient->setScopes(array('https://www.googleapis.com/auth/youtube.force-ssl', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://picasaweb.google.com/data/')); $googleClient->setRedirectUri($callbackUrl); // We still have a token saved if (isset($_SESSION['googleSessionToken'])) { try { $googleClient->setAccessToken($_SESSION['googleSessionToken']); // Make sure our access token is still good if ($googleClient->isAccessTokenExpired()) { $googleClient->refreshToken($user['google_session_token']); } } catch (Exception $e) { $failure = 1; } } elseif (!empty($user['google_session_token'])) { try { $googleClient->refreshToken($user['google_session_token']); $_SESSION['googleSessionToken'] = $googleClient->getAccessToken(); } catch (Exception $e) { $failure = 1; } } if (!isset($failure) && isset($_SESSION['googleSessionToken'])) { try { $youtube = new Google_Service_YouTube($googleClient); $channel = $youtube->channels->listChannels('id', array('mine' => 'true')); } catch (Exception $e) { echo '<div class="error-alert">ERROR: ' . $e->getMessage() . '</div>'; $this->displayFooter(); return; } $oAuth = new Google_Service_Oauth2($googleClient); $userInfo = $oAuth->userinfo->get(); $user = '******' . $channel->items[0]['id'] . '">' . $userInfo->email . '</a>'; $status = sprintf(T_('Currently connected as: %s'), $user); $link = '<a class="disconnect" href="?revoke=google">' . T_('Disconnect') . '</a>'; } else { $state = mt_rand(); $googleClient->setState($state); $_SESSION['state'] = $state; $url = $googleClient->createAuthUrl(); $status = T_('Not Connected'); $link = '<a href="' . $url . '">' . T_('Connect') . '</a>'; } } echo ' <div class="social-media-connect"> <img class="icon" src="ui/img/google.png" alt="Google"/> <h2>Google</h2> <p>' . T_('Connecting with Google will allow you to:') . '</p> <ul> <li>' . T_('Share your Picasa photos with this site.') . '</li> <li>' . T_('Share your YouTube videos with this site.') . '</li> </ul> <div class="status">' . $status . '</div> <div class="action">' . $link . '</div> </div>'; $this->displayFooter(); }
public function connect_google($in_upload_state = "") { set_include_path(get_include_path() . PATH_SEPARATOR . BASEPATH . '../assets/google_api/src'); require_once 'Google/Client.php'; require_once 'Google/Service/YouTube.php'; $this->load->library('session'); $client = new Google_Client(); $client->setApplicationName("Zeepro youtube upload"); $client->setClientId("652807238221-vrc4no9o0t9mdb48ltc69v215henenm4.apps.googleusercontent.com"); $client->setClientSecret("PPww8vp8cOVcqeHioL7HbCFx"); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('https://sso.zeepro.com/redirect.ashx', FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); $client->setAccessType('offline'); $youtube = new Google_Service_YouTube($client); if (isset($_GET['code'])) { if (strval($this->session->userdata('state')) !== strval($_GET['state'])) { var_dump($this->session->all_userdata()); die('The session state did not match.'); } $client->authenticate($_GET['code']); $this->session->set_userdata('token', $client->getAccessToken()); $this->session->set_userdata('code', $_GET['code']); } if ($this->session->userdata('token') !== FALSE) { $client->setAccessToken($this->session->userdata('token')); if ($client->isAccessTokenExpired()) { $currentTokenData = json_decode($this->session->userdata('token')); if (isset($currentTokenData->refresh_token)) { $client->refreshToken($tokenData->refresh_token); } } } if ($client->getAccessToken() && $in_upload_state != "") { $this->load->helper('zimapi'); try { $videoPath = ZIMAPI_FILEPATH_TIMELAPSE; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($this->session->userdata('yt_title')); $snippet->setDescription($this->session->userdata("yt_desc")); $snippet->setTags($this->session->userdata("yt_tags")); // Numeric video category. See https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); // Set the video's status to "public". Valid statuses are "public", "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = $this->session->userdata('yt_privacy'); // Associate the snippet and status objects with a new video resource. $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $chunkSizeBytes = 1 * 1024 * 1024; // Setting the defer flag to true tells the client to return a request which can be called // with ->execute(); instead of making the API call immediately. $client->setDefer(true); // Create a request for the API's videos.insert method to create and upload the video. $insertRequest = $youtube->videos->insert("status,snippet", $video); // Create a MediaFileUpload object for resumable uploads. $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/mp4', null, true, $chunkSizeBytes); $media->setFileSize(filesize($videoPath)); // Read the media file and upload it chunk by chunk. $status = false; $handle = fopen($videoPath, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } fclose($handle); $client->setDefer(false); $this->session->unset_userdata(array('yt_title', 'yt_desc', 'yt_tags', 'yt_privacy')); echo "<h3>Video Uploaded</h3><ul>"; echo sprintf('<li>%s (%s)</li>', $status['snippet']['title'], $status['id']); echo '</ul>'; //stats info $this->load->helper('printerlog'); PrinterLog_statsShareVideo(PRINTERLOG_STATS_LABEL_YOUTUBE); } catch (Google_ServiceException $e) { $this->_exitWithError500(sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()))); } catch (Google_Exception $e) { $this->_exitWithError500(sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()))); } $this->session->set_userdata('token', $client->getAccessToken()); } else { $this->load->helper(array('zimapi', 'corestatus')); $prefix = CoreStatus_checkTromboning() ? 'https://' : 'http://'; $data = array('printersn' => ZimAPI_getSerial(), 'URL' => $prefix . $_SERVER['HTTP_HOST'] . '/share/video_upload'); $options = array('http' => array('header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data))); $context = stream_context_create($options); @file_get_contents('https://sso.zeepro.com/url.ashx', false, $context); $result = substr($http_response_header[0], 9, 3); if ($result == 200) { //echo 'ca marche'; } $state = ZimAPI_getSerial(); $client->setState($state); $this->session->set_userdata('state', $state); $authUrl = $client->createAuthUrl(); $this->output->set_header("Location: " . $authUrl); } return; }
public function google_access($flag) { include_once APPPATH . "third_party/Google/autoload.php"; //include_once APPPATH . "libraries/Google/Client.php"; //include_once APPPATH . "libraries/google-api-php-client-master/src/Google/Service/Oauth2.php"; //include_once APPPATH . "libraries/Google/Service/Youtube.php"; $scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner'); $client = new Google_Client(); $client->setClientId($this->client_id); $client->setClientSecret($this->client_secret); //$client->setScopes('https://www.googleapis.com/auth/youtube'); $client->setScopes($scope); $client->setRedirectUri($this->redirect_uri); $client->setApplicationName($this->application_name); $client->setAccessType('offline'); $youtube = new Google_Service_YouTube($client); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); } if ($flag == '') { if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); $client->getAccessToken(); $_SESSION['token'] = $client->getAccessToken(); //unset($_SESSION['token']); var_dump($_SESSION); return 1; } else { $authUrl = $client->createAuthUrl(); $string = '<script src="' . base_url() . '"assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>'; return $string; } } if ($flag) { if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); $client->getAccessToken(); $_SESSION['token'] = $client->getAccessToken(); try { /*if($client->isAccessTokenExpired()) { $newToken = json_decode($client->getAccessToken()); $client->refreshToken($newToken->access_token); }*/ $video_det = explode(',', $flag); // $video_det[0], $video_det[1]; $videoPath = $video_det[0]; $videoTitle = $video_det[1]; $videoDescription = "A video tutorial on how to upload to YouTube"; $videoCategory = "22"; $videoTags = array("youtube", "tutorial"); $youtube = new Google_Service_YouTube($client); // Create a snipet with title, description, tags and category id $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($videoTitle); $snippet->setDescription($videoDescription); $snippet->setCategoryId($videoCategory); $snippet->setTags($videoTags); // Create a video status with privacy status. Options are "public", "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); $status->setPrivacyStatus('private'); // Create a YouTube video with snippet and status $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks, // for reliable connections). Setting it lower leads better recovery (fine-grained chunks) $chunkSizeBytes = 1 * 1024 * 1024; // Setting the defer flag to true tells the client to return a request which can be called // with ->execute(); instead of making the API call immediately. $client->setDefer(true); // Create a request for the API's videos.insert method to create and upload the video. $insertRequest = $youtube->videos->insert("status,snippet", $video); // Create a MediaFileUpload object for resumable uploads. $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes); $media->setFileSize(filesize($videoPath)); //var_dump(filesize($videoPath)); // Read the media file and upload it chunk by chunk. $status = false; $handle = fopen($videoPath, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } fclose($handle); // Video has successfully been upload, now lets perform some cleanup functions for this video if ($status->status['uploadStatus'] == 'uploaded') { // Actions to perform for a successful upload redirect('home', 'refresh'); } // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); } catch (Google_Service_Exception $e) { print "Caught Google service Exception " . $e->getCode() . " message is " . $e->getMessage(); print "Stack trace is " . $e->getTraceAsString(); } catch (Exception $e) { print "Caught Google service Exception " . $e->getCode() . " message is " . $e->getMessage(); print "Stack trace is " . $e->getTraceAsString(); } } else { $authUrl = $client->createAuthUrl(); $string = '<script src="' . base_url() . 'assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>'; return $string; } if ($client->getAccessToken()) { try { // Call the channels.list method to retrieve information about the // currently authenticated user's channel. $channelsResponse = $youtube->channels->listChannels('contentDetails', array('mine' => 'true')); $htmlBody = ''; foreach ($channelsResponse['items'] as $channel) { // Extract the unique playlist ID that identifies the list of videos // uploaded to the channel, and then call the playlistItems.list method // to retrieve that list. $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads']; $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array('playlistId' => $uploadsListId, 'maxResults' => 50)); $htmlBody .= "<h3>Videos in list {$uploadsListId}</h3><ul>"; foreach ($playlistItemsResponse['items'] as $playlistItem) { $htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'], $playlistItem['snippet']['resourceId']['videoId']); } $htmlBody .= '</ul>'; } } catch (Google_ServiceException $e) { $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } $_SESSION['token'] = $client->getAccessToken(); } else { $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $string = '<script src="' . base_url() . '"assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>'; return $string; } } }
/** * Retrieve the authorization URL. * * @param String $emailAddress User's e-mail address. * @param String $state State for the authorization URL. * @return String Authorization URL to redirect the user to. */ function getAuthorizationUrl($emailAddress, $state) { $client = new Google_Client(); $client->setClientId($this->ClientId); $client->setRedirectUri($this->redirect_url); $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $client->setState($state); $client->setScopes($this->authorizationUrl); $tmpUrl = parse_url($client->createAuthUrl()); $query = explode('&', $tmpUrl['query']); $query[] = 'user_id=' . urlencode($emailAddress); return $tmpUrl['scheme'] . '://' . $tmpUrl['host'] . $tmpUrl['port'] . $tmpUrl['path'] . '?' . implode('&', $query); }
function google($video_temp = '', $video_name = '', $video_desc = '') { $OAUTH2_CLIENT_ID = '353001433162-42vrona3fi8msfve7akh857t6fk0di9v.apps.googleusercontent.com'; $OAUTH2_CLIENT_SECRET = 'cEcHT7CkTK5GYUDmC7dgYa8r'; $redirect = 'http://localhost/multitvfinal/index.php/video/google'; $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); $youtube = new Google_Service_YouTube($client); if (isset($_GET['code'])) { if (strval($this->session->userdata('state')) !== strval($_GET['state'])) { die('The session state did not match.'); } $client->authenticate($_GET['code']); $this->session->set_userdata('token', $client->getAccessToken()); header('Location: ' . $redirect); } $session_token = $this->session->userdata('token'); if ($session_token) { $client->setAccessToken($this->session->userdata('token')); } if ($client->getAccessToken()) { if (isset($video_temp) && $video_temp != '') { // REPLACE this value with the path to the file you are uploading. $videoPath = $video_temp; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($video_name); $snippet->setDescription($video_desc); $snippet->setTags(array("globalPunjab", "Video")); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); $snippet->setChannelTitle("GlobalPunjab"); // Set the video's status to "public". Valid statuses are "public", // "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = "public"; // Associate the snippet and status objects with a new video resource. $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $chunkSizeBytes = 1 * 1024 * 1024; // Setting the defer flag to true tells the client to return a request which can be called // with ->execute(); instead of making the API call immediately. $client->setDefer(true); // Create a request for the API's videos.insert method to create and upload the video. $insertRequest = $youtube->videos->insert("status,snippet", $video); // Create a MediaFileUpload object for resumable uploads. $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes); $media->setFileSize(filesize($videoPath)); // Read the media file and upload it chunk by chunk. $status = false; $handle = fopen($videoPath, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } fclose($handle); // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); $htmlBody = $status['id']; //echo "<pre>"; print_r($status); } $htmlBody = false; } else { // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $this->session->set_userdata('state', $state); //echo $this->session->userdata('state'); $authUrl = $client->createAuthUrl(); $htmlBody = $authUrl; } return $htmlBody; //spl_autoload_register('google_api_php_client_autoload'); die; }
function buildWidgetRSSDropDown($instance) { // set our default instance arguments $instance = wp_parse_args((array) $instance, array('select_user' => '1234~~Recent Uploads~~user_channel', 'randomize_feed' => 0)); ?> <script type="text/javascript"> jQuery(document).ready(function() { var user_subscription_feed_dropdown = jQuery('#user_subscription_feeds'); jQuery('.widget-inside').undelegate( ".feed_selector" , 'change' ).delegate( ".feed_selector" , 'change' , function() { var selected_feed = jQuery(this.options[this.selectedIndex]).closest('optgroup').prop('class'); if ( selected_feed == 'user_playlist' || selected_feed == 'user_channels' ) { jQuery(this).parents('.widget-content').find('#user_subscription_feeds').fadeOut('fast'); } else if ( selected_feed == 'user_subscription' ) { // get the feed to display text jQuery('.widget-content').find('#user_subscription_feeds').find('select').find('option').each(function() { var dropdown_text = jQuery('.widget-content').find('#user_selection').find('select option:selected').text().replace( 'Your Uploads' , '' ); var the_dropdown_text = jQuery(this).val(); jQuery(this).html(dropdown_text+' '+'<span style="text-transform:capitalize;">'+the_dropdown_text+'</span>'); }); jQuery(this).parents('.widget-content').find('#user_subscription_feeds').fadeIn('fast'); } }); }); </script> <?php // Call set_include_path() as needed to point to your client library. require_once YT4WP_PATH . 'inc/Google/Client.php'; require_once YT4WP_PATH . 'inc/Google/Service/YouTube.php'; /* * Check if session has started * On callback, it tries to restart the session * Throwing an error */ if (!isset($_SESSION)) { session_start(); } // check if yt plus session is started /* * You can acquire an OAuth 2.0 client ID and client secret from the * Google Developers Console <https://console.developers.google.com/> * For more information about using OAuth 2.0 to access Google APIs, please see: * <https://developers.google.com/youtube/v3/guides/authentication> * Please ensure that you have enabled the YouTube Data API for your project. */ $YT4WPBase = new YT4WPBase(); $OAUTH2_CLIENT_ID = $YT4WPBase->optionVal['yt4wp-oauth2-key']; $OAUTH2_CLIENT_SECRET = $YT4WPBase->optionVal['yt4wp-oauth2-secret']; $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?page=youtube-for-wordpress', FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); // Define an object that will be used to make all API requests. $youtube = new Google_Service_YouTube($client); if (isset($screen_base) && $screen_base == '') { $screen_base = get_current_screen()->base; } if (isset($_GET['code'])) { if (strval($_SESSION['state']) !== strval($_GET['state'])) { // die('The session state did not match.'); } $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); $token_array = explode(",", str_replace("}", "", str_replace("{", "", str_replace("\"", "", $_SESSION['token'])))); // empty exploded token data array $exploded_token_array = array(); // loop over to build our array of token data foreach ($token_array as $token_data) { $exploded_token_array[] = explode(":", $token_data); } // remove our \ in the refresh token, which throws errors // when sending to YouTube APi $refresh_token = str_replace("\\", "", $exploded_token_array[3][1]); // update the refresh token option with the new refresh token update_option('yt4wp_user_refresh_token', $refresh_token); // set the access token $client->setAccessToken($_SESSION['token']); // set our headers $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); header('Location: ' . $redirect); } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } if ($client->isAccessTokenExpired()) { // check if the user has ANY data stored in the token session // if they do, but the token has expired, we simply call a refresh // on the refresh token to retreive new access tokens // // we do this to avoid re-authorizing every time you use // the plugin -- this is all done behind the scenes ;) if (get_option('yt4wp_user_refresh_token') != '') { $client->refreshToken(get_option('yt4wp_user_refresh_token')); $_SESSION['token'] = $client->getAccessToken(); } else { // this runs only the first time the user ever installs the plugin echo '<div class="error"><p>' . __("Access Token Has Expired - Please ReAuthenticate", "yt-plus-translation-text-domain") . '</p></div>'; // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $htmlBody = <<<END <h3>Authorization Required</h3> <p>You need to <a href="{$authUrl}">authorize access</a> before proceeding.<p> END; } } // Check to ensure that the access token was successfully acquired. if ($_SESSION['token'] != '') { try { // Call the channels.list method to retrieve information about the // currently authenticated user's channel. $subscriptionsResponse = $youtube->subscriptions->listSubscriptions('snippet', array('mine' => 'true', 'maxResults' => 50)); // list my playlists here as well $userPlaylists = $youtube->playlists->listPlaylists('snippet', array('mine' => 'true', 'maxResults' => 50)); // list my channels here as well // ( includes favorites, watch history, likes, recent uploads etc. ) $userChannels = $youtube->channels->listChannels('contentDetails', array('mine' => 'true')); // Testing returned data from YouTube API // subscription list... // to do--- // get all video for given subscription // print_r($subscriptionsResponse); // define our htmlBody variable $htmlBody = ''; $htmlBody .= '<select style="width:100%;" id="' . $this->get_field_id('select_user') . '" class="feed_selector" name="' . $this->get_field_name('select_user') . '">'; // list user channels // likes, favorites, uploads etc. // set up the user channel dropdown if ($userChannels) { $htmlBody .= '<optgroup label="Your Channels" class="user_channels">'; foreach ($userChannels['items'] as $channel) { // Extract the unique playlist ID that identifies the list of videos // uploaded to the channel, and then call the playlistItems.list method // to retrieve that list. if (isset($channel['contentDetails']['relatedPlaylists']['uploads']) && $instance["select_user"] == $channel['contentDetails']['relatedPlaylists']['uploads'] . '~~Recent Uploads~~user_channel') { $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads']; $htmlBody .= '<option value="' . $uploadsListId . '~~Recent Uploads~~user_channel" selected="selected">Your Uploads</option>'; } else { $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads']; $htmlBody .= '<option value="' . $uploadsListId . '~~Recent Uploads~~user_channel">Your Uploads</option>'; } if (isset($channel['contentDetails']['relatedPlaylists']['likes']) && $instance["select_user"] == $channel['contentDetails']['relatedPlaylists']['likes'] . '~~Likes~~user_channel') { $likesListId = $channel['contentDetails']['relatedPlaylists']['likes']; $htmlBody .= '<option value="' . $likesListId . '~~Likes~~user_channel" selected="selected">Your Likes</option>'; } else { $likesListId = $channel['contentDetails']['relatedPlaylists']['likes']; $htmlBody .= '<option value="' . $likesListId . '~~Likes~~user_channel" >Your Likes</option>'; } if (isset($channel['contentDetails']['relatedPlaylists']['favorites']) && $instance["select_user"] == $channel['contentDetails']['relatedPlaylists']['favorites'] . '~~Favorites~~user_channel') { $favoritesListId = $channel['contentDetails']['relatedPlaylists']['favorites']; $htmlBody .= '<option value="' . $favoritesListId . '~~Favorites~~user_channel" selected="selected">Your Favorites</option>'; } else { $favoritesListId = $channel['contentDetails']['relatedPlaylists']['favorites']; $htmlBody .= '<option value="' . $favoritesListId . '~~Favorites~~user_channel">Your Favorites</option>'; } } $htmlBody .= '</optgroup>'; } // end the user channels dropdown // print_r($userPlaylists); // set up the user playlists dropdown $htmlBody .= '<optgroup label="Your Playlists" class="user_playlist">'; // list user playlists, if any are found if ($userPlaylists['modelData']['pageInfo']['totalResults'] > 0) { // print_r($userPlaylists); foreach ($userPlaylists as $playlist) { if ($playlist['modelData']['snippet']['title'] != 'Favorites') { if (isset($instance["select_user"]) && $instance["select_user"] == $playlist['id'] . '~~' . $playlist['modelData']['snippet']['title'] . '~~user_playlist') { $htmlBody .= '<option value="' . $playlist['id'] . '~~' . $playlist['modelData']['snippet']['title'] . '~~user_playlist" selected="selected">' . ucwords($playlist['modelData']['snippet']['title']) . '</option>'; } else { $htmlBody .= '<option value="' . $playlist['id'] . '~~' . $playlist['modelData']['snippet']['title'] . '~~user_playlist">' . ucwords($playlist['modelData']['snippet']['title']) . '</option>'; } } } } else { $htmlBody .= '<option value="no_playlists_found" disabled="disabled">No Playlists Found</option>'; } $htmlBody .= '</optgroup>'; // end user playlists dropdown // set up the subscriptions dropdown $htmlBody .= '<optgroup label="Your Subscriptions" class="user_subscription">'; // list users subscriptions if ($subscriptionsResponse['modelData']['pageInfo']['totalResults'] > 0) { foreach ($subscriptionsResponse as $subscription) { if (isset($instance["select_user"]) && $instance["select_user"] == $subscription["modelData"]['snippet']["resourceId"]["channelId"] . '~~' . $subscription['modelData']['snippet']['title']) { $htmlBody .= '<option value="' . $subscription["modelData"]['snippet']["resourceId"]["channelId"] . '~~' . $subscription['modelData']['snippet']['title'] . '" selected="selected">' . ucwords($subscription['modelData']['snippet']['title']) . '</option>'; } else { $htmlBody .= '<option value="' . $subscription["modelData"]['snippet']["resourceId"]["channelId"] . '~~' . $subscription['modelData']['snippet']['title'] . '">' . ucwords($subscription['modelData']['snippet']['title']) . '</option>'; } } } else { $htmlBody .= '<option value="no_subscritions" disabled="disabled">No Subscriptions Found</option>'; } $htmlBody .= '</optgroup>'; // end subscriptions dropdown $htmlBody .= '</select>'; // end dropdown all together } catch (Google_ServiceException $e) { $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('<p>A client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } echo $htmlBody; } }
/** * Retrieve the authorization URL. * * @param String $emailAddress User's e-mail address. * @param String $state State for the authorization URL. * @return String Authorization URL to redirect the user to. */ public function getAuthorizationUrl($state) { if ($this->_enabled) { $client = new Google_Client(); $client->setClientId($this->clientId); switch ($state) { case 'calendar': $_SESSION['calendarForceRefresh'] = 1; $client->setRedirectUri((@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . Yii::app()->controller->createUrl('/calendar/calendar/syncActionsToGoogleCalendar')); break; default: $client->setRedirectUri($this->redirectUri); } $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $client->setState($state); $client->setScopes($this->scopes); return $client->createAuthUrl(); } else { return false; } // $tmpUrl = parse_url($client->createAuthUrl()); // $query = explode('&', $tmpUrl['query']); // $query[] = 'user_id='.urlencode($emailAddress); // return // $tmpUrl['scheme'].'://'.$tmpUrl['host'].$tmpUrl['port']. // $tmpUrl['path'].'?'.implode('&', $query); }
function GoogleLogin() { $post = $_POST; $get = $_GET; $request = $_REQUEST; $site = $this->siteUrl(); $callBackUrl = $this->callBackUrl(); $options = get_option(APSL_SETTINGS); $response = new stdClass(); $a = explode('_', $_GET['apsl_login_id']); $action = $a[1]; $client_id = $options['apsl_google_settings']['apsl_google_client_id']; $client_secret = $options['apsl_google_settings']['apsl_google_client_secret']; $site_url = site_url() . '/wp-admin'; $encoded_url = isset($_GET['redirect_to']) ? $_GET['redirect_to'] : $site_url; $callback = $callBackUrl . 'apsl_login_id' . '=google_check'; $redirect_uri = $callback; $client = new Google_Client(); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->setRedirectUri($redirect_uri); $client->addScope("https://www.googleapis.com/auth/plus.profile.emails.read"); if (isset($encoded_url) && $encoded_url != '') { $client->setState(base64_encode("redirect_to={$encoded_url}")); } else { } $service = new Google_Service_Plus($client); if ($action == 'login') { // Get identity from user and redirect browser to OpenID Server if (!(isset($_SESSION['access_token']) && $_SESSION['access_token'])) { $authUrl = $client->createAuthUrl(); $this->redirect($authUrl); die; } else { // if($encoded_url == ''){ // $this->redirect($redirect_uri); // }else{ $this->redirect($redirect_uri . "&redirect_to={$encoded_url}"); // } die; } } elseif (isset($_GET['code'])) { // Perform HTTP Request to OpenID server to validate key $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $this->redirect($redirect_uri . "&redirect_to={$encoded_url}"); die; } elseif (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); try { $user = $service->people->get("me", array()); } catch (Exception $fault) { unset($_SESSION['access_token']); $ref_object = $this->accessProtected($fault, 'errors'); echo $ref_object[0]['message'] . " Please notify about this error to the Site Admin."; die; } if (!empty($user)) { if (!empty($user->emails)) { $response->email = $user->emails[0]->value; $response->username = $user->emails[0]->value; $response->first_name = $user->name->givenName; $response->last_name = $user->name->familyName; $response->deuid = $user->emails[0]->value; $response->deuimage = $user->image->url; $response->gender = $user->gender; $response->id = $user->id; $response->about = $user->aboutMe; $response->url = $user->url; $response->deutype = 'google'; $response->status = 'SUCCESS'; $response->error_message = ''; } else { $response->status = 'ERROR'; $response->error_code = 2; $response->error_message = "INVALID AUTHORIZATION"; } } else { // Signature Verification Failed $response->status = 'ERROR'; $response->error_code = 2; $response->error_message = "INVALID AUTHORIZATION"; } } elseif ($get['openid_mode'] == 'cancel') { // User Canceled your Request $response->status = 'ERROR'; $response->error_code = 1; $response->error_message = "USER CANCELED REQUEST"; } else { // User failed to login $response->status = 'ERROR'; $response->error_code = 3; $response->error_message = "USER LOGIN FAIL"; } return $response; }
/** * Method to setup google params and redirect to google auth URL * * @param object $view view object * @param object $tpl template object * @return void */ public function display($view, $tpl) { // Set up the config for the google api instance $client = new Google_Client(); $client->setClientId($this->params->get('app_id')); $client->setClientSecret($this->params->get('app_secret')); $client->setRedirectUri(self::getRedirectUri('google')); $client->setAccessType('online'); $client->setState($view->return); $client->setApprovalPrompt('auto'); $client->setScopes('https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'); // Create and follow the authorization URL App::redirect($client->createAuthUrl()); }
/** * Retrieve the authorization URL. * * @param String $email_address User's e-mail address. * @return String Authorization URL to redirect the user to. */ public static function getAuthorizationUrl($client_id, $redirect_uri, $scopes, $email_address = false) { require_once CASH_PLATFORM_ROOT . '/lib/google/Google_Client.php'; $client = new Google_Client(); $client->setClientId($client_id); $client->setRedirectUri($redirect_uri); $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $client->setState('preauth'); $client->setScopes($scopes); $auth_url = $client->createAuthUrl(); if ($email_address) { $client->setState('refresh'); $tmpUrl = parse_url($auth_url); $query = explode('&', $tmpUrl['query']); $query[] = 'user_id=' . urlencode($email_address); return $tmpUrl['scheme'] . '://' . $tmpUrl['host'] . $tmpUrl['port'] . $tmpUrl['path'] . '?' . implode('&', $query); } else { return $auth_url; } }
require_once 'autoload.php'; require_once '/Client.php'; require_once '/Service/Calendar.php'; //require_once 'CalendarHelper.php'; session_start(); $client = new Google_Client(); $client->setApplicationName("Client_Library_Examples"); //$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE"); $client->setClientId('882360446644-9ui7gju7k6cmj4ti6ilgp054h5glvfp9.apps.googleusercontent.com'); $client->setClientSecret('vVImW-aIa5avv2zh-EUK5zCq'); $client->setRedirectUri('http://localhost:4567/oauth2callback'); $client->setAccessType('offline'); // Gets us our refreshtoken $client->setScopes(array('https://www.googleapis.com/auth/calendar')); $client->setState("https://u5.fengoffice.com/_feng"); //For loging out. if (isset($_GET['logout'])) { unset($_SESSION['token']); } // Step 2: The user accepted your access now you need to exchange it. if (isset($_GET['code'])) { print_r($_SESSION); print_r($_GET); $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; $redirect = $_GET['state']; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); } // Step 1: The user has not authenticated we give them a link to login
public function youtube_upload($video = "linkedin.mp4", $title = "tvn rahul youtube api v3", $desc = "tvn rahul youtube api v3 for php", $tags = ["rahultvn", "youtubeapi3"], $privacy_status = "public") { $result = []; $htmlBody = ""; $OAUTH2_CLIENT_ID = $this->ci->config->item('OAUTH2_CLIENT_ID'); //'980811603180-qlbtavji7o0ekejgerqifous319d2he2.apps.googleusercontent.com'; $OAUTH2_CLIENT_SECRET = $this->ci->config->item('OAUTH2_CLIENT_SECRET'); //'sbzALHg38sB9aXEo0a9GG4ZA'; $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = $this->ci->config->item('REDIRECT_URI'); //filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], //FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); // Define an object that will be used to make all API requests. $youtube = new Google_Service_YouTube($client); if (isset($_GET['code'])) { if (strval($_SESSION['state']) !== strval($_GET['state'])) { die('The session state did not match.'); } $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); header('Location: ' . $redirect); } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } // Check to ensure that the access token was successfully acquired. if ($client->getAccessToken()) { //echo $client->getAccessToken(); try { // REPLACE this value with the path to the file you are uploading. $videoPath = realpath(APPPATH . '../videos/' . $video); //$videoPath = "videos/linkedin.mp4"; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($title); $snippet->setDescription($desc); $snippet->setTags($tags); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); // Set the video's status to "public". Valid statuses are "public", // "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = $privacy_status; // Associate the snippet and status objects with a new video resource. $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $chunkSizeBytes = 1 * 1024 * 1024; // Setting the defer flag to true tells the client to return a request which can be called // with ->execute(); instead of making the API call immediately. $client->setDefer(true); // Create a request for the API's videos.insert method to create and upload the video. $insertRequest = $youtube->videos->insert("status,snippet", $video); // Create a MediaFileUpload object for resumable uploads. $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes); $media->setFileSize(filesize($videoPath)); // Read the media file and upload it chunk by chunk. $status = false; $handle = fopen($videoPath, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } fclose($handle); // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); $htmlBody .= "<h3>Video Uploaded</h3><ul>"; $htmlBody .= sprintf('<li>%s (%s)</li>', $status['snippet']['title'], $status['id']); $htmlBody .= '</ul>'; $result['id'] = $status['id']; $result['title'] = $status['snippet']['title']; } catch (Google_Service_Exception $e) { $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } $_SESSION['token'] = $client->getAccessToken(); } else { // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $htmlBody .= "<h3>Authorization Required</h3>"; $htmlBody .= "<p>You need to <a href=" . $authUrl . ">authorize access</a> before proceeding.<p>"; $result['authUrl'] = $authUrl; } $result['message'] = $htmlBody; return $result; }
function setAppConfig($approval = 'auto') { $this->client = new Google_Client(); /* Set Retries */ $this->client->setClassConfig('Google_Task_Runner', 'retries', 5); $this->userInfoService = new Google_Service_Oauth2($this->client); $this->googleDriveService = new Google_Service_Drive($this->client); $this->googleUrlshortenerService = new Google_Service_Urlshortener($this->client); if (!empty($this->settings['googledrive_app_client_id']) && !empty($this->settings['googledrive_app_client_secret'])) { $this->client->setClientId($this->settings['googledrive_app_client_id']); $this->client->setClientSecret($this->settings['googledrive_app_client_secret']); } else { $this->client->setClientId('538839470620-fvjmtsvik53h255bnu0qjmbr8kvd923i.apps.googleusercontent.com'); $this->client->setClientSecret('UZ1I3I-D4rPhXpnE8T1ggGhE'); } $this->client->setRedirectUri('http://www.florisdeleeuw.nl/use-your-drive/index.php'); $this->client->setApprovalPrompt($approval); $this->client->setAccessType('offline'); $this->client->setScopes(array('https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/urlshortener')); $page = isset($_GET["page"]) ? '?page=' . $_GET["page"] : ''; $location = get_admin_url(null, 'admin.php' . $page); $this->client->setState(strtr(base64_encode($location), '+/=', '-_~')); /* Logger */ $this->client->setClassConfig('Google_Logger_File', array('file' => USEYOURDRIVE_CACHEDIR . '/log', 'mode' => 0640, 'lock' => true)); $this->client->setClassConfig('Google_Logger_Abstract', array('level' => 'debug', 'log_format' => "[%datetime%] %level%: %message% %context%\n", 'date_format' => 'd/M/Y:H:i:s O', 'allow_newlines' => true)); /* Uncomment the following line to log communcations. * The log is located in /cache/log */ //$this->client->setLogger(new Google_Logger_File($this->client)); return true; }