include_once __DIR__ . '/../vendor/autoload.php';
//include_once "templates/base.php";
$sc = '************************************/service-account-credentials.json';
$cs = '******************************************/google-api-php-client-2.0.0/client_secret.json';
define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
//define('CREDENTIALS_PATH', __DIR__ . '/../service-account-credentials.json');
define('CREDENTIALS_PATH', $sc);
define('CLIENT_SECRET_PATH', $cs);
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Calendar::CALENDAR_READONLY)
));
//if (php_sapi_name() != 'cli') {
// throw new Exception('This application must be run on the command line.');
//}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
exit;
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->authenticate($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, $accessToken);
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, $client->getAccessToken());
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
echo pageHeader("Service Account Access");
//TELL GOOGLE WHAT WE'RE DOING
$client = new Google_Client();
$client->setApplicationName("My Calendar"); //DON'T THINK THIS MATTERS
$client->setDeveloperKey('***************************************'); //GET AT AT DEVELOPERS.GOOGLE.COM
$cal = new Google_Service_Calendar($client);
//THE CALENDAR ID, FOUND IN CALENDAR SETTINGS. IF YOUR CALENDAR IS THROUGH GOOGLE APPS
//YOU MAY NEED TO CHANGE THE CENTRAL SHARING SETTINGS. THE CALENDAR FOR THIS SCRIPT
//MUST HAVE ALL EVENTS VIEWABLE IN SHARING SETTINGS.
//$calendarId = '****************************************************';
$calendarList = $cal->calendarList->listCalendarList();
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary();
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
<?php pageFooter(__FILE__); ?>
function checkServiceAccountCredentialsFile(){ // service account creds //$application_creds = __DIR__ . '/../../service-account-credentials.json'; $application_creds = 'GOOGLE_APPLICATION_CREDENTIALS=' . API_CREDENTIALS_PATH . '/service-account-credentials.json'; putenv( $application_creds ); return file_exists($application_creds) ? $application_creds : false;}<?phpinclude_once __DIR__ . '/../vendor/autoload.php';include_once "templates/base.php";
echo pageHeader("Calendar List");
/************************************************* * Ensure you've downloaded your oauth credentials ************************************************/if (!$oauth_credentials = getOAuthCredentialsFile()) { echo missingOAuth2CredentialsWarning(); return;}
/************************************************ * The redirect URI is to the current page, e.g: ************************************************/$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google_Client();checkServiceAccountCredentialsFile();$client->setAuthConfig($oauth_credentials);$client->setRedirectUri($redirect_uri);$client->addScope("https://www.googleapis.com/auth/calendar");$service = new Google_Service_Calendar($client);
// add "?logout" to the URL to remove a token from the sessionif (isset($_REQUEST['logout'])) { unset($_SESSION['calendar_token']); header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));}
/************************************************ * If we have a code back from the OAuth 2.0 flow, * we need to exchange that with the * Google_Client::fetchAccessTokenWithAuthCode() * function. We store the resultant access token * bundle in the session, and redirect to ourself. ************************************************/if (isset($_GET['code'])) { $token = $client->fetchAccessTokenWithAuthCode($_GET['code']); $client->setAccessToken($token);
// store in the session also $_SESSION['calendar_token'] = $token;
// redirect back to the example if (!headers_sent()) { header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); }}
// set the access token as part of the clientif (!empty($_SESSION['calendar_token'])) { $client->setAccessToken($_SESSION['calendar_token']); if ($client->isAccessTokenExpired()) { unset($_SESSION['calendar_token']); }} else { $authUrl = $client->createAuthUrl();}
$request = array_merge($_GET, $_POST);if(isset($request['timeMin'])): $date = new DateTime($request['timeMin']); $time['timeMin'] = $date->format(DateTime::ATOM);else: $date = new DateTime(); $time['timeMin'] = $date->format(DateTime::ATOM);endif;if(isset($request['timeMax'])): $date = new DateTime($request['timeMax']); $time['timeMax'] = $date->format(DateTime::ATOM);else: $date = new DateTime(); $time['timeMax'] = $date->format(DateTime::ATOM);endif;
?>
<div class="box" style="max-width: 900px; width: 98%;"><?php if (isset($authUrl) ){ ?> <div class="request"> <a class='login' href='<?= $authUrl ?>'>Connect Me!</a> </div><?php }elseif( isset($_GET['code']) && $_GET['code'] != '' ){ ?> <div> <p>Your call was successful!</p> <p><a href="https://verwoerd.meta-inc.com/google-api-php-client-2.0.1/examples/calendar-list.php">Get Calendar List</a></p> <a class='logout' href='?logout'>Logout</a> </div><?php }else{?> <div class="result" style="max-width: 900px; width: 98%;">
<?php /************************************************ * If we're signed in then lets try to upload our * file. ************************************************/
$calendarList = $service->calendarList->listCalendarList();
while(true) { foreach ($calendarList->getItems() as $calendarListEntry) { $summary = $calendarListEntry->getSummary(); if($summary != '') echo '<span>' . $calendarListEntry->id .': '. $calendarListEntry->getSummary() .'</span>' ."<br />"; } $pageToken = $calendarList->getNextPageToken(); if ($pageToken) { $optParams = array('pageToken' => $pageToken); $calendarList = $service->calendarList->listCalendarList($optParams); } else { break; } }
echo "<p><a class='logout' href='?logout'>Logout</a></p>"; } ?> </div> </div>