Laravel Model Event: delete() doesn't delete files fromstorage - laravel

I am using FilePond for the image upload. It generates random strings for the images uploaded and is saved in database as Array.
I tried to do the following, it deletes the record but doesn't delete the files associated with it.
Since it's an array, I tried this:
foreach($this->attachments as $attachment) {
if(File::exists(storage_path($attachment))) {
Storage::delete($attachment);
}
}
Also tried this:
if(Storage::exists($this->attachments))
{
Storage::delete($this->attachments);
}
Note:
I am using Filament as the admin dashboard.
The files are being saved at storage/app/public/vehicle-images
I did php artisan storage:link, so the public folder shows ``public/storage/vehicle-images```

In this example, the file exists in: Laravel/storage/app/public/vehicle-images
$filename = 'test.txt';
if(\File::exists(storage_path('app/public/vehicle-images/'.$filename))){
\File::delete(storage_path('app/public/vehicle-images/'.$filename));
}
To better understand where the files are, and after that you can simply foreach loop check/delete.
You can read more on this here: https://laravel.com/docs/9.x/filesystem#the-public-disk
You can also later on specify a disk for that folder to make things easier to access.
Finally:
foreach($this->attachments as $attachment) {
//Option #1: if $attachment == file.txt
//use this code:
if(\File::exists(storage_path('app/public/vehicle-images/'.$attachment))){
\File::delete(storage_path('app/public/vehicle-images/'.$attachment));
}
//Option #2: if $attachment == vehicle-images/file.txt
//use this code:
if(\File::exists(storage_path('app/public/'.$attachment))){
\File::delete(storage_path('app/public/'.$attachment));
}
}
If you can show me how the filePond array looks like, I can adjust the code to work with it.

I got it. FilePond doesn't only store the image name, it also stores the url/folder the image was saved in. So instead of image.png, it is vehicle-images/image.png.
The code should be:
File::exists('storage/' . $attachment)
Which will read as: storage/ + vehicle-images/image.png.
Working code block:
foreach ($this->attachments as $attachment) {
if (File::exists('storage/' . $attachment)) {
File::delete('storage/' . $attachment);
}
}

Related

qml qt grabToImage get image bytes

For some reason, saving a png back out from qml directly doesn't work. I have a qml UI on top of a Golang application. When I do
source.grabToImage(function(result){
console.log("image: ", result.url)
if (!result.saveToFile(urlNoProtocol)){
console.error('Unknown error saving to',urlNoProtocol);
} else {
console.log("saved to " + urlNoProtocol)
}
I get an error saving out. The location to save the file is coming from a fileDialog and I preprocess it to remove the file:// which I understand needs to be removed before using saveToFile. However I get an unknown error saving from the above code.
I suspect this is something to do with the qml being embedded in the binary application (perhaps to do with qrc:// or something)
Anyway my current plan is to send the image to the golang backend and save it out from there, so my question is, how from grabToImage or saveToFile can I get the image bytes that I will then save?
N.B Using therecipe/qt for the interface between Golang and qml
I have used this method for grabbing screen shots..
function performScreenShot(item, name) {
if(typeof(item) === "undefined") {
return;
}
else if(typeof(name) !== "string") {
name = "screenshot.png"
}
item.grabToImage(function(result) {
result.saveToFile(name);
});
}
Usage example:-
performScreenShot(main, "screenshot-" + screenShotIndex + ".png")
Where main is my object id and screenShotIndex is something im incrementing so as not to override any previous capture.
Ensure that you have write permission on the device.

Exclude Folder with Laravel File::allFiles

I am currently using the following function:
public function recentImages(){
foreach(\File::allFiles("up") as $path){
$files[] = pathinfo($path);
}
return view('recent-images-view')->with('files',$files);
}
To list all images in my upload folder, however this also include the thumbnails that are separated in a separated folder called "thumbs".
I was wondering if there's any way to tell the allFiles function to exclude the folders with the name thumbs. Or should I handle this completely differently?
Thanks for any information in advance.
File::allFiles() will get all of the files from the given directory recursively. Try using File::files() which will get all files from the given directory only.
Update
Since you have other directories which you need. I came up with following solution.
public function images(){
foreach(\File::directories('up') as $dir) { // Get all the directories
if(str_contains('thumbs', $dir)) { // Ignore thumbs directory
continue;
}
foreach(\File::files($dir) as $path) { // Get all the files in each directory
$files[] = pathinfo($path);
}
}
return view('recent-images-view')->with('files',$files);
}
Didn't test it, the concept is get all the directories and get all the files inside those directory by ignoring the unwanted directory.

elFinder not showing Folder or File with umlaute

i encountered a problem with elFinder.
When on the server there is a file or a folder containing one of the letters öäü, the directory(file) wont be shown in el finder and i get an error in
lFinderConnector.class.php json_encode(): Invalid UTF-8 sequence in
argument
but if i upload a file with elFinder itself like: Test ö.png its shown correctly and on the server it looks like this: Test ö.png. Same goes for directorys.
My problem is i have a millions of files that may countain umlaute (ö,ü ,ä) and elFinder cant show them.
Does any one else got problem like this or got any idea or tip how to solwe it?
setlocale(LC_ALL, 'de_DE');
function array_walk_deep(&$items){
foreach ($items as &$item) {
if(is_array($item)) {
array_walk_deep($item);
} else {
if (!strpos($item ,'ö')) {
$item = iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($item)) ;
}
}
}
}
array_walk_deep($data);
so i just made a workaround on this. In the elFinderConnector i just use this piece of code before i return the array to javascript this will change the ö->oe the ä->ae and the ü-> ue will no longer cause any problems and the directorys will be shown. Directory and files can be renamed afterward by the users.
Hope some one will finde this usefull.
regrads
Your solution replaces the umlauts by ASCII chars, for me it worked by just using utf8_encode() on the items of $data array before json_encode() and outputting it (it keeps the umlauts).
I took your snippet, modified it and added it to the elFinderConnector class.
protected function array_walk_deep(&$items){
foreach ($items as &$item) {
if(is_array($item)) {
$this->array_walk_deep($item);
} else {
$item = utf8_encode($item);
}
}
Then call it on the $data array in the output() method.
$this->array_walk_deep($data);
exit(json_encode($data));

In Symfony 2, is there a good way to interact with the app/cache cache using read() and write() methods?

I want to save data to Symfony's file cache. Is there a good way to interact with the app/cache cache using read() and write() methods?
EDIT
The excellent winzou CacheBundle was exactly what I needed.
You can do it from the controller:
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;
//Define your file path based on the cache one
$filename = $this->container->getParameter('kernel.cache_dir') . '/yourapp/filename.txt';
//Create your own folder in the cache directory
$fs = new Filesystem();
try {
$fs->mkdir(dirname($filename));
} catch (IOException $e) {
echo "An error occured while creating your directory";
}
//Write your file
file_put_contents($filename, 'Text content');
//Read the content of your file
echo file_get_contents($filename);
Note that DoctrineCacheBundle is now recommended. Don't be misled by the Doctrine branding - this is distinct and separate from the ORM and DBAL etc.
Not really sure what you're trying to achieve but you'd have a look at the config component documentation, and specifically at the ConfigCache class:
http://symfony.com/doc/current/components/config/index.html
http://symfony.com/doc/current/components/config/caching.html

Magento: ImageCdn bug? (long story)

I have some question related with Magento's free extension OnePica ImageCdn.
A broken image appear in frontend when I uploaded "corrupt image".
Ok, let's start the long story:
I notice it is happened because of ImageCdn extension and "corrupt image".
In some part of ImageCdn's code:
OnePica_ImageCdn_Helper_Image
/**
* In older versions of Magento (<1.1.3) this method was used to get an image URL.
* However, 1.1.3 now uses the getUrl() method in the product > image model. This code
* was added for backwards compatibility.
*
* #return string
*/
public function __toString()
{
parent::__toString();
return $this->_getModel()->getUrl();
}
My question is, anybody know what is the purpose of that code?
I don't understand what is the meaning of their comment above.
I think it is a bug as it always return $this->_getModel()->getUrl();
Is is really a bug or it is just my wrong interpretation?
This is what I've done so far:
I have an image dummy.jpeg
After some investigation, I just realized that is a "corrupt image".
I tested using: <?php print_r(getimagesize('dummy.jpeg')); ?>
Result:
Array
(
[0] => 200
[1] => 200
[2] => 6
[3] => width="200" height="200"
[bits] => 24
[mime] => image/x-ms-bmp
)
Of course I was surprised by the result because it looks good when I open it using Preview (on Mac OSX)
Then I open it using hex editor, the first two bytes is : BM which is BMP's identifier
I tried to upload .bmp image for product -> failed, can not select the image
I asked my colleague to upload it too (on Ubuntu), he was able to change the choices for file type into "any files". When he click "Upload Files", error message shown state that that type of file is not allowed.
What crossed on my mind is: an admin tried to upload .bmp image and failed. Then he rename it into .jpeg and successful. Though I don't get it what kind of images can be renamed without showing broken image logo (out of topic).
Those scenarios trigger an Exception, I'll break down what I've traced.
Trace of the codes:
app/design/frontend/base/default/catalog/product/view/media.phtml
<?php
$_img = '<img id="image" src="'.$this->helper('catalog/image')->init($_product, 'image').'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
From that code, I know that image url is generated using: $this->helper('catalog/image')->init($_product, 'image')
I did Mage::log((string)$this->helper('catalog/image')->init($_product, 'image'));
Result:
http://local.m.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/d/u/dummy.jpeg
.
Mage_Catalog_Helper_Image
public function __toString()
{
try {
if( $this->getImageFile() ) {
$this->_getModel()->setBaseFile( $this->getImageFile() );
} else {
$this->_getModel()->setBaseFile( $this->getProduct()->getData($this->_getModel()->getDestinationSubdir()) );
}
if( $this->_getModel()->isCached() ) {
return $this->_getModel()->getUrl();
} else {
if( $this->_scheduleRotate ) {
$this->_getModel()->rotate( $this->getAngle() );
}
if ($this->_scheduleResize) {
$this->_getModel()->resize();
}
if( $this->getWatermark() ) {
$this->_getModel()->setWatermark($this->getWatermark());
}
Mage::log('pass');
$url = $this->_getModel()->saveFile()->getUrl();
Mage::log('not pass');
}
} catch( Exception $e ) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
return $url;
}
The error triggered in $this->_getModel()->saveFile()->getUrl(). In some part of the code, it will eventually reach:
Varien_Image_Adapter_Gd2
private function _getCallback($callbackType, $fileType = null, $unsupportedText = 'Unsupported image format.')
{
if (null === $fileType) {
$fileType = $this->_fileType;
}
if (empty(self::$_callbacks[$fileType])) {
//reach this line -> exception thrown
throw new Exception($unsupportedText);
}
if (empty(self::$_callbacks[$fileType][$callbackType])) {
throw new Exception('Callback not found.');
}
return self::$_callbacks[$fileType][$callbackType];
}
The exception was catched in the previous code:
Mage_Catalog_Helper_Image
public function __toString()
{
...
} catch( Exception $e ) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
...
}
the $url became:
http://local.m.com/skin/frontend/default/default/images/catalog/product/placeholder/image.jpg
So, it should have generated placeholder image right?
(without ImageCdn extension)
No, because
Mage_Catalog_Helper_Image was rewritten by
OnePica_ImageCdn_Helper_Image
public function __toString()
{
parent::__toString(); //the result is http://local.m.com/skin/frontend/default/default/images/catalog/product/placeholder/image.jpg but no variable store/process its value
return $this->_getModel()->getUrl(); //in the end it will return http://local.m.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/d/u/dummy.jpeg
}
In case you all already forgot the question:
Anybody know what is the purpose of that code? I don't understand what is the meaning of their comment above.
Is it really a bug or it is just my wrong interpretation?
No it isn't a bug. It's just legacy support for older Magento systems. I'm wondering, have you ever got around to snoop around earlier versions of magento (as the inline documentation comment references to, < 1.1.3)?
The gist of the matter is before Mage 1.1.3, Mage_Catalog_Helper_Image instances happen to produce URL's from to-string casts e.g.
$image = (some instance of Mage_Catalog_Helper_Image).. ;
$imageUrl = (string) $image;
__toString is probably either protected or private, i'm not sure but what I'm sure is the usual practice is to always code up this Magic Method in order to use it in a class that you are meaning to rewrite something with that expects to use this kind data cast.

Resources