Skip to content

Instantly share code, notes, and snippets.

@georgestephanis
Created April 24, 2019 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgestephanis/2aa444e96e0439e96b2aac5317722e88 to your computer and use it in GitHub Desktop.
Save georgestephanis/2aa444e96e0439e96b2aac5317722e88 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Grunion to Google Sheets
*/
require __DIR__ . '/vendor/autoload.php';
define( 'SPREADSHEET_ID', '' );
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig( __DIR__ . '/credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = __DIR__ . '/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} 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->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
function add_sheet_to_spreadsheet( $service, $spreadsheetId, $sheetTitle ) {
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => [
new Google_Service_Sheets_Request([
'addSheet' => [
'properties' => [
'title' => $sheetTitle,
],
],
]),
],
]);
return $service->spreadsheets->batchUpdate( $spreadsheetId, $requestBody );
}
function does_spreadsheet_have_sheet( $service, $spreadsheetId, $sheetTitle ) {
$sheets = $service->spreadsheets->get( $spreadsheetId )->getSheets();
foreach ( $sheets as $sheet ) {
if ( $sheetTitle === $sheet->properties->title ) {
return true;
}
}
return false;
}
function insert_row_into_sheet( $service, $spreadsheetId, $sheetTitle, $data ) {
$body = new Google_Service_Sheets_ValueRange([
'values' => [
$data
]
]);
$params = [
'valueInputOption' => 'RAW',
];
return $service->spreadsheets_values->append(
$spreadsheetId,
$sheetTitle,
$body,
$params
);
}
/**
* Set up actions to capture form submissions and track them.
*/
if ( function_exists( 'add_action' ) ) {
add_action( 'grunion_pre_message_sent', 'send_submission_to_gsheets', 10, 2 );
}
function send_submission_to_gsheets( $post_id, $all_values, $service = null ) {
$sheetTitle = $all_values['entry_title'];
$values = array_merge(
array(
'feedback_id' => $all_values['feedback_id'],
),
array_diff_key(
$all_values,
array(
'entry_title' => null,
'entry_permalink' => null,
'feedback_id' => null,
)
)
);
if ( ! $service ) {
$client = getClient();
$service = new Google_Service_Sheets( $client );
}
if ( ! does_spreadsheet_have_sheet( $service, SPREADSHEET_ID, $sheetTitle ) ) {
add_sheet_to_spreadsheet( $service, SPREADSHEET_ID, $sheetTitle );
insert_row_into_sheet( $service, SPREADSHEET_ID, $sheetTitle, array_keys( $values ) );
}
insert_row_into_sheet( $service, SPREADSHEET_ID, $sheetTitle, array_values( $values ) );
}
if ( php_sapi_name() === 'cli' ) {
$client = getClient();
$service = new Google_Service_Sheets( $client );
include( __DIR__ . '/../../../wp-load.php' );
$feedbacks = get_posts( array(
'posts_per_page' => -1,
'post_type' => 'feedback',
'post_status' => 'publish',
'order' => 'ASC',
'fields' => 'ids',
'suppress_filters' => false,
) );
$grunion = Grunion_Contact_Form_Plugin::init();
foreach ( $feedbacks as $feedback ) {
$post_fields = $grunion->get_parsed_field_contents_of_post( $feedback );
send_submission_to_gsheets( $feedback['ID'], $post_fields['_feedback_all_fields'], $service );
}
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment