BaseHtmlPurifier.php 2.3 KB

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