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));
Related
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);
}
}
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.
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.
I'm managing an MVC3 app where I need to support the ability of 3rd parties to create link to assets within my domain. Because some of the links are sliced and diced by mail merges and other text editing problems, URLs with typos have been introduced, e.g.:
/Content/ima!+ges/email/spacer.gif
or
/Content/image++s/email+/spacer.gif
I'd like to strip these extraneous characters by RegEx before attempting to serve them. I _think this is something a Route method could accomplish and I'd welcome a pointer or two to articles that demonstrate this approach.
ADDENDUM (cuz I need the formatting):
Implementing #Nathan's routing I'm unable to send the filename to the controller handler - it's always seeing a null value passed in. I've tried both 'filepath' and 'path' with the same 'null' result.
routes.MapRoute(
"MangledFilename",
"{*filepath}",
new { controller = "MangledFilename", action = "ServeFile" }
);
I think this is a matter of configuring wildcard handling on IISExpress and am looking for that solution separately. The more serious immediate problem is how your suggestion returns the HttpNotFound - i'm getting a hard IIS exception (execution halts with a YellowScreenDeath) instead of the silent 404 result.
public ActionResult ServeFile(string filePath)
{
if (filePath != null) // workaround the null
{
...
}
return HttpNotFound();
}
thx
I think something along this approach should work:
First add a route like this to the end of your route registering declarations:
routes.MapRoute(
"MangledFilename",
"{*filepath}",
new { controller = "MangledFilename", action = "ServeFile" });
If you haven't seen them before, a route parameter with an * after the opening { is a wildcard parameter, in this case it will match the entire path. You could also write it like content/{*filepath} if you wanted to restrict this behavior to your content directory.
And then a controller something like this should do the trick:
public class MangledFilenameController : Controller
{
public ActionResult ServeFile(string filePath)
{
filePath = CleanFilePath(filePath);
var absolutePath = Server.MapPath(filePath);
if (System.IO.File.Exists(absolutePath))
{
var extension = System.IO.Path.GetExtension(absolutePath);
var contentType = GetContentTypeForExtenion(extension);
return File(absolutePath, contentType);
}
return HttpNotFound();
}
private string CleanFilePath(string filepath)
{
//clean the path up
return filepath;
}
private string GetContentTypeForExtenion(string extension)
{
//you will want code here to map extensions to content types
return "image/gif";
}
}
In regards to mapping an extension to a MIME / content type for the GetContentTypeForExtension method, you could choose to hard code types you are expecting to serve, or use one of the solutions detailed in this post:
File extensions and MIME Types in .NET
EDIT:
After thinking about it, I realized there's another way you can handle the ServeFile action. Redirecting to the existing file could be simpler. I'm leaving the original method I wrote above and adding the alternative one here:
public ActionResult ServeFile(string filePath)
{
filePath = CleanFilePath(filePath);
var absolutePath = Server.MapPath(filePath);
if (System.IO.File.Exists(absolutePath))
{
return RedirectPermanent(filePath);
}
return HttpNotFound();
}
I believe #Nathan Anderson provided a good answer but it seems incomplete.
If you want to correct the typos and the types are as simple as those you mentioned then you can use Nathan code but before trying to find the file, you remove any plus or exclamation point characters in the path and you can do it like this:
String sourcestring = "source string to match with pattern";
String matchpattern = #"[+!]";
String replacementpattern = #"";
Console.WriteLine(Regex.Replace(sourcestring,matchpattern,replacementpattern));
Generated this code from the My Regex Tester tool.
This is the code you need. This code also removes any + character from the filename. If you don't want that behavior, you may select a substring without the filename and only replace + and ! characters before the filename.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this error mean in PHP?
I am having an issue with the following section of code:
I can get the error notices in the validation but the next step = valid code I just get a white page, Any Ideas?
I have checked the error settings and I have set it in the public_html php.ini file and I still don't get errors
function create_sale()
{
$this->template->append_metadata( js('debounce.js', 'sales') );
$this->template->append_metadata( js('new_sale.js', 'sales') );
// -------------------------------------
// Validation & Setup
// -------------------------------------
$this->load->library('form_validation');
$this->sale_rules[1]['rules'] .= '|callback__check_slug[insert]';
$this->form_validation->set_rules( $this->sale_rules );
foreach($this->sale_rules as $key => $rule)
{
$sale->{$rule['field']} = $this->input->post($rule['field'], TRUE);
}
// -------------------------------------
// Process Data
// -------------------------------------
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) ):
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
}
else:
{
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
endif;
redirect('admin/sales');
}
$this->template->set('sale', $sale)
->build('admin/new');
}
You said that your code is valid but you get a white page.
Most of the time when you get a white page you will simply have an error in your code.
As is the case here:
You suddenly have an endif; in your code which you don't want there.
Enable error reporting please:
Include this code in your bootstrap file:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Remember to disable this in production!
To remove the error change:
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) ):
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
}
else:
{
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
endif;
redirect('admin/sales');
}
to:
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) )
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
} else {
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
redirect('admin/sales');
}
You have too many closing curly braces, remove the 'endif' in your script and it should work.
CodeIgniter is notorious for the "white screen of death".
Generally when I've run into it, it's been because of the way they set up their database error handling (it's not good). Database errors aren't handled when $db['default']['db_debug'] is set to FALSE. Any query or connection attempt that fails just returns false. Execution continues after a bad query, which can result in a white screen of death. If you're lucky, you'll get an error message in the logs in some cases, but in most you won't, as the query() function just silently returns false without logging anything.
If you set it to TRUE, then you can be in an even worse position, because any database error will automatically result in CodeIgniter calling it's own show_error() function and generating a 500 HTTP response, and you have no chance of handling it on your own.
This is the most common way to get the WSOD that I'm aware of. I haven't used the 2.0 versions of CI, but it was the case in the 1.7 versions. You may want to try setting db_debug to true in your database.php config file until you find out what's going on.
I suspect that your redirect() is failing to redirect (instead just leaving a blank page sans redirect) for some reason or another. Toss a debug message before it to check.