stevebauman / purify Goto Github PK
View Code? Open in Web Editor NEWA Laravel wrapper for HTMLPurifier by ezyang
License: MIT License
A Laravel wrapper for HTMLPurifier by ezyang
License: MIT License
I have an issue after deployment:
Directory /var/www/html/mysite.com/vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer not writable, please chmod to 777
The fix is released already. You can see the ticket here:
passbolt/passbolt_api#274
Can you please update your package
Im using purify as my primary sanitization package together with ckeditor to embed media objects like youtube videos and twitter tweets? ckeditor add these object inside custom html tage.
<oembed>https://www.youtube.com/watch?v=H08tGjXNHO4</oembed>
<oembed>http://www.slideshare.net/esaops/rosetta-comet-landing-press-kit-12-nov-2014</oembed>
<oembed>https://twitter.com/Philae2014/status/610047412036595712</oembed>
unfortunately, Purify is automatically stripping these tages from published blade template, so im getting this instead
https://www.youtube.com/watch?v=H08tGjXNHO4
http://www.slideshare.net/esaops/rosetta-comet-landing-press-kit-12-nov-2014 https://twitter.com/Philae2014/status/610047412036595712
dos anybody have an idea on how to solve this problem? or maybe adding customer tags to allowed html tags in purify.
I have HTMLPurifier 4.15.0 from PEAR on an ubuntu server 22.04.
I've set
$config->set('Cache.DefinitionImpl', null);
but I'm still seeing this warning:
/usr/share/php/HTMLPurifier/DefinitionCache/Serializer.php(297): Directory /usr/share/php/HTMLPurifier/DefinitionCache/Serializer not writable, please chmod to 777
If I set:
$config->set('Cache.SerializerPath', '/some/dir'); // which is writable by the web server
the exact same warning still appears mentioning DefinitionCache/Serializer not my directory.
I can't set the permissions of the default directory because I have no access and I don't need caching anyway because I'm doing inbound filtering.
I am using Purify in a laravel project and need to allow
elements (for tinymyce wysiwyg editor).Have followed the readme Custom Configuration Rules and installed a PurifySetupProvider with the new element. Nevertheless, Purify strips out the figure elements.
Here is the ServideProvider:
<?php
namespace App\Providers;
use HTMLPurifier_HTMLDefinition;
use Stevebauman\Purify\Facades\Purify;
use Illuminate\Support\ServiceProvider;
class PurifySetupProvider extends ServiceProvider
{
const DEFINITION_ID = 'tinymce-editor';
const DEFINITION_REV = 1;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
/** @var \HTMLPurifier $purifier */
$purifier = Purify::getPurifier();
/** @var \HTMLPurifier_Config $config */
$config = $purifier->config;
$config->set('HTML.DefinitionID', static::DEFINITION_ID);
$config->set('HTML.DefinitionRev', static::DEFINITION_REV);
$config->set('URI.AllowedSchemes', ['data' => true]); // allow data URIs
if ($def = $config->maybeGetRawHTMLDefinition()) {
$this->setupDefinitions($def);
}
$purifier->config = $config;
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Adds elements and attributes to the HTML purifier
* definition required by the tinyMCE editor.
*
* @param HTMLPurifier_HTMLDefinition $def
*/
protected function setupDefinitions(HTMLPurifier_HTMLDefinition $def)
{
$def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common');
$def->addAttribute('figure', 'class', 'Text');
$def->addElement('figcaption', 'Inline', 'Flow', 'Common');
$def->addAttribute('figcaption', 'class', 'Text');
}
}
and my test:
<?php
namespace Tests\Unit;
use Tests\TestCase;
class PurifyTest extends TestCase
{
/** @test */
function it_allows_figures()
{
$input = '<figure><figcaption>Hello fig</figcaption></figure>';
$cleaned = \Purify::clean($input);
$this->assertEquals( '<figure><figcaption>Hello fig</figcaption></figure>', $cleaned);
}
}
The workaround to make it work was to update the package service provider register method to bind a singleton, instead of an usual bind:
/**
* Register the service provider.
*/
public function register()
{
$this->publishes([
__DIR__.'/Config/config.php' => config_path('purify.php'),
], 'config');
$this->app->singleton('purify', function ($app) {
return new Purify();
});
}
What am I missing in setting up the Custom Configuration rules? What are the implications of using the singleton on the caching?
thanks
Hello
Please upgrade this package to support latest version of Laravel 6.0.
Thanks :)
Hello,
I am using a trix-editor with Laravel 5.5 and, of course, the stevebauman/purify package to sanitize the html input.
There seems to be an issue with sanitizing attachments (uploaded images) in the trix editor. It seems to multiply the anchor tags, so instead of one anchor tag (before sanitizing), you get 5 anchor tags (after sanitizing).
Here is the content without sanitizing (what the trix-editor outputs):
before
And here is the content after purifying it:
after
I have added the proposed Service Provider for the Trix Editor, which seems to miss a few attributes, but this should not be a problem.
Hello,
I noticed after implementing this as middleware for all incoming request input that when a boolean is passed to Purify, it simply nullifies the input.
In my failing tests, this generates an error because the input passed is nullified :
'boolean_field' => false,
If I switch the above field to the following , it works :
'boolean_field' => 0,
Any ideas?
I have the same project on 2 different PCs. One works just fine while the other one is getting the following error:
ErrorException
Base directory C:\projects\Laravel\projectName\storage\purify does not exist, please create or change using %Cache.SerializerPath
Any idea on how to fix this?
I wanna test attribute purify. It works fine in local but failed in pupunit testing.
I have made ServiceProvider as readme mentioned.
// provider
$def->addAttribute('span', 'data-user', 'Text');
// config/purify.php
'HTML.Allowed' => 'span[data-user]',
// testing
$content = '<span class="text-primary" data-user="foo">@foo</span>';
\Purify::clean($content)
// ErrorException : Attribute 'data-user' in element 'span' not supported (for information on implementing this, see the support forums)
// but it works in tinker
Hello, my team and I ran into an issue when trying to use this with Vapor and realized that the 'Cache.SerializerPath' must be a local directory on the webserver, which Vapor doesn't support.
Is it possible to add support for S3 or other Storage drivers to this and are there any plans for that?
Image tags are having their style attributes removed - the style tags are added by an RTE so I have no control over how the markup is generated.
Example is:- <img src="..." style="width: 50%;">
-> <img src="...">
My config is as follows:-
HTML.Allowed' => 'h1,h2,h3,h4,h5,h6,b,strong,i[class|id],em,a[href|title|class|id|style],ul,ol,li,p[style|class],br,span[style|class|id],img[width|height|alt|src|class|style],div[style|class|id]',
'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,padding-right,padding-top,padding-bottom,padding,color,background-color,text-align,background,width,height',
I thought it could be the config cache so I ran:-
php artisan purify:clear
but that produced the error There are no commands defined in the "purify" namespace.
Any ideas?
Thanks
So I followed all your installation and configuration steps.
When I use
$cleaned = Purify::clean($input);
It works fine and all cache are stored in storage/purify.
As soon as I dynamically configure the second array and pass my configuration it seems that it will again start storing cache into the default htmlPurify vendor file.
;)
Hi @stevebauman thank you so much for the package, Im having problems trying to purify (text) something simple like "A & B
" it turns it into "A & B
", how can I allow some letters to stay the same?
'text' => [
'Core.Encoding' => 'utf-8',
'HTML.Doctype' => 'HTML 4.01 Transitional',
'HTML.Allowed' => '',
'HTML.ForbiddenElements' => 'script,meta',
'AutoFormat.AutoParagraph' => false,
'AutoFormat.RemoveEmpty' => false,
],
The idea for this 'text' configuration is to just clean any malicious stuff
Appreciate any help
Hi Author,
Can you please upgrade this package to support Laravel 7?
Thanks :)
Hi,
I'm trying to create custom configuration by add strike
to PurifySetupProvider
as in https://github.com/stevebauman/purify#custom-configuration-rules
I created PurifySetupProvider and I added this line for strike
$def->addElement('strike', 'Block', 'Flow', 'Common');
And still not working,
Did I miss something in configuration ?
Can you add a license.md file?
Hi Steve,
First of all, thanks for the great library to sanitize the input.
Is there any solution to add attributes of allowfullscreen in iframe or in the future?
I manually add allowfullscreen as bool to enable the allowfullscreen feature for now.
If there a feature to enable this it will be great.
Hi There,
I'm currently using Purify in my Laravel form validations.
Essentially I clean an input string and compare it to the original and if they are not identical then something illegal was entered into the field and the user is asked to correct their input.
However, I've noticed that textarea fields that contain \n newlines are replaced in Purify by \n\r and therefore cleaned content does not match original content and user is asked to remove illegal markup.
Is there a way to bypass this please?
Thanks
Does anyone know why I get this error when I do this in my accessor
public function getBodyAttribute($body)
{
return Purify::clean($body)
}
ErrorException (E_ERROR)
count(): Parameter must be an array or an object that implements Countable
In HTMLPurifies is fixed but i don't know why not when i pull this package.
ezyang/htmlpurifier#157
Trying to use purify with pre,code
in the HTML.Allowed
config crashes swoole worker processes used by Laravel Octane. I tried to figure out where exactly but didn't have any luck so far, opening this to see if others bump in the same issue.
Swoole issue: swoole/swoole-src#5083
Hello,
Could you please give me some hint how I can use Purify in form request?
Regards
I need an administrator to be able to create html templates for users so that they can fill out these custom forms.
How can I allow the input tag?
Anyway to incorporate border-radius
as an optional CSS.AllowedProperties?
This lib clears base64 images.
<img style="width: 268px;" src="data:image/png;base64 ...
This is strange, since it is mostly used to sanitize input from WYSIWYG and base64 images are mainstay of such editors. It should be an integral part of lib's core.
A difficult one to explain, but I'm trying to set up Purify to "allow" <u>
tags, and transform them into <span style="text-decoration: underline">
.
After I've done what I think is required, it works, but not on the first call to Purify::clean() in a given PHP request cycle, e.g.
$ tinker
Psy Shell v0.9.3 (PHP 7.1.16 — cli) by Justin Hileman
>>> Purify::clean('<u>Foo</u>');
PHP Warning: Element 'u' is not supported (for information on implementing this, see the support forums) in /private/tmp/purify-test/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLDefinition.php on line 311
>>> Purify::clean('<u>Foo</u>');
=> "<span style="text-decoration:underline;">Foo</span>"
Whereas I'd expect:
$ tinker
Psy Shell v0.9.3 (PHP 7.1.16 — cli) by Justin Hileman
>>> Purify::clean('<u>Foo</u>');
=> "<span style="text-decoration:underline;">Foo</span>"
>>> Purify::clean('<u>Foo</u>');
=> "<span style="text-decoration:underline;">Foo</span>"
Steps to reproduce:
laravel new test-project
cd test-project
composer require stevebauman/purify
php artisan vendor:publish --provider="Stevebauman\Purify\PurifyServiceProvider"
config/purify.php
and add "u" to HTML.Allowed
app/Providers/PurifyServiceProvider.php
as per https://gist.github.com/leewillis77/6c1fe0ad5448b1fae6b5412a2ee02502config/app.php
and add App\Providers\PurifyServiceProvider::class
to the list of providersrm -fr storage/purify/
)Purify::clean('<u>Foo</u>');
in a tinker session[Sidenote, I'd be happy if I could get it just to allow as an alternative, but the same issue happens with that]
I've ran into a potential improvement in the package.
At the moment the package forces the developer to publish the configuration file to change the Cache.SerializerPath
from the vendor folder the storage folder.
This should be done by default, so would it be possible to either merge the configuration file in the service provider or manually override the that configuration setting.
Merging the configuration would be done like so (this solution automatically updates with any new configuration options you've published).
<?php
class PurifyServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__ . '/Config/purify.php', 'purify');
}
}
OR
Should that configuration option be forced manually? Leaving the rest up to the original package to decide? Like so.
<?php
class PurifyServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*/
public function register()
{
$this->app->get('config')->set('purify.settings.Cache.SerializerPath', storage_path('purify'));
}
}
Hello,
Thank you for Purify, it's great! I'm using Trix and I need the code blocks working, but I don't know how to do it with Purify and how safe is to leave them.
Thank you in advance.
I would like to allow classes wih values ql-size-small, etc.
I have the following code:
public static function apply(HTMLPurifier_HTMLDefinition $definition)
{
$definition->addAttribute('span', 'class', new HTMLPurifier_AttrDef_Enum(['ql-size-small']));
}
After having clleared the cache, the following html code doesn't get passed:
<span class=\"ql-size-small\">My text</span>
Using purify without the Laravel extension:
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.DefinitionID', 'enduser-customize.html tutorial');
$config->set('HTML.DefinitionRev', 1);
$config->set('Cache.DefinitionImpl', null); // remove this later!
$def = $config->getHTMLDefinition(true);
$def->addAttribute('span', 'class', new HTMLPurifier_AttrDef_Enum(['ql-size-small']));
The classes are passed correctly.
After upgrading to laravel 7, i have this issue for some reason.
Undefined variable: array
In here:
* @return string[] Array of purified HTML
*/
public function purifyArray($array_of_html, $config = null)
{
$context_array = array();
foreach($array_of_html as $key=>$value){
if (is_array($value)) {
$array[$key] = $this->purifyArray($value, $config);
} else {
$array[$key] = $this->purify($value, $config);
}
$context_array[$key] = $this->context;
}
$this->context = $context_array;
return $array;
}
What can be the problem?
I followed the instructions for installing stevebauman/purify
, I have installed it via composer and inserted the service provider in config/app.php
:
/*
* Application Service Providers...
*/
Stevebauman\Purify\PurifyServiceProvider::class,
Also, I've added facade:
'aliases' => [
'Purify' => Stevebauman\Purify\Facades\Purify::class,
],
In my controller when I have:
use Stevebauman\Purify\Facades\Purify;
...
$article->body = Purify::clean($article->body);
I am getting the following error:
Class purify does not exist
But if I have use Stevebauman\Purify\Purify;
then I get:
Non-static method Stevebauman\Purify\Purify::clean() should not be called statically
Hi @stevebauman , thank you for the work in the package, nice
Steve is there any way to allow all css class="" and style=""?
Appreciate any guidance
good day
Hi,
first of all thank you very much for this.
My question is how to accept <style></style>. I tried adding it in the config/purify but to no avail.
'HTML.Allowed' => 'style,div,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span[style],img[width|height|alt|src]',
I wish donot removed table element when i clean the input.
I have problem for purify:clean table, please help
Required attribute 'summary' in element 'table' was not allowed, which means 'table' will not be allowed either
Anyway to allow oembed tags with purifier that comes with CKeditor media embed option?
The current version 4 doesn't appear to be supported by the latest version of Laravel 9.
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Root composer.json requires stevebauman/purify ^4.0 -> satisfiable by stevebauman/purify[v4.0.0].
- Conclusion: don't install laravel/framework v9.0.0-beta.2 (conflict analysis result)
- Conclusion: don't install laravel/framework v9.0.0-beta.3 (conflict analysis result)
- Conclusion: don't install laravel/framework v9.0.0-beta.4 (conflict analysis result)
- Conclusion: don't install laravel/framework v9.0.0-beta.5 (conflict analysis result)
- Conclusion: don't install laravel/framework v9.0.0 (conflict analysis result)
- Conclusion: don't install laravel/framework v9.0.1 (conflict analysis result)
- Conclusion: don't install laravel/framework v9.0.0-beta.1 (conflict analysis result)
- stevebauman/purify v4.0.0 requires illuminate/support ~5.5|~6.0|~7.0|~8.0 -> satisfiable by illuminate/support[v5.5.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev].
- Only one of these can be installed: illuminate/support[v5.5.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev], laravel/framework[v9.0.0-beta.1, ..., 9.x-dev]. laravel/framework replaces illuminate/support and thus cannot coexist with it.
- Root composer.json requires laravel/framework ^9.0 -> satisfiable by laravel/framework[v9.0.0-beta.1, ..., 9.x-dev].
This appears to be a conflict in versions between Purify and Laravel with the illuminate/support
library.
Hi,
After running php artisan vendor:publish --provider="Stevebauman\Purify\PurifyServiceProvider"
I get:
Publishing complete.
... but there is no config/purify.php
file.
Following warning started showing up when installing the package.
Deprecation Notice: Class HTMLPurifier_Language_en_x_test located in ./vendor/ezyang/htmlpurifier/library/HTMLPurifier/Language/classes/en-x-test.php does not comply with psr-0 autoloading standard. It will not autoload anymore in Composer v2.0. in phar:///usr/local/bin/composer.phar/src/Composer/Autoload/ClassMapGenerator.php:201
In addition to that, the automatic package discovery didn't work and I had to manually create the storage/purify
directory.
Composer version 1.10.5 2020-04-10 11:44:22
Laravel Framework 7.11.0
PHP 7.2.31 (cli) (built: May 14 2020 10:54:35) ( NTS )
Steve,
I'm trying hard to get target="_blank" working in my links. I've tried -
'Attr.AllowedFrameTargets' => ['_blank'],
and
'HTML.Allowed' => 'a[href|target|rel]',
but it still throws message that "Attribute 'target' in element 'a' not supported (for information on implementing this, see the support forums) ",
Would really appreciate if you could suggest a way to make this work. I've spent at least 4 hours on this, but without success.
$config = ['HTML.ForbiddenElements' => 'span[style]'];
$cleaned = Purify::clean($cleaned_content, $config);
return $cleaned;
//result <span style="font-weight:400;"> is still there
I extended HTMLPurifier_DefinitionCache in order to use the Laravel caching system rather than the bespoke filesystem one; mainly because Vapor (lambda) doesn't support local fs usage, so I use Redis.
Having written that class, I can't see how to inject that strategy. The config option requires you to pass a "short name" - one which has already been mapped to the class name you want to use with $factory->register(...).
Hence this isn't a help request but an issue/feature for Purify - to allow bespoke classes to be passed in as cache definitions.
Hello Steve,
I am running production on laradock environment.
PHP 7.3
Using redis for cache
Laravel 6.0
The error is "/vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer not writable, please chmod to 777"
I already published the config file which is inside config/purify.php and "chmod -R 777 storage".
The weird thing is I don't see this error on local dev environment.
Thanks
Love your Purify!
But here is one issue:
You aspect this:
"Hi 😃 How are you?"
But after the Clean you get this:
"Hi 😃How are you?"
I was trying to clean a text input value and found that it is adding an additional <p>
tag. For text area it is ok, but i do not want to add <p>
in the string input.
Is there any way to configure this for specific fields?
Looks like Laravel 10 will be released in one week. Are there any chances for update?
Firstly I must thank you for this script it's very good with Laravel 5.
I have been trying to add HTML5 tags (article,section,... etc) and also support to add iFrames like from youtube etc. But I am really stuck trying to add them to your code. I have tried modifying the config file and tried adding them to a custom $settings. But still not getting anywhere.
I have come across another github found here: https://github.com/xemlock/htmlpurifier-html5
Also this github: https://github.com/kennberg/php-htmlpurfier-html5
But I am stuck in trying to merge the extra files together to make it work. So I thought I'd reach out and see if it's possible to get some help to upgrade this script.
The code I have been using to try and add Youtube and Vimeo support into your config etc was this:
'HTML.SafeIframe' => 'true',
'URI.SafeIframeRegexp' => '%^(http:|https:)?//(www.youtube(?:-nocookie)?.com/embed/|player.vimeo.com/video/)%',
or
'URI.SafeIframeRegexp' => '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%',
Thanks.
I'm currently hitting an issue where Purify throws the following error during package discovery on a fresh composer install
of my project:
mkdir(): No such file or directory
It's trying to create the folder {projectroot}/storage/purify
, but failing because {projectroot}/storage
doesn't exist at that point. As background, I symlink in the storage folder as part of my deployment process, so there is no storage folder in my project's repository at all.
While I realise that might make my setup a little non-standard, Purify is the only package that fails under this setup. I can work around this on my side, however it seems like it might be best resolved in Purify (especially since it looks like you're doing that filesystem check every time Purify is instantiated (e.g. on every page load if every page uses Purify)?
Hey Steve. Thanks a lot for this package.
I'm working on a website building platform and need to use different rules for different fields. For example, the "Custom CSS" field should only contain CSS, a page's content field should only contain HTML + CSS etc.
I was thinking of using config::set to modify the config dynamically, but was wondering if there was a cleaner approach.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.