BaseHtmlPurifier.php 1.99 KB
Newer Older
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Carsten Brandt committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5 6
 * @license http://www.yiiframework.com/license/
 */
Carsten Brandt committed
7

8
namespace yii\helpers;
9 10

/**
11
 * BaseHtmlPurifier provides concrete implementation for [[HtmlPurifier]].
12
 *
13
 * Do not use BaseHtmlPurifier. Use [[HtmlPurifier]] instead.
14 15 16 17
 *
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @since 2.0
 */
18
class BaseHtmlPurifier
19
{
20 21
    /**
     * Passes markup through HTMLPurifier making it safe to output to end user
22 23 24 25 26
     * 
     * @param string $content The HTML content to purify
     * @param array|\Closure|null $config The config to use for HtmlPurifier.
     * If not specified or `null` the default config will be used.
     * You can use an array or an anonymous function to provide configuration options:
27
     *
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
     * - An array will be passed to the `HTMLPurifier_Config::create()` method.
     * - An anonymous function will be called after the config was created.
     *   The signature should be: `function($config)` where `$config` will be an
     *   instance of `HTMLPurifier_Config`.
     *
     *   Here is a usage example of such a function:
     *
     *   ~~~
     *   // Allow the HTML5 data attribute `data-type` on `img` elements.
     *   $content = HtmlPurifier::process($content, function($config) {
     *     $config->getHTMLDefinition(true)
     *            ->addAttribute('img', 'data-type', 'Text');
     *   });
     * ~~~
     *
     * @return string the purified HTML content.
44 45 46
     */
    public static function process($content, $config = null)
    {
47
        $configInstance = \HTMLPurifier_Config::create($config instanceof \Closure ? null : $config);
48 49 50
        $configInstance->autoFinalize = false;
        $purifier=\HTMLPurifier::instance($configInstance);
        $purifier->config->set('Cache.SerializerPath', \Yii::$app->getRuntimePath());
51 52 53 54
        
        if ($config instanceof \Closure) {
            call_user_func($config, $configInstance);
        }
55 56 57

        return $purifier->purify($content);
    }
58
}