issue with image validator rules in laravel 4 - html

I have defined this validating rule for a file(image) in laravel 4 .
'image' => 'image|mimes:jpeg,jpg,bmp,png,gif'
And this is my html code:
{{ Form::label('Image of the product') }} {{ Form::file('image') }}
now , I always get 2 errors while uploading an image even If I chose a png, jpg image
The image must be an image.
The image must be a file of type: jpeg, jpg, bmp, png, gif.
this is the update action that includes image upload :
public function update($id)
{
$product = Product::find($id);
$validator = Validator::make($data = Input::all(), Product::$rules);
if($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$old_img = "";
if(isset($data['image']) and !empty($data['image']))
{
$image = Input::file('image');
$filename = time().'-'.$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(468, 249)->save('public/img/products/'.$filename);
$data['image'] = 'img/products/'.$filename;
$old_img = $product->image;
}
$product->update($data);
File::delete('public/'.$old_img);
return Redirect::route('admin.products');
}

Ensure that your form is a multipart one by adding
'files' => 'true'
to the config array.

first add this to your form tag enctype="multipart/form-data"
second in your validation just 'file'=>'required|mimes:jpeg,png,jpg,gif,svg'
validate mimes and remove image

Related

displaying existing images in ngx dropzone

I am using Angular ngx-dropzone to insert images in Mysql and save them on Server. now I need to do preview/edit mode in angular component in the edit mode, I want to show the existing file in the drop box and display the same when uploading drop zone, any ideas? I have the image as a file and its name of it in the database.
You can use the below code for previewing selected images
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f" [removable]="true" (removed)="onRemove(f)">
</ngx-dropzone-image-preview>
If you want to show the label also
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f" [removable]="true" (removed)="onRemove(f)">
<ngx-dropzone-label>{{ f.name }} ({{ f.type }})</ngx-dropzone-label>
</ngx-dropzone-image-preview>
I understand your question.I was facing the same issue.For this, you have
to have a blob response. So if you have a url you have to convert it into a
blob response. I have given an example below
URL: string = `https://fireflysemantics.github.io/i/service-parts-
help/electrocardiogram-36732.png`;
files: File[] = [];
this.loadImage().subscribe(i => {
const myFile = new File([i], this.URL, {
type: i.type,
});
this.files.push(myFile)
})
loadImage(): Observable < Blob > {
return this.http.get(this.URL, {
responseType: "blob"
});
}

Passing down MediaWiki template arguments to custom HTML attributes

Consider a custom MediaWiki extension that adds a new tag named simplified_example with some JavaScript (just calling alert with provided argument for simplicity):
<?php
if ( ! defined( 'MEDIAWIKI' ) ) die();
$wgExtensionFunctions[] = 'registerTags';
$wgExtensionCredits['parserhook'][] = array(
'name' => 'myTags',
);
function registerTags() {
global $wgParser;
$wgParser->setHook('simplified_example', function ($input, $argv, $parser, $frame) {
$output = $parser->recursiveTagParse($input, $frame);
$title = $argv["value"];
return "<div onclick=\"alert('$title')\">$output</div>";
});
}
?>
Using that I can put following code in a MediaWiki page source:
<simplified_example value="Testing">...</simplified_example>
This results with ... div being clickable - a message box with provided text is displayed. Now I wanted to place this tag inside a template, like this:
<simplified_example value="{{{1}}}">...</simplified_example>
When I put this template into a MediaWiki page:
{{TestTemplate|Testing...}}
Once again I obtain a clickable ... but displayed message is not evaluated and {{{1}}} is displayed instead of provided Testing....
How can I pass the argument from MediaWiki page source down to my custom tag through a template?
Try to use #tag function instead of html in your template, like this:
{{#tag:simplified_example|value={{{1}}} }}

How to create a string map "location" and "location Value Text" of this string text?

I developed project using anguler with ngRx framework. I used TypeScript with HTML for developing front-end.My db have saved 'HTML' format texts like below.
"<html><body>A.txt
B.txt
D.txt
www.facebook.com
</body></html>"
This text priviouly , I drectly render in html file using <dev INNERHTML ={{stringText }} \> like wise.
But my project using JXBrowser and as it's configuration , this can't be directly open in default browser clicking just link.
For that work ,I need to take href location as URL and when click it passed to .ts file.
I thought ,it change as like this <a role="button" click='getLink(myText)'> {{getLink(value}} </a>'. so ,create this ,I need that text put a array with contain 'location' and value.Next ,I though ,Iterate that array in HTML file.
I need some expert help to do this ? I am struggle with map above text to such kind of string array (eg :array[hrfeLink][value]). Hope some expert help me.
------------Updated---------------
According to the comment, I will try this way, and I can take the link location. But still couldn't take value.
let parser = new DOMParser();
let doc = parser.parseFromString(info, "text/html");
let x = doc.getElementsByTagName('a');
for (let i = 0; i < x.length ; i++) {
console.log(x[i].getAttribute('href'));
}
What is the value that you want? Is it the anchor text of the link?
We create an interface Link with the properties that we want from each link
interface Link {
location: string;
value: string;
}
Then we create a function that extracts all links from an html string and converts them to an array of Link objects.
function parseLinks( stringHTML: string ): Link[] {
// create a parser object
const parser = new DOMParser();
// turn the string into a Document
const doc = parser.parseFromString( stringHTML, "text/html" );
// get all links
const linkNodes = doc.getElementsByTagName('a');
// convert from HTMLCollection to array to use .map()
const linksArray = [...linkNodes];
// map from HTMLAnchorElement to Link object
return linksArray.map( element => ({
location: element.href,
value: element.innerText,
}))
}
Now you can do whatever with the links from your text
const text = `<html><body>A.txt
B.txt
D.txt
www.facebook.com
</body></html>`;
const links: Link[] = parseLinks( text );
// can use like this
links.map( ({location, value}) => {
// do something here
})
Typescript Playground Link

Yii2 render image in browser without image tag using yii2-imagine

I'm using yii2-imagine
$imagine = yii\imagine\Image::getImagine();
Imagine->open('path/watermark.jpg')->show('jpg');
My problem is it not show the image, it show that:
����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ��C $.' ",#(7),01444'9=82<.342��C 2!!22222222222222222222222222222222222222222222222222����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�%�
Any idea?
You need to use the getImagine() function first to invoke the GD or Imagick which ever available instance then call ->open() and ->show() on the object. Moreover, you need to provide the $options for the image to display too. You can copy paste the following code inside an action in your controller and can see the result image. I just tested on my local system, and it is in working, just remember to provide valid path to the $source variable
use yii\imagine\Image;
$source="/path/to/your/image.jpg";
$imagine = new Image();
$options = array(
'resolution-units' => \Imagine\Image\ImageInterface::RESOLUTION_PIXELSPERINCH,
'resolution-x' => 300,
'resolution-y' => 300,
'jpeg_quality' => 100,
);
echo $imagine->getImagine()->open($source)->show('jpg',$options);
Apart from the above solution that displays the image in the browser if you want to display the image inside the img tag you can base64_encode the raw image data returned from the open() method and provide into the tag like below.
echo '<img src="data:image/jpeg;base64,'.base64_encode($imagine->getImagine()->open($source)).'" >';
Hope it helps

CKeditor returning 403 when submitting certain html tags

I've created a page where I have two input textareas and I add CKeditor (ver. 4) to both of them.
The first editor works fine, I've set config.allowedContent = true; in the config.js to stop stripping tags like <script> and everything works as expected.
I have another editor right below it, same settings, same setup, I just changed the ID of the textarea field. It works when I submit normal text, but as soon as I add a <script> tag, for example, and press the submit button of the form in which the editors are in it seems to reload the page, doesn't submit any data and firebug tells me that the server returns 403.
I tried isolating the editor, adding personal configuration. Nothing. The first textarea works like a charm, second one returns 403 if the text has unsafe tags in it.
My setup is as follows, I'm using this ckeditor helper to insert the editors where I need. Page is created with CodeIgniter as you guessed.
I got a config.js file in ckeditor folder.
I'm using a regular form, nothing fancy about it. It looks like this
<form action="http://domain.com/admin/articles/edit/47" method="post">
<div id="cke_ckeditor_en_container">
<textarea cols="75" rows="7" id="ckeditor_en" name="text_en" class="input-text is-col-text"><?php echo set_value('text_en', isset($text_en) ? htmlspecialchars_decode($text_en) : ''); ?></textarea>
<?php echo display_ckeditor($ckeditor_en); ?>
</div>
<input type="submit" value="submit" />
</form>
The form has another part of html for the other editor which is the same, with changed id and other attributes, and a checkbox, nothing relevant.
And got this in my controller
public function edit(){
$this->load->helper('ckeditor');
$id = (int)$this->uri->segment(4);
if (empty($id)){
$this->session->set_flashdata('error', 'Empty ID!');
redirect('admin/articles');
}
$data = $this->articles_model->fetch_article($id);
$data['page_title'] = "Edit `" . $data['title'] . "`";
$data['form_url'] = "admin/articles/edit/" . $id;
$data['ckeditor'] = array(
'id' => 'ckeditor',
'path' => 'js/ckeditor');
$data['ckeditor_en'] = array(
'id' => 'ckeditor_en',
'path' => 'js/ckeditor');
$data['edit'] = true;
if($this->input->post('submit')){
$this->save_article("update",$id);
}
$this->load->view("admin/articles",$data);
}
private function save_article($type='insert', $id=0){
$this->load->library('form_validation');
$this->form_validation->set_rules('title','Title','trim|xss_clean|max_length[150]|min_length[1]');
$this->form_validation->set_rules('text','Text','trim');
$this->form_validation->set_rules('title_en','Title EN','trim|xss_clean|max_length[150]|min_length[1]');
$this->form_validation->set_rules('text_en','Text EN','trim');
$this->form_validation->set_rules('top_menu','Show in top menu','trim|xss_clean|max_length[1]');
if ($this->form_validation->run() === FALSE)
{
return FALSE;
}
// make sure we only pass in the fields we want
$data = array();
$data['title'] = $this->input->post('title');
$data['text'] = htmlspecialchars($this->input->post('text'));
$data['title_en'] = $this->input->post('title_en');
$data['text_en'] = htmlspecialchars($this->input->post('text_en'));
$data['url'] = $this->toAscii($this->input->post('title'));
$data['url_en'] = $this->toAscii($this->input->post('title_en'));
$data['top_menu'] = $this->input->post('top_menu');
if($type == "insert"){
$data['time'] = date("YmdHis");
}
if ($type == 'insert'){
if($this->articles_model->insert($data)){
$this->session->set_flashdata('success', 'Article added successfully!');
}else{
$this->session->set_flashdata('error', 'An error occured!');
}
}else if ($type == 'update'){
if($this->articles_model->update($id, $data)){
$this->session->set_flashdata('success', 'Article `' . $data['title'] . '` edited successfully!');
}else{
$this->session->set_flashdata('error', 'An error ecc!');
}
}
redirect("admin/articles");
}
Safety, or unsafeness, to be exact, of my code is not relevant
edit
Adding config.js for ckeditor.
CKEDITOR.editorConfig = function( config ) {
config.filebrowserBrowseUrl = '/js/kcfinder/browse.php?type=files';
config.filebrowserImageBrowseUrl = '/js/kcfinder/browse.php?type=images';
config.filebrowserFlashBrowseUrl = '/js/kcfinder/browse.php?type=flash';
config.filebrowserUploadUrl = '/js/kcfinder/upload.php?type=files';
config.filebrowserImageUploadUrl = '/js/kcfinder/upload.php?type=images';
config.filebrowserFlashUploadUrl = '/js/kcfinder/upload.php?type=flash';
config.removeButtons = 'Underline,Subscript,Superscript';
config.allowedContent = true;
// Se the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre';
// Make dialogs simpler.
config.removeDialogTabs = 'image:advanced;link:advanced';
};
I'm stumped and stupified, I've got no ideas on what to do. It seems that the one input has been cursed.
Any help appreciated, thank you.
This would be the result of your mod_security rules. Depending on how strict they are they help better protect scripts from being hacked through vulnerabilities, generally those exploited via POST's.
As I understand you are trying to add something to your second textarea. And CKEditor removing some "unsafe" tags. I won't be very secure, but this can help you:
config.extraAllowedContent = '*{*}';
You will add this to your config.js. This code provides you to add anything you want. And CKEditor won't delete "unsafe" tags.
Documenation for this method
https://www.bilisimkitabi.com/403-error-on-submit-of-ckeditor
You can add to following code in your .htaccess file
#ckeditor Post 403 problem
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
#ckeditor Post 403 problem