Code Monkey home page Code Monkey logo

purify's Introduction

Purify

A Laravel wrapper for HTMLPurifier by ezyang.

Index

Requirements

  • PHP >= 7.4
  • Laravel >= 7.0

Installation

To install Purify, run the following command in the root of your project:

composer require stevebauman/purify

Then, publish the configuration file using:

php artisan vendor:publish --provider="Stevebauman\Purify\PurifyServiceProvider"

Usage

Cleaning a String

To clean a users input, simply use the clean method:

use Stevebauman\Purify\Facades\Purify;

$input = '<script>alert("Harmful Script");</script> <p style="border:1px solid black" class="text-gray-700">Test</p>';

// Returns '<p>Test</p>'
$cleaned = Purify::clean($input);
Cleaning an Array

Need to purify an array of user input? Just pass in an array:

use Stevebauman\Purify\Facades\Purify;

$array = [
    '<script>alert("Harmful Script");</script> <p style="border:1px solid black" class="text-gray-700">Test</p>',
    '<script>alert("Harmful Script");</script> <p style="border:1px solid black" class="text-gray-700">Test</p>',
];

$cleaned = Purify::clean($array);

// array [
//  '<p>Test</p>',
//  '<p>Test</p>',
// ]
var_dump($cleaned);
Dynamic Configuration

Need a different configuration for a single input? Pass in a configuration array into the second parameter:

Note: Configuration passed into the second parameter is not merged with your default configuration.

use Stevebauman\Purify\Facades\Purify;

$config = ['HTML.Allowed' => 'div,b,a[href]'];

$cleaned = Purify::config($config)->clean($input);

Configuration

Inside the configuration file, multiple HTMLPurifier configuration sets can be specified, similar to Laravel's built-in database, mail and logging config. Simply call Purify::config($name)->clean($input) to use another set of configuration.

For example, if we need to have a separate configuration for a comment system, we can setup this configuration in the config/purify.php file:

// config/purify.php

'configs' => [
    // ...

    'comments' => [
        // Some configuration ...
    ],
]

Then, utilize it anywhere in your application by its name:

use Stevebauman\Purify\Facades\Purify;

$cleanedContent = Purify::config('comments')->clean(request('content'));

For HTMLPurifier configuration documentation, please visit the HTMLPurifier Website:

http://htmlpurifier.org/live/configdoc/plain.html

Cache

After running Purify once, HTMLPurifier will auto-cache your serialized definitions into the serializer.cache definition you have configured in config/purify.php.

Important

If you have configured Purify to utilize the CacheDefinitionCache in the serializer option, this command will issue a Cache::clear() on the cache driver you have configured it to use.

If you have configured Purify to utilize the FilesystemDefinitionCache in the serializer option, this command will clear the directory that you have configured it to store in.

It is recommended to setup a unique filesystem path or disk (via config/filesystems.php) or cache store (via config/cache.php) for Purify if you intended to clear the serialized definitions using this command.

If you ever update the definitions configuration option, you must clear this HTMLPurifier cache.

You may do so via a purify:clear command:

php artisan purify:clear

Disabling Caching

To disable caching all together, you may set the serializer path to null:

// config/purify.php

'serializer' => null,

This will cause your definitions to be serialized upon each application request.

This is especially useful when debugging or tweaking definition files to see immediate results.

Important

Caching is recommended in production environments.

Practices

If you're looking into sanitization, you're likely wanting to sanitize inputted user HTML content that is then stored in your database to be rendered onto your application.

In this scenario, it's likely best practice to sanitize on the way out instead of the on the way in. The database doesn't care what text it contains.

This way you can allow anything to be inserted in the database, and have strong sanization rules on the way out.

To accomplish this, you may use the provided PurifyHtmlOnGet cast class on your Eloquent model:

use Stevebauman\Purify\Casts\PurifyHtmlOnGet;

class Post extends Model
{
    protected $casts = [
        'content' => PurifyHtmlOnGet::class,
    ];
}

Or, implement it yourself via an Eloquent attribute mutator:

use Stevebauman\Purify\Facades\Purify;

class Post extends Model
{
    public function getContentAttribute($value)
    {
        return Purify::clean($value);
    }
}

You can even configure the configuration that is used when casting by appending it's name to the cast:

// config/purify.php

'configs' => [
    // ...

    'other' => [
        // Some configuration ...
    ],
]
protected $casts = [
    'content' => PurifyHtmlOnGet::class.':other',
];

This helps tremendously if you change your sanization requirements later down the line, then all rendered content will follow these sanization rules.

If you'd like to purify HTML while setting the value, you can use the inverse PurifyHtmlOnSet cast instead.

Custom HTML definitions

The HTML.Doctype configuration option denotes the schema to ultimately abide to. You may want to extend these schema definitions to support custom elements or attributes (e.g. <foo>...</foo>, or <span foo="...">) by specifying a custom HTML element "definitions".

Purify ships with additional HTML5 definitions that HTMLPurifier does not (yet) support of the box (via the Html5Definition class).

To create your own HTML definition, create a new class and have it implement Definition:

namespace App;

use HTMLPurifier_HTMLDefinition;
use Stevebauman\Purify\Definitions\Definition;

class CustomDefinition implements Definition
{
    /**
     * Apply rules to the HTML Purifier definition.
     *
     * @param HTMLPurifier_HTMLDefinition $definition
     *
     * @return void
     */
    public static function apply(HTMLPurifier_HTMLDefinition $definition)
    {
        // Customize the HTML purifier definition.
    }
}

Then, reference this class in the config/purify.php file in the definitions key:

// config/purify.php

'definitions' => \App\CustomDefinitions::class,

If you'd like to extend the built-in default Html5Definition, you can apply it to your custom definition:

use Stevebauman\Purify\Definitions\Html5Definition;

class CustomDefinition implements Definition
{
    public static function apply(HTMLPurifier_HTMLDefinition $definition)
    {
        Html5Definition::apply($definition);
        
        // ...
    }
}
Basecamp Trix Definition

Here's an example for customizing the definition in order to support Basecamp's Trix WYSIWYG editor (credit to Antonio Primera & Daniel Sun):

namespace App;

use HTMLPurifier_HTMLDefinition;
use Stevebauman\Purify\Definitions\Definition;

class TrixPurifierDefinitions implements Definition
{
    /**
     * Apply rules to the HTML Purifier definition.
     *
     * @param HTMLPurifier_HTMLDefinition $definition
     *
     * @return void
     */
    public static function apply(HTMLPurifier_HTMLDefinition $definition)
    {
        $definition->addElement('figure', 'Inline', 'Inline', 'Common');
        $definition->addAttribute('figure', 'class', 'Class');
        $definition->addAttribute('figure', 'data-trix-attachment', 'Text');
        $definition->addAttribute('figure', 'data-trix-attributes', 'Text');

        $definition->addElement('figcaption', 'Inline', 'Inline', 'Common');
        $definition->addAttribute('figcaption', 'class', 'Class');
        $definition->addAttribute('figcaption', 'data-trix-placeholder', 'Text');

        $definition->addAttribute('a', 'rel', 'Text');
        $definition->addAttribute('a', 'tabindex', 'Text');
        $definition->addAttribute('a', 'contenteditable', 'Enum#true,false');
        $definition->addAttribute('a', 'data-trix-attachment', 'Text');
        $definition->addAttribute('a', 'data-trix-content-type', 'Text');
        $definition->addAttribute('a', 'data-trix-id', 'Number');

        $definition->addElement('span', 'Block', 'Flow', 'Common');
        $definition->addAttribute('span', 'data-trix-cursor-target', 'Enum#right,left');
        $definition->addAttribute('span', 'data-trix-serialize', 'Enum#true,false');

        $definition->addAttribute('img', 'data-trix-mutable', 'Enum#true,false');
        $definition->addAttribute('img', 'data-trix-store-key', 'Text');
    }
}

Custom CSS definitions

It's possible to override the CSS definitions, this allows you to customize what inline styles you allow and their properties and values. This can help fill in missing values for properties such as text-align, which by default is missing start and end values. You can do this by creating a CSS definition.

To create your own CSS definition, create a new class and have it implement CssDefinition:

namespace App;

use HTMLPurifier_CSSDefinition;
use Stevebauman\Purify\Definitions\CssDefinition;

class CustomCssDefinition implements CssDefinition
{
    /**
     * Apply rules to the CSS Purifier definition.
     *
     * @param HTMLPurifier_CSSDefinition $definition
     *
     * @return void
     */
    public static function apply(HTMLPurifier_CSSDefinition $definition)
    {
        // Customize the CSS purifier definition.
        $definition->info['text-align'] = new \HTMLPurifier_AttrDef_Enum(
            ['right', 'left', 'center', 'start', 'end'],
            false,
        );
    }
}

Then, reference this class in the config/purify.php file in the css-definitions key:

// config/purify.php

'css-definitions' => \App\CustomCssDefinition::class,

See the class HTMLPurifier_CSSDefinition in the HTMLPurifier library for other examples of what can be changed.

Upgrading from v4 to v5

To upgrade from v4, install the latest version by running the below command in the root of your project:

composer require stevebauman/purify

Then, navigate into your published config/purify.php configuration file and copy the settings array -- except for the following keys:

  • HTML.DocType:
  • Core.Encoding:
  • Cache.SerializerPath:
'settings' => [
-   'Core.Encoding' => 'utf-8',
-   'Cache.SerializerPath' => storage_path('app/purify'),
-   'HTML.Doctype' => 'XHTML 1.0 Strict',
+   'HTML.Allowed' => 'h1,h2,h3,h4,h5,h6,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span,img[width|height|alt|src]',
+   'HTML.ForbiddenElements' => '',
+   'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align',
+   'AutoFormat.AutoParagraph' => false,
+   'AutoFormat.RemoveEmpty' => false,
],

Important: If you've created a unique storage path for Cache.SerializerPath, take note of this as well, so you can migrate it into the new configuration file.

Once copied, delete the config/purify.php file, and run the below command:

php artisan vendor:publish --provider="Stevebauman\Purify\PurifyServiceProvider"

Then, inside the newly published config/purify.php configuration file, paste the keys (overwriting the current) into the configs.default array:

'configs' => [
    'default' => [
        'Core.Encoding' => 'utf-8',
        'HTML.Doctype' => 'HTML 4.01 Transitional',
+       'HTML.Allowed' => 'h1,h2,h3,h4,h5,h6,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span,img[width|height|alt|src]',
+       'HTML.ForbiddenElements' => '',
+       'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align',
+       'AutoFormat.AutoParagraph' => false,
+       'AutoFormat.RemoveEmpty' => false,
    ],
],

If you've created a unique serializer path (previously set via the old Cache.SerializerPath configuration key mentioned above), then you may reconfigure this in the new serializer configuration key:

'serializer' => storage_path('app/purify'),

You're all set!

Upgrading from v5 to v6

In v6, the HTMLPurifier Serializer storage mechanism was updated for Laravel Vapour support, allowing you to store the serialized HTMLPurifier definitions in a Redis cache, or an external filesystem.

To upgrade from v5, install the latest version by running the below command in the root of your project:

composer require stevebauman/purify

Then, navigate into your published config/purify.php configuration file and replace the serializer configuration option with the below:

-    'serializer' => storage_path('app/purify'),

+    'serializer' => [
+       'disk' => env('FILESYSTEM_DISK', 'local'),
+       'path' => 'purify',
+       'cache' => \Stevebauman\Purify\Cache\FilesystemDefinitionCache::class,
+    ],
+
+    // 'serializer' => [
+    //    'driver' => env('CACHE_DRIVER', 'file'),
+    //    'cache' => \Stevebauman\Purify\Cache\CacheDefinitionCache::class,
+    // ],

This will update the syntax used to control the serializer cache mechanism. You may now uncomment the below serializer cache definition if you would like to use a Laravel Cache driver (such as Redis) to store the serialized definitions.

purify's People

Contributors

andrzejkupczyk avatar aterniad avatar austenc avatar darthsoup avatar edwinhoksberg avatar filippotoso avatar joostdebruijn avatar kvas-damian avatar mvanduijker avatar plmrlnsnts avatar propaganistas avatar spekulatius avatar stevebauman avatar stylecibot avatar tiagomalheiro avatar zschuessler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

purify's Issues

It's not working as it should ?

$config = ['HTML.ForbiddenElements' => 'span[style]'];

$cleaned = Purify::clean($cleaned_content, $config);

return $cleaned; 

//result <span style="font-weight:400;"> is still there 

phpunit issue

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

Getting target="_blank" to work for links

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.

License

Can you add a license.md file?

Clears base64 images.

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.

html5 and youtube iframe support (possible upgrade feature)

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.

input tag

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?

Trix-editor config

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.

Throws error during package discovery if storage folder doesn't exist

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)?

Allow different caching strategies

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.

/vendor/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer not writable, please chmod to 777

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

Purify replaces \n with \r\n

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

Allow all css and style

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

Merging configuration.

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'));
    }

}

Cache.DefinitionImpl / Cache.SerializerPath is ignored

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.

Depreciation Notice: Class HTMLPurifier_Language_en_x_test does not comply with psr-0 autoloading standard. It will not autoload anymore in Composer v2.0.

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 )

Best way to use with Trix code blocks?

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.

Custom Configuration Rules are not applied

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

Laravel 9 support

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.

oembed / CKeditor

Anyway to allow oembed tags with purifier that comes with CKeditor media embed option?

Definition with HTMLPurifier_HTMLDefinition not working

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.

Registered elements / transforms do not work on first invocation

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"
  • Edit config/purify.php and add "u" to HTML.Allowed
  • Create app/Providers/PurifyServiceProvider.php as per https://gist.github.com/leewillis77/6c1fe0ad5448b1fae6b5412a2ee02502
  • Edit config/app.php and add App\Providers\PurifyServiceProvider::class to the list of providers
  • Clear the purify cache (rm -fr storage/purify/)
  • Try 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]

Multiple configs?

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.

'Cache.SerializerPath' does not work with Dynamic Configuration

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.

Publishing the configuration file doesn't work?

Hi,

After running php artisan vendor:publish --provider="Stevebauman\Purify\PurifyServiceProvider" I get:

Publishing complete.

2018-01-12 00 29 44

... but there is no config/purify.php file.

System details

  • Operating System: Ubuntu 16.04 (Laravel Homestead)
  • PHP Version: PHP 7.1 (Laravel Homestead)
  • Laravel Version: 5.4.36
  • stevebauman/purify Version 2.0.0

Problem table

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

Allow style element

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]',

Image style attributes stripped

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

<p> is added automatically

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?

"A & B" turns it into "A &amp; B"

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 &amp; 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

Class purify does not exist | Non-static method Stevebauman\Purify\Purify::clean() should not be called statically

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

System details

  • Operating System: Ubuntu 16.04 (Laravel Homestead)
  • PHP Version: PHP 7.1 (Laravel Homestead)
  • Laravel Version: 5.4.36
  • stevebauman/purify Version 2.0.0

Booleans are nullified

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?

Vapor / Other storage drivers Support

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?

After Emoji No Space

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?"

Purify is stripping ckeditor <oembed> custome tags

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.

Undefined variable: array

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?

Purify in form request

Hello,
Could you please give me some hint how I can use Purify in form request?

Regards

Iframe allowfullscreen not enabled

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.

image

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.