I want to create copy of excel sheet of google doc using PHP API.I can see java code but no PHP code at all :(
Actually I already have a excel sheet on google drive I want to show it on website, I am already successed in it but problem is The same file is visible to everyone and if one user is changing file and at the same time same user can see that changes as it is synced to google drive.
So I thought solution is if I can create a copy of the sheet and shows different-2 copies to each user via PHP API.
===============
Edited Code
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
$arr['convert'] = false;
$arr['visibility'] = 'default';
return $service->files->copy($originFileId, $copiedFile,$arr);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
function insertPermission($service, $fileId, $value, $type, $role) {
$newPermission = new Google_Permission();
$newPermission->setValue($value);
$newPermission->setType($type);
$newPermission->setRole($role);
try {
return $service->permissions->insert($fileId, $newPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
function updateRevision($service, $fileId, $revisionId) {
try {
// First retrieve the revision from the API.
$revisions = $service->revisions;
$revision = $revisions->get($fileId, $revisionId);
echo '<pre>';print_r($revision);
$revision->setPinned(true);
return $revisions->update($fileId, $revisionId, $revision);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
function updateRevision1($service, $fileId, $revisionId) {
$patchedRevision = new Google_Revision();
$patchedRevision->setPublished(true);
$patchedRevision->setPublishAuto(true);
$patchedRevision->setPublishedOutsideDomain(true);
try {
return $service->revisions->patch($fileId, $revisionId, $patchedRevision);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('clientid');
$client->setClientSecret('secret');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setRedirectUri('redirecturi');
$service = new Google_DriveService($client);
if(!isset($_GET['code']) ) {
$authUrl = $client->createAuthUrl();
header('location: '.$authUrl );
die;
}
else{
$authCode = $_GET['code'];
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
$new_file = copyFile($service,'fileid','Baby Schema');
echo 'file=<pre>';print_r($new_file);
$permission = insertPermission($service,$new_file['id'],'me','anyone','writer');
echo 'permission=<pre>';print_r($permission);
$revision = updateRevision1($service, $new_file['id'], '1');
echo 'pub=<pre>';print_r($revision);
}
Code is working absolutely perfect but it is not doing what I want.
The above code is doing these tasks
1) I have one spreadsheet on bhuvneshgupta333#gmail.com
2) I am creating copy when bhuvnesh.gupta#witslog.com login to my abc.com website.
3) I am setting copy to be public on web.
4) Making copy to be published on web.
Now I am having issue.
1) In the spreadsheet there are 5 sheets out of them 2 are editable and rest 3 are protected so no one can see my formulas.
2) When copy is created by bhuvnesh.gupta#witslog.com then he becomes the owner of file while file is on bhuvneshgupta333#gmail.com while I want Owner to be bhuvneshgupta not bhuvnesh.gupta because I don't want to show formulas to any one not even bhuvnesh.gupta when file is opened on web.
3) I want to protect 3 sheets of spreadsheet to everyone.
I am using this way to call spreadhseet on web.
<iframe width="100%" height="600" src="https://docs.google.com/spreadsheets/d/fileid/edit?usp=sharing;&rm=minimal"></iframe>
Please help me guys.It's last point of my project.
Please help me guys.
Thanks in advance!
The google drive API reference does include PhP code for file copying.
/**
* Copy an existing file.
*
* #param Google_DriveService $service Drive API service instance.
* #param String $originFileId ID of the origin file to copy.
* #param String $copyTitle Title of the copy.
* #return DriveFile The copied file. NULL is returned if an API error occurred.
*/
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
return $service->files->copy($originFileId, $copiedFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
It is here: https://developers.google.com/drive/v2/reference/files/copy#try-it
Related
I'm using this code and it's returning me URL and it looks fine and it creating the folder in public/sre_reports/
But after the URL I don't see what to do :
public function generatePublicReport()
{
try {
$report = new ReportOptions(Constants::SRE_PUBLIC_REPORT);
$report->select_tables(array("users"))
->set_grouping(array("id"))
->select_all_fields();
$engine = new CustomEngine($report);
$report_path = $engine->create_report();
return "Your report URL:" . $report_path;
} catch (Exception $ex) {
echo "Caught exception message:". $ex->getMessage();
}
}
OutPut: Your report URL:https://domainname.com/var/www/html/folder/public/sre_reports/rep1592553829503324/rep1592553829503324.php
We have a Google My business account that manage multiple locations. I want to create an interface for answering questions. My problem is that I can't find how to retreive the Author object for the current location.
I tried creating a new Google_Service_MyBusiness_Author object and submitting it but it doesn't seems to work. I'm using MyBusiness API 4.5
$author = new Google_Service_MyBusiness_Author();
$author->setDisplayName('location display name');
$author->setProfilePhotoUrl('someurl.jpg');
$author->setType('MERCHANT');
$answer = new Google_Service_MyBusiness_Answer();
$answer->setText($_POST['answerReplyText']);
$answer->setAuthor($author);
$postBody = new Google_Service_MyBusiness_UpsertAnswerRequest();
$postBody->setAnswer($answer);
try {
$mybusinessService->accounts_locations_questions_answers->upsert($_POST['question_name'],$postBody);
}
catch(Exception $e) {
var_dump($e);
}
I get the 'Request contains an invalid argument' exception. I am doing this the right way ? What should I do to make my answer valid ?
Please try the following by removing the output only fields:
// $author = new Google_Service_MyBusiness_Author();
// $author->setDisplayName('location display name');
// $author->setProfilePhotoUrl('someurl.jpg');
// $author->setType('MERCHANT');
$answer = new Google_Service_MyBusiness_Answer();
$answer->setText($_POST['answerReplyText']);
// $answer->setAuthor($author);
$postBody = new Google_Service_MyBusiness_UpsertAnswerRequest();
$postBody->setAnswer($answer);
try {
$mybusinessService->accounts_locations_questions_answers->upsert($_POST['question_name'],$postBody);
}
catch(Exception $e) {
var_dump($e);
}
This works for me quite well. Hope this will help you too.
I'm trying to read ratings from a Facebook page to display externally, using the PHP SDK. I already have a long live access token, and have been able to use it to pull in the main page data, but when I try access the /ratings endpoint, I just receive back an empty Array ( )
class FacebookReviews
{
protected $session;
protected $page;
protected $ratings;
protected $appId;
protected $appSecret;
function __construct($appId = null, $appSecret = null)
{
session_start();
$this->appId = '123456789123456';
$this->appSecret = '1234567890abcdefghijklmnopqrstuv';
Facebook\FacebookSession::setDefaultApplication($this->appId, $this->appSecret);
$this->session = new Facebook\FacebookSession('LONG LIVE ACCESS TOKEN I GENERATED ON THE GRAPH API');
try {
$this->session->validate();
} catch (Facebook\FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
echo $ex->getMessage();
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
echo $ex->getMessage();
}
try {
$this->page = (new Facebook\FacebookRequest($this->session, 'GET', '/123456789123456/ratings'))->execute()->getGraphObject()->asArray();
} catch(Facebook\FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
public function result()
{
return $this->page;
}
}
$reviews = new FacebookReviews();
print_r($reviews->result());
If I remove /ratings from the request uri, it returns the data fine, but as I mentioned with it in there it doesn't work.
I generated the long live access token from my own account, which has admin access to the page
I am trying to create a subscribe method for my laravel app that uses the mailchimp api to subscribe a user to a given list. The method works fine when the email address is not already on the lsit. when it is already subscribed the mailchimp api throws the following error
Mailchimp_List_AlreadySubscribed blah#blah.co is already subscribed to
list Tc App Test List. Click here to update your profile.
with the following code being shown
public function castError($result) {
if($result['status'] !== 'error' || !$result['name']) throw new Mailchimp_Error('We received an unexpected error: ' . json_encode($result));
$class = (isset(self::$error_map[$result['name']])) ? self::$error_map[$result['name']] : 'Mailchimp_Error';
return new $class($result['error'], $result['code']);
}
I have attempted a try catch block to catch the error but it is still being returned to the browser, here is what I tried and were it says MailChimp_Error I tried with Exception as well.
public function subscribe($id, $email, $merge_vars)
{
try {
$this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (MailChimp_Error $e) {
$response = 'an error has occured';
}
return $response;
}
Ultimately I want to be able to run the method and then either return either a success message or a message describing the issue to the user. the 3 possible mailchimp method errors are Email_notexists, list_alreadysubscribed and list does not exist although tihs last one should not occur as I am providing the list in the source code.
edit 1; after being in touch with mailchimp api support they suggested this code but the error still gets returned to the browser in its entirety
try {
$results = $this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (Mailchimp_Error $e) {
if ($e->getMessage()) {
$error = 'Code:'.$e->getCode().': '.$e->getMessage();
}
}
echo $error;
You can do
try
{
$response = $this->mailchimp->lists->addListMember($list_id, [
"email_address" => $email,
"status" => "subscribed",
]);
}
catch (\EXCEPTION $e) {
return $e->getMessage();
}
The \EXCEPTION handles a sort of error for stripe
Subscribe is in a namespace Acme\Emails\Subscribe so catch(Mailchimp_Error $e) looks for Mailchimp_Error in this namespace.
Changing it to catch(\Mailchimp_Error $e) makes it look in the root namespace and then it works as intended
I have made a simple PHP script which uploads a file to Google Drive. I then run the following function:
function PublishToWeb($service, $fileId, $revisionId) {
$patchedRevision = new Google_Revision();
$patchedRevision->setPublished(true);
$patchedRevision->setPublishAuto(true);
$patchedRevision->setPublishedOutsideDomain(true);
try {
return $service->revisions->patch($fileId, $revisionId, $patchedRevision);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
I get no error message but the word document is not published.
When I try to set the flags using the Google APIs explorer it returns no errors but also fails to set the published flag to true. Am I missing something obvious?
For clarity I'm trying to upload a file then instantly simulate pressing 'Publish to web'. I also tried using revisions.update
Update:
Okay, I've figured out that the document has to be uploaded and converted to a google doc format to be published. However when the document is saved as a google doc it has no headrevisionid set so I can't use revisions.update or revisions.patch
Anyone know how to publish a google doc file?
Okay I figured it out.
When uploading the file convert to a google doc
$createdFile = $service->files->insert($file, array(
'data' => $data,
'convert' => 'true',
));
Then update the published flag to true
$revisionId = 1; //The revisionId for a newly created google doc will = 1
function updateRevision($service, $fileId, $revisionId) {
$patchedRevision = new Google_Revision();
$patchedRevision->setPublished(true);
$patchedRevision->setPublishAuto(true);
$patchedRevision->setPublishedOutsideDomain(true);
try {
return $service->revisions->patch($fileId, $revisionId, $patchedRevision);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
Then build the publishedlink as this isn't done for you
$PublishURL = 'https://docs.google.com/document/d/'.$fileId.'/pub';