Google drive api folder permissions - google-api

I have problem with google drive api v3.
I took google example and I tried. I could read folder content but I did nothing with folder permission.
I received error 403, "Insufficient Permission".
I can't create or read all permissions for the folder.
<?php
require_once __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE);
$client->setAccessType('offline');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$drive = new Google_Service_Drive($client);
$folderId = '1_ip3-WUs4F6atNdElJ3KHccAV4lI0nLL';
$optParams = array(
'pageSize' => 100,
'fields' => "nextPageToken, files(id,name)",
'q' => "'".$folderId."' in parents"
);
$results = $drive->files->listFiles($optParams);
if (count($results->getFiles()) != 0) {
foreach ($results->getFiles() as $file) {
echo "Id: " . $file->getId() . " Name: " . $file->getName() . "<br>";
}
}
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
//+!+!+!+!+!+!+!+!+!+! Next code doesn't WORK !+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!//
$fileId = '1UXSg5W-XIX82izGK8uEXXWPUCLcDGRa1';
$userPermission = new Google_Service_Drive_Permission(array(
'type' => 'user',
'role' => 'reader',
'emailAddress' => 'email#gmail.com'
));
$request = $drive->permissions->create($fileId, $userPermission, array('fields' => 'id'));
echo $request;
?>

It may be that wrong permissions have been set when creating the folder, even though you said you did nothing. I do not see the code for creating the folder here, just an ID, which indicates that the folder has already been created.
I suggest trying to list the permissions using Drive.Permissions.List first. Particularly, look at the type and role or teamDrivePermissionDetails[].role properties. See the permissions guide on what operations each role or type can do. You can also visit this documentation on managing sharing in case you need to.

Related

How to attach file with api request in laravel store controller?

Here is my controller
I would like to attach a file that was requested from Postman API, please help me to solve my problem.
$p = new PersonAskPermission();
$p->start = $request->start;
$p->end = $request->end;
$p->day = $request->day;
$p->person_id = $request->person_id;
$fileTemp = $request->file('file');
$fileExtension = $fileTemp->getClientOriginalExtension();
$fileName = Str::random(4). '.'. $fileExtension;
$path = $fileTemp->storeAs(
'apiDocs', $fileName
);
$p->getTypes()->attach($p_type);
$p->getReasons()->attach($p_reason);
return response()->json([
'message' => 'Permission Reason created successfully!',
'data' => $p
]);
}

Function wp_generate_attachment_metadata returns always empty array in ajax function

I have searched far and wide, but have not found a solution.
I have a real estate ad insertion form, I need to be able to upload photos of the listings. I can upload the photos to the server via ajax, return the filenames in a textarea and always via ajax, after submitting the form, I can upload the photos to wordpress and attach them to the ad
The only problem is that it does not generate the photo metadata, wp_generate_attachment_metadata always returns an empty array.
I can't find a solution about it. I have another plugin with a similar form, but there I post the form not via ajax, but with the action = "post", and I can safely generate the metadata.
This is the code with which I insert the attachments and link them to the newly created post.
Hope someone can help me
//$filename = domoria-torino-strada-della-fornace-druento-15.jpg
if ($filename != '') {
$wp_upload_dir = wp_upload_dir();
$filename_path = $wp_upload_dir['path'] .'/'. $filename;
$filename_url = $wp_upload_dir['url'] .'/'. $filename;
$guid = $wp_upload_dir['url'] . '/' . basename( $filename_path );
$attachment = array(
'guid'=> $guid,
'post_mime_type' => 'image/jpeg',
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post_id
);
$attach_id = wp_insert_attachment( $attachment, $filename_path);
if($iter === 0){
set_post_thumbnail( $post_id, $attach_id );
}
$ids [] = $attach_id; //this array needs for an ACF field
//filename_path = home/uxo80ef6/domains/homeprime.sviluppo.host/public_html/wp-content/uploads/2021/12/domoria-torino-strada-della-fornace-druento-15.jpg
//$attach_id = 629
$file_uploaded_path = get_attached_file($attach_id);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_uploaded_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
$iter++;
}
UPDATE: The problem is due to getimagesize called by wp_generate_attachment_metadata that can't find the file by file_path, however the file is on the server.
I rewrote some parts of the code you posted:
change hardcoded post_mime_type with wp_check_filetype() instead.
rename some of the variables to: $file_name, $file_path, $parent_post_id
removed unused $filename_url
added $parent_post_id as the third argument into wp_insert_attachment()
removed get_attached_file() function and used $file_path for wp_generate_attachment_metadata()
<?php
// $file_name = domoria-torino-strada-della-fornace-druento-15.jpg
if (!empty($file_name)) {
// The ID of the post this attachment is for.
// eg. $parent_post_id = 37;
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
$file_path = $wp_upload_dir['path'] . '/' . $file_name;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype(basename($file_path), null);
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($file_path),
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_title($file_name),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment($attachment, $file_path, $parent_post_id);
// Set the first attachment as Featured image.
if ($iter === 0) {
set_post_thumbnail($parent_post_id, $attach_id);
}
// ACF field array data.
$ids[] = $attach_id;
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
$iter++;
}

How can i change the image upload directory and view image url in laravel

In my script all images uploaded goes into directory "ib" but i want to change that directory to a different name eg. "imgib"
here is what i did so far. i changed the code vlues from "ib" to "imgib"
} else {
// upload path
$path = 'imgib/';
// if path not exists create it
if (!File::exists($path)) {
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
}
// move image to path
$upload = $request->file('uploads')->move($path, $imageName);
// file name
$filename = url($path) . '/' . $imageName;
// method server host
$method = 1;
}
// if image uploded
if ($upload) {
// if user auth get user id
if (Auth::user()) {$userID = Auth::user()->id;} else { $userID = null;}
// create new image data
$data = Image::create([
'user_id' => $userID,
'image_id' => $string,
'image_path' => $filename,
'image_size' => $fileSize,
'method' => $method,
]);
// if image data created
if ($data) {
// success array
$response = array(
'type' => 'success',
'msg' => 'success',
'data' => array('id' => $string),
);
// success response
return response()->json($response);
} else {
if (file_exists('imgib/' . $filename)) {$delete = File::delete('imgib/' . $filename);}
// error response
return response()->json(array(
'type' => 'error',
'errors' => 'Opps !! Error please refresh page and try again.',
));
}
so far everything looks ok and it creates "imgib" directory automatically and all uploads go into "imgib" directory.
But the issue is, image url still uses the same old directory name.
eg. site.org/ib/78huOP09vv
How to make it get the correct url eg. site.org/imgib/78huOP09vv
Thanks for the help everyone. I managed to fix the issue by editing viewimage.blade.php
Yes of course need to clear the browser cache after editing the files.

Laravel Homestead Development: AJAX POST request gets redirected for unknown reason

I'm on Laravel 5.3 and I was working on a form I POST submit to the server. What I want to point out right at the beginning is that I have been working on this form for days, with no issues what so ever. Yesterday I was working in the store method of my controller, when all of a sudden the form won't submit at all anymore.
The opening form:
{!! Form::model($addon = new \App\Addon, ['name' => 'FinalForm', 'route' => 'addons.store', 'enctype' => 'multipart/form-data']) !!}
My route:
Route::resource('addons', 'AddonController');
php artisan route:list:
Method: POST
URI: addons
Name: addons.store
Action: App\Http\Controllers\AddonController#store
Middleware: web,auth
So what happens now is, the form gets posted, but then, for some reason, get's redirected. This is what chrome says:
POST request to /addons
And after that, for some reason, GET request to /addons/
As you can see I'm getting a 403 Forbidden response. Why is the request being redicted to /addons/ ??
As I said before, I changed NOTHING, I was working with the inner logic of the store method on the controller when this popped up. I even restarted the homestead box (and my whole machine), I don't know what is causing it.
EDIT (controller):
/**
* Store the addon.
*
* #return Response
**/
public function store(CreateAddonRequest $request, ImageHandler $imageHandler)
{
$input = $request->only('title', 'body', 'author', 'slogan', 'version', 'revision', 'published_at', '_img_data');
$session = $request->session()->all();
$slug = SlugService::createSlug(Addon::class, 'title', $input['title'], ['unique' => true]);
$imageHandler->move($slug, $input['body'], 'description');
$body = $imageHandler->body;
$addon = Auth::user()->addons()->create([
'body' => $body,
'title' => $input['title'],
'slogan' => $input['slogan'],
'author' => $input['author'],
'locales' => $session['locales'],
'published_at' => $input['published_at']
]);
$addon->categories()->attach($request->input('categories'));
Storage::makeDirectory('addons/' . $slug . '/files/');
$extension = Dir::extension('temp/' . $session['file_name']);
if ($input['revision'] != "") {
$file = $addon->slug . '-v' . $input['version'] . '-r' . $input['revision'] . '.' . $extension;
} else {
$file = $addon->slug . '-v' . $input['version'] . '.' . $extension;
}
Storage::disk('local')->move('temp/' . $session['file_name'], 'public/addons/' . $addon->slug . '/files/' . $file);
// With 5.4 we don't need that check anymore
if ($input['revision'] == "") {
$input['revision'] = null;
}
$addon->files()->create([
'file_name' => $file,
'hash' => $session['hash'],
'version' => $input['version'],
'revision' => $input['revision'],
'game_version' => $session['interface'],
'virustotal' => $session['virustotal']
]);
dd('done');
// if ($request->hasFile('images'))
// {
// Storage::makeDirectory('addons/' . $slug . '/images/');
// foreach ($request->file('images') as $image)
// {
// $imageName = uniqid() . '.' . $image->getClientOriginalExtension();
// //$image->storeAs('addons/' . $slug . '/images/', $imageName);
// $addon->images()->create(array('image_name' => $imageName));
// }
// }
// flash('The addon has been uploaded.');
// return redirect('addons');
dd('done');
return response()->json([
'success' => true,
'message' => 'Images checked',
]);
}

Lang sub folder detection codeigniter

In my lang load I would like to be able to try and make it so that if type admin then would pick up subfolder in admin and find the controller lang file. Same as what do with the glob.
How would that be possible for language load function?
Unable to load the requested language file:
language/english/admin/*/dashboard_lang.php
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
if ($files) {
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
$this->lang->load('admin/*'. $controller, 'english');
$data['controller_files'][] = array(
'controller' => $controller,
'install' => '',
'installed' => in_array($controller, $controller_files)
);
}
}
You could do something like this if you wanted to load a language file
in a subfolder with the same name as the "controller".
language/english/admin/dashboard/dashboard_lang.php
$controller = '';
$path = FCPATH . 'application/modules/admin/controllers/*/*.php';
$files = glob($path, GLOB_BRACE);
if(!$files || empty($files)){
log_message('error', "Unable to find any matches : $path");
}
foreach($files as $file){
$basename = basename(strtolower($file));
$pathinfo = pathinfo($basename);
$controller = $pathinfo['filename'];
$this->lang->load("admin/$controller/$controller", 'english');
$data['controller_files'][] = array(
'controller' => $controller,
'install' => '',
'installed' => in_array($controller, $controller_files)
);
}

Resources