Copy file with Permissions in Google Drive API PHP - php

I'm trying to copy a file with a service account, and then grant access to my personal account. The copy seems to be working correctly which it seems to be copying the file to the google drive service account. So it's returning and ID that was created, but it fails when trying to insert the permissions on the file. says undefined method insert.
Here's what I have now
private function copy_base_file( $new_file_name )
{
$service = $this->get_google_service_drive( $this->get_google_client() );
$origin_file_id = "{id of file to copy}";
$copiedFile = new Google_Service_Drive_DriveFile();
$copiedFile->setName($new_file_name);
try {
$response = $service->files->copy($origin_file_id, $copiedFile);
$ownerPermission = new Google_Service_Drive_Permission();
$ownerPermission->setEmailAddress("{myemailhere}");
$ownerPermission->setType('user');
$ownerPermission->setRole('owner');
$service->permissions->insert("{sheet_id_here}", $ownerPermission,
['emailMessage' => 'You added a file to ' .
static::$applicationName . ': ' . "Does this work"]);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

The insert method is deprecated in the latest version (V3) of the Google Drive API.
Use the create method instead.
V3 Drive API Permissions Create
private function copy_base_file( $new_file_name )
{
$service = $this->get_google_service_drive( $this->get_google_client() );
$origin_file_id = "{id of file to copy}";
$copiedFile = new Google_Service_Drive_DriveFile();
$copiedFile->setName($new_file_name);
try {
$response = $service->files->copy($origin_file_id, $copiedFile);
$ownerPermission = new Google_Service_Drive_Permission();
$ownerPermission->setEmailAddress("{myemailhere}");
$ownerPermission->setType('user');
$ownerPermission->setRole('owner');
$service->permissions->create("{sheet_id_here}", $ownerPermission,
['emailMessage' => 'You added a file to ' .
static::$applicationName . ': ' . "Does this work"]);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

Related

How to delete a file in a google drive shared drive folder using php?

All I need is to delete a file which is inside my shared drive folder using google/apiclient using php , this is my code below .
session_start();
require __DIR__ . '/vendor/autoload.php'; // ready the API to upload to drive
use Google\Client;
use Google\Service\Drive;
if (isset($_POST['file'])) {
$file = $_POST['file'];
$client = new Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=./credentials.json');
$client->useApplicationDefaultCredentials();
$client->addScope(Drive::DRIVE);
$driveService = new Drive($client);
$delete = $driveService->files->delete($file);
if ($delete) {
$_SESSION['success'] = "Video deleted successfully";
header("Location: upload");
}
}
If your client has permission for deleting the file from the shared Drive, how about the following modification?
From:
$delete = $driveService->files->delete($file);
To:
$fileId = "###"; // Please set the file ID of the file you want to delete.
try {
$driveService->files->delete($fileId, array('supportsAllDrives' => true));
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
In this case, when the file is deleted, no value is returned. Please be careful about this.
Note:
When I tested this script, I confirmed that a file in a shared Drive could be deleted. But, if an error occurs, please confirm the permission of your client, again.
Reference:
Files: delete

How do i exit when error from new CallbackFilterIterator

I'm trying to get the files in a directory in my filesystem. Did some research here and found the necessary info to create the following piece of code that works perfectly!
define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define(FILM_IMG_UPLOAD_DIR, DOCUMENT_ROOT . '/filmography/img/films/');
$files = new filesystemiterator(FILM_IMG_UPLOAD_DIR, FilesystemIterator::SKIP_DOTS);
$filter_files = new CallbackFilterIterator($files, function($cur, $key, $iter) {
return $cur->isFile();
});
$num_files = iterator_count($filter_files);
...
The problem is when the directory does NOT exist, i get the error
Fatal error: Uncaught exception 'UnexpectedValueException' with
message
'FilesystemIterator::__construct(C:/public_html/filmography/img/films/,C:/public_html/filmography/img/films/)...
So, how do I exit the code when i get an error from new CallbackFilterIterator ?
Looks to me like you need to wrap the code in a try-catch block.
define('DOCUMENT_ROOT', '/usr/local/share');
define('FILM_IMG_UPLOAD_DIR', DOCUMENT_ROOT . '/film/');
try {
$files = new filesystemiterator(FILM_IMG_UPLOAD_DIR, FilesystemIterator::SKIP_DOTS);
$filter_files = new CallbackFilterIterator($files, function($cur, $key, $iter) {
return $cur->isFile();
});
$num_files = iterator_count($filter_files);
}
catch(UnexpectedValueException $e) {
echo "App Exception: " . $e->getMessage() . "\n";
}

PHPUnit testing ExpectedException not throwing exception

Using Laravel framework with phpunit for unit tests.
I am working with a function that requires directories to be created for a file to be written to it, in short, the function gets data, write it to a temp file and moves the temp file once done.
public function getDataAndStoreToCSVFile() {
Log::info(date('Y-m-d H:i:s') . " -> " . __FILE__ . "::" . __FUNCTION__);
try {
// make sure directories exist
if (!Storage::has($this->temporary_directory) || !Storage::has($this->storage_directory)) {
$this->createDirectories();
}
// get full path of storage disk for files
$diskPath = Storage::getAdapter()->getPathPrefix();
// create a complete path to temporary file to allow tempnam to find the directory
$full_temporary_file_path = $diskPath.$this->temporary_directory;
// fetch stations, station networks and station params seperated by double new line,
// will return FALSE if something is missing and file will not be created and not written to
if($stations_data_array = $this->getCompleteStationsDataArray("\n\n")){
// create temporary file
$temporary_file = tempnam($full_temporary_file_path,'') ;
// if both $temporary_file and $stations_data_array exist write entries to file one at a time in CSV format
if (file_exists($temporary_file)) {
$fp = fopen($temporary_file, 'a');
foreach ($stations_data_array as $fields) {
if (is_object($fields) || is_array($fields)) {
// $fields is an array
$fields = (array)$fields;
fputcsv($fp, $fields);
} else {
// $fields is the separator
fwrite($fp, $fields);
}
}
// done writing, close file
fclose($fp);
// create new permanent name for $temporary_file in the storage directory "full_disk_path.storage_path.yyyymmddhhmmss.timestamp"
$storage_file = $diskPath . $this->storage_directory . "/" . date('YmdHis') . "." . time();
// rename $temporary_file to $storage_file
if (!rename($temporary_file, $storage_file)) {
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Failed to move temporary file from " . $this->temporary_directory . " to " . $this->storage_directory);
}
} else{
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Temporary file was not available or does not exist.");
}
} else {
Log::error(__FILE__ . "::" . __FUNCTION__ . " : Temporary file was not created.");
}
} catch (\ErrorException $e) {
// Catches missing directory or file, or tempnam couldn't find temporary storage path //Todo add test for this exception
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
} catch (\Exception $e) {
// Catches uncaught exceptions
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
}
}
To test if ErrorException is thrown when directories are missing, this test :
public function test_getDataAndStoreToCSVFile_handles_ErrorException() {
// set up data
$this->setup_all_data_for_getDataAndStoreToCsvFile_funtion();
// mock class
$mock = $this->getMockBuilder('App\Interfaces\Sources\IdbStationSourceInterface')
// stub function createDirectories, will now return null and not create directories, missing directories will throw ErrorException
->setMethods(['createDirectories'])
->getMock();
// expect the ErrorException to be thrown
$this->expectException('ErrorException');
// run function
$mock->getDataAndStoreToCSVFile();
}
When I run the test, my logs indicate that I fell into :
} catch (\ErrorException $e) {
// Catches missing directory or file, or tempnam couldn't find temporary storage path //Todo add test for this exception
Log::error(__FILE__ . "::" . __FUNCTION__ . " : " . $e->getMessage());
}
But my terminal says :
1) Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::test_getDataAndStoreToCSVFile_handles_ErrorException
Failed asserting that exception of type "ErrorException" is thrown.
I have no clue where to go from there, I read and tried a couple of things but clearly I'm doing something wrong.
Edit 1 :
Tried : $this->setExpectedException("ErrorException");
But I get the following :
1) Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::test_getDataAndStoreToCSVFile_handles_ErrorException
Error: Call to undefined method Tests\Interfaces\Sources\IdbStationSourceInterfaceTest::setExpectedException()
Thats because you catched the exception. PHPUnits expectedException-method only registers unhandled or rethrown exceptions. Either rethrow the exception in your catch-block or just test for the log-entry you are creating in the catch-block.
from function getDataAndStoreToCSVFile() you just throw error with error code and message. Then you can use these assertion in test case.
/**
*#expectedException ExampleException
*#expectedExceptionCode ExampleException::EceptionCode
*/
public function test_getDataAndStoreToCSVFile_handles_ErrorException() {}

Warning: file_put_contents : failed to open stream: No such file or directory

I am working with facebook graph api, in my code i want to store a user profile image url in my database & the image store in my database file, it can find the source file also show it but it can't store image my database. The error says that:
file_put_contents(celebrity_u_look_alike/youtube_star/fb_user_image/img_1264053943663652.png): failed to open stream: No such file or directory in /home/smartcarsassocia/public_html/celebrity_u_look_alike/youtube_star/youtube_star.php on line 101
My source code shown below :
try {
$requestPicture = $fb->get('/me/picture?redirect=false&height=250&width=250'); //getting user picture
$requestProfile = $fb->get('/me'); // getting basic info
$picture = $requestPicture->getGraphUser();
$profile = $requestProfile->getGraphUser();
$url= $picture['url'];
echo $url;
$filename = 'img_' . $profile_data['id'] . '.png';
echo $filename;
$path1 = "celebrity_u_look_alike/youtube_star/fb_user_image/" . basename($filename);
$image_file = file_get_contents($url);
file_put_contents($path1, $image_file );
//file_put_contents($path2, file_get_contents($url));
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
This is because:
file_put_contents($path1, $image_file );
the path you have provided in $path1 doesn't exist physically. So make sure the directory exist. If not, then create it using mkdir() function.

Symfony2: How to move file from tmp directory to definitve position

I'm on a Mac and I'm trying to create an image in the PHP tmp directory, and then move it to its definitive location.
This is the code I'm using:
public function download()
{
// Get the remote file extension
$remoteImageExtension = explode('.', $this->getRemoteUri()->getPath());
$remoteImageExtension = array_pop($remoteImageExtension);
$fs = new Filesystem();
$tempImage = tempnam(sys_get_temp_dir(), 'image.') . '.' . $remoteImageExtension;
/** #todo: Refact: Pass this as constructor parameter so it will be possible to unit test it */
$client = new Client();
// Get and save file
$client->get($this->getRemoteUri(), ['save_to' => $tempImage]);
$tempImage = new File($tempImage);
try {
if ($fs->exists($tempImage))
{
die('Temporary file exists');
$fs->copy($tempImage, $this->getDownloadRootDir() . $this->getName() . '.' . $remoteImageExtension);
} else {
die('Temporary file doesn\'t exist');
}
} catch (\Exception $e)
{
die($e->getMessage());
}
// die(print_r($tempImage));
// Move the file to its definitive location
//die($this->getDownloadRootDir() . ' | ' . $this->getName());
/*try {
$tempImage->move(
$this->getDownloadRootDir(),
$this->getName() . '.' . $remoteImageExtension
);
} catch (FileException $e)
{
echo $e->getMessage();
}*/
// set the path property to the filename where you've saved the file
$this->path = $this->getName();
}
As you can see I've put some die() in the code to print some information during the execution.
Doing this, I know the temporary file is correctly created, but it isn't moved to its new location.
I've read around that it could be a problem of permissions on destination folder, but, changing them with returns me an error about an illegal user (I'm on a Mac!):
$ chown -R www-data /Users/Aerendir/Documents/JooServer/_Projects/path/to/symfony_project/web/images/path/to/destination_folder
chown: www-data: illegal user name
I have tried both the Filesystem::copy() and the File::move() methods (as you can see from the source code provided), but the file isn't moved.
Any ideas about how to solve this?
UPDATE
Trying to know which is my current Apache user I see it is correctly set to my main system user (Aerendir).

Categories