create() public static method

Convenience constructor that creates a config object based on a mixed var
public static create ( mixed $config, HTMLPurifier_ConfigSchema $schema = null ) : HTMLPurifier_Config
$config mixed Variable that defines the state of the config object. Can be: a HTMLPurifier_Config() object, an array of directives based on loadArray(), or a string filename of an ini file.
$schema HTMLPurifier_ConfigSchema Schema object
return HTMLPurifier_Config Configured object
Ejemplo n.º 1
0
 function testLineNumbers()
 {
     //       .  .     .     .  .     .     .           .      .             .
     //       01234567890123 01234567890123 0123456789012345 0123456789012   012345
     $html = "<b>Line 1</b>\n<i>Line 2</i>\nStill Line 2<br\n/>Now Line 4\n\n<br />";
     $expect = array(0 => new HTMLPurifier_Token_Start('b'), 1 => new HTMLPurifier_Token_Text('Line 1'), 2 => new HTMLPurifier_Token_End('b'), 3 => new HTMLPurifier_Token_Text("\n"), 4 => new HTMLPurifier_Token_Start('i'), 5 => new HTMLPurifier_Token_Text('Line 2'), 6 => new HTMLPurifier_Token_End('i'), 7 => new HTMLPurifier_Token_Text("\nStill Line 2"), 8 => new HTMLPurifier_Token_Empty('br'), 9 => new HTMLPurifier_Token_Text("Now Line 4\n\n"), 10 => new HTMLPurifier_Token_Empty('br'));
     $context = new HTMLPurifier_Context();
     $config = HTMLPurifier_Config::createDefault();
     $output = $this->DirectLex->tokenizeHTML($html, $config, $context);
     $this->assertIdentical($output, $expect);
     $context = new HTMLPurifier_Context();
     $config = HTMLPurifier_Config::create(array('Core.MaintainLineNumbers' => true));
     $expect[0]->position(1, 0);
     $expect[1]->position(1, 3);
     $expect[2]->position(1, 9);
     $expect[3]->position(2, -1);
     $expect[4]->position(2, 0);
     $expect[5]->position(2, 3);
     $expect[6]->position(2, 9);
     $expect[7]->position(3, -1);
     $expect[8]->position(3, 12);
     $expect[9]->position(4, 2);
     $expect[10]->position(6, 0);
     $output = $this->DirectLex->tokenizeHTML($html, $config, $context);
     $this->assertIdentical($output, $expect);
 }
Ejemplo n.º 2
0
 /**
  * Accepts config and context and prepares them into a valid state
  * @param &$config Reference to config variable
  * @param &$context Reference to context variable
  */
 protected function prepareCommon(&$config, &$context)
 {
     $config = HTMLPurifier_Config::create($config);
     if (!$context) {
         $context = new HTMLPurifier_Context();
     }
 }
Ejemplo n.º 3
0
 public function test_setup()
 {
     $i = 0;
     // counter, helps us isolate expectations
     // initialize partial mock
     $module = new HTMLPurifier_HTMLModule_Tidy_TestForConstruct();
     $module->fixesForLevel['light'] = array('light-fix-1', 'light-fix-2');
     $module->fixesForLevel['medium'] = array('medium-fix-1', 'medium-fix-2');
     $module->fixesForLevel['heavy'] = array('heavy-fix-1', 'heavy-fix-2');
     $j = 0;
     $fixes = array('light-fix-1' => $lf1 = $j++, 'light-fix-2' => $lf2 = $j++, 'medium-fix-1' => $mf1 = $j++, 'medium-fix-2' => $mf2 = $j++, 'heavy-fix-1' => $hf1 = $j++, 'heavy-fix-2' => $hf2 = $j++);
     $module->setReturnValue('makeFixes', $fixes);
     $config = HTMLPurifier_Config::create(array('HTML.TidyLevel' => 'none'));
     $module->expectAt($i++, 'populate', array(array()));
     $module->setup($config);
     // basic levels
     $config = HTMLPurifier_Config::create(array('HTML.TidyLevel' => 'light'));
     $module->expectAt($i++, 'populate', array(array('light-fix-1' => $lf1, 'light-fix-2' => $lf2)));
     $module->setup($config);
     $config = HTMLPurifier_Config::create(array('HTML.TidyLevel' => 'heavy'));
     $module->expectAt($i++, 'populate', array(array('light-fix-1' => $lf1, 'light-fix-2' => $lf2, 'medium-fix-1' => $mf1, 'medium-fix-2' => $mf2, 'heavy-fix-1' => $hf1, 'heavy-fix-2' => $hf2)));
     $module->setup($config);
     // fine grained tuning
     $config = HTMLPurifier_Config::create(array('HTML.TidyLevel' => 'none', 'HTML.TidyAdd' => array('light-fix-1', 'medium-fix-1')));
     $module->expectAt($i++, 'populate', array(array('light-fix-1' => $lf1, 'medium-fix-1' => $mf1)));
     $module->setup($config);
     $config = HTMLPurifier_Config::create(array('HTML.TidyLevel' => 'medium', 'HTML.TidyRemove' => array('light-fix-1', 'medium-fix-1')));
     $module->expectAt($i++, 'populate', array(array('light-fix-2' => $lf2, 'medium-fix-2' => $mf2)));
     $module->setup($config);
 }
Ejemplo n.º 4
0
 protected function generateEnLanguage()
 {
     $factory = HTMLPurifier_LanguageFactory::instance();
     $config = HTMLPurifier_Config::create(array('Core.Language' => 'en'));
     $context = new HTMLPurifier_Context();
     return $factory->create($config, $context);
 }
 function test()
 {
     generate_mock_once('HTMLPurifier_URIScheme');
     $config = HTMLPurifier_Config::create(array('URI.AllowedSchemes' => 'http, telnet', 'URI.OverrideAllowedSchemes' => true));
     $context = new HTMLPurifier_Context();
     $registry = new HTMLPurifier_URISchemeRegistry();
     $this->assertIsA($registry->getScheme('http', $config, $context), 'HTMLPurifier_URIScheme_http');
     $scheme_http = new HTMLPurifier_URISchemeMock();
     $scheme_telnet = new HTMLPurifier_URISchemeMock();
     $scheme_foobar = new HTMLPurifier_URISchemeMock();
     // register a new scheme
     $registry->register('telnet', $scheme_telnet);
     $this->assertIdentical($registry->getScheme('telnet', $config, $context), $scheme_telnet);
     // overload a scheme, this is FINAL (forget about defaults)
     $registry->register('http', $scheme_http);
     $this->assertIdentical($registry->getScheme('http', $config, $context), $scheme_http);
     // when we register a scheme, it's automatically allowed
     $registry->register('foobar', $scheme_foobar);
     $this->assertIdentical($registry->getScheme('foobar', $config, $context), $scheme_foobar);
     // now, test when overriding is not allowed
     $config = HTMLPurifier_Config::create(array('URI.AllowedSchemes' => 'http, telnet', 'URI.OverrideAllowedSchemes' => false));
     $this->assertNull($registry->getScheme('foobar', $config, $context));
     // scheme not allowed and never registered
     $this->assertNull($registry->getScheme('ftp', $config, $context));
 }
Ejemplo n.º 6
0
 /**
  * Passes markup through HTMLPurifier making it safe to output to end user
  *
  * @param string $content
  * @param array|null $config
  * @return string
  */
 public static function process($content, $config = null)
 {
     $configInstance = \HTMLPurifier_Config::create($config);
     $configInstance->autoFinalize = false;
     $purifier = \HTMLPurifier::instance($configInstance);
     $purifier->config->set('Cache.SerializerPath', \Yii::$app->getRuntimePath());
     return $purifier->purify($content);
 }
Ejemplo n.º 7
0
 /**
  * @param string $html
  * @param array $config
  * @return string
  */
 protected function purifyHTML($html, $config)
 {
     $configInstance = \HTMLPurifier_Config::create($config);
     $configInstance->autoFinalize = false;
     $purifier = \HTMLPurifier::instance($configInstance);
     $purifier->config->set('Cache.SerializerPath', $this->tmpPath);
     return $purifier->purify($html);
 }
Ejemplo n.º 8
0
 public function __construct($root_dir)
 {
     $config = \HTMLPurifier_Config::create(array('Cache.SerializerPath' => $root_dir));
     $def = $config->getHTMLDefinition(true);
     $def->addAttribute('a', 'data-code', 'Text');
     $this->purifier_service = new \HTMLPurifier($config);
     $this->markdown_service = new \Parsedown();
 }
Ejemplo n.º 9
0
 public function setup()
 {
     $this->config = HTMLPurifier_Config::create(array('Core.CollectErrors' => true));
     $this->context = new HTMLPurifier_Context();
     generate_mock_once('HTMLPurifier_ErrorCollector');
     $this->collector = new HTMLPurifier_ErrorCollectorEMock();
     $this->collector->prepare($this->context);
     $this->context->register('ErrorCollector', $this->collector);
     $this->callCount = 0;
 }
Ejemplo n.º 10
0
 /**
  * Passes markup through HTMLPurifier making it safe to output to end user
  *
  * @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:
  *
  * - 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.
  */
 public static function process($content, $config = null)
 {
     $configInstance = \HTMLPurifier_Config::create($config instanceof \Closure ? null : $config);
     $configInstance->autoFinalize = false;
     $purifier = \HTMLPurifier::instance($configInstance);
     $purifier->config->set('Cache.SerializerPath', Application::$app->getRuntimePath());
     if ($config instanceof \Closure) {
         call_user_func($config, $configInstance);
     }
     return $purifier->purify($content);
 }
Ejemplo n.º 11
0
 protected static function truncateHtml($string, $count, $suffix, $wordsPerLine, $encoding)
 {
     $config = \HTMLPurifier_Config::create(null);
     $config->set('Cache.SerializerPath', \Yii::$app->getRuntimePath());
     $lexer = \HTMLPurifier_Lexer::create($config);
     $tokens = $lexer->tokenizeHTML($string, $config, null);
     $openTokens = 0;
     $totalCount = 0;
     $truncated = [];
     foreach ($tokens as $token) {
         if ($token instanceof \HTMLPurifier_Token_Start) {
             //Tag begins
             $openTokens++;
             $truncated[] = $token;
         } elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) {
             //Text
             if (false === $encoding) {
                 $token->data = self::truncateWords($token->data, ($count - $totalCount) * $wordsPerLine, '');
                 $currentWords = str_word_count($token->data);
             } else {
                 $token->data = self::truncate($token->data, ($count - $totalCount) * $wordsPerLine, '', $encoding) . ' ';
                 $currentWords = mb_strlen($token->data, $encoding);
             }
             //$totalCount += $currentWords;
             if (!$token->is_whitespace) {
                 $totalCount += intval(ceil($currentWords / $wordsPerLine));
             }
             //turn into lines
             if (1 === $currentWords) {
                 $token->data = ' ' . $token->data;
             }
             $truncated[] = $token;
         } elseif ($token instanceof \HTMLPurifier_Token_End) {
             //Tag ends
             $openTokens--;
             $truncated[] = $token;
         } elseif ($token instanceof \HTMLPurifier_Token_Empty) {
             //Self contained tags, i.e. <img/> etc.
             if ($token->name == 'img') {
                 //filter img tag
             } else {
                 $truncated[] = $token;
             }
         }
         if (0 === $openTokens && $totalCount >= $count) {
             break;
         }
     }
     $context = new \HTMLPurifier_Context();
     $generator = new \HTMLPurifier_Generator($config, $context);
     return $generator->generateFromTokens($truncated) . $suffix;
 }
Ejemplo n.º 12
0
 public function testAllowedModules()
 {
     $manager = new HTMLPurifier_HTMLModuleManager();
     $manager->doctypes->register('Fantasy Inventory 1.0', true, array('Weapons', 'Magic'));
     // register these modules so it doesn't blow up
     $weapons_module = new HTMLPurifier_HTMLModule();
     $weapons_module->name = 'Weapons';
     $manager->registerModule($weapons_module);
     $magic_module = new HTMLPurifier_HTMLModule();
     $magic_module->name = 'Magic';
     $manager->registerModule($magic_module);
     $config = HTMLPurifier_Config::create(array('HTML.CustomDoctype' => 'Fantasy Inventory 1.0', 'HTML.AllowedModules' => 'Weapons'));
     $manager->setup($config);
     $this->assertTrue(isset($manager->modules['Weapons']));
     $this->assertFalse(isset($manager->modules['Magic']));
 }
Ejemplo n.º 13
0
/**
 * Initializes the appropriate configuration from either a PHP file
 * or a module configuration value
 * @return Instance of HTMLPurifier_Config
 */
function phorum_htmlpurifier_get_config()
{
    global $PHORUM;
    $config_exists = phorum_htmlpurifier_config_file_exists();
    if ($config_exists || !isset($PHORUM['mod_htmlpurifier']['config'])) {
        $config = HTMLPurifier_Config::createDefault();
        include dirname(__FILE__) . '/config.default.php';
        if ($config_exists) {
            include dirname(__FILE__) . '/config.php';
        }
        unset($PHORUM['mod_htmlpurifier']['config']);
        // unnecessary
    } else {
        $config = HTMLPurifier_Config::create($PHORUM['mod_htmlpurifier']['config']);
    }
    return $config;
}
Ejemplo n.º 14
0
 public static function purify($var)
 {
     $external = Ajde_Core_ExternalLibs::getInstance();
     if ($external->has('HTMLPurifier')) {
         $purifier = $external->get('HTMLPurifier');
         /* @var $purifier HTMLPurifier */
         $config = HTMLPurifier_Config::createDefault();
         $config->set('AutoFormat.AutoParagraph', true);
         $config->set('AutoFormat.DisplayLinkURI', false);
         $config->set('AutoFormat.Linkify', false);
         $config->set('AutoFormat.RemoveEmpty', true);
         $config->set('AutoFormat.RemoveSpansWithoutAttributes', true);
         $config->set('CSS.AllowedProperties', '');
         $config->set('HTML.Doctype', 'XHTML 1.0 Strict');
         $config->set('URI.DisableExternalResources', true);
         $purifier->config = HTMLPurifier_Config::create($config);
         return $purifier->purify($var);
     } else {
         return self::clean($var);
     }
 }
Ejemplo n.º 15
0
 /**
  * Truncate a string while preserving the HTML.
  * 
  * @param string $string The string to truncate
  * @param integer $count
  * @param string $suffix String to append to the end of the truncated string.
  * @param string|boolean $encoding
  * @return string
  * @since 2.0.1
  */
 protected static function truncateHtml($string, $count, $suffix, $encoding = false)
 {
     $config = \HTMLPurifier_Config::create(null);
     $lexer = \HTMLPurifier_Lexer::create($config);
     $tokens = $lexer->tokenizeHTML($string, $config, null);
     $openTokens = 0;
     $totalCount = 0;
     $truncated = [];
     foreach ($tokens as $token) {
         if ($token instanceof \HTMLPurifier_Token_Start) {
             //Tag begins
             $openTokens++;
             $truncated[] = $token;
         } else {
             if ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) {
                 //Text
                 if (false === $encoding) {
                     $token->data = self::truncateWords($token->data, $count - $totalCount, '');
                     $currentCount = str_word_count($token->data);
                 } else {
                     $token->data = self::truncate($token->data, $count - $totalCount, '', $encoding) . ' ';
                     $currentCount = mb_strlen($token->data, $encoding);
                 }
                 $totalCount += $currentCount;
                 if (1 === $currentCount) {
                     $token->data = ' ' . $token->data;
                 }
                 $truncated[] = $token;
             } else {
                 if ($token instanceof \HTMLPurifier_Token_End) {
                     //Tag ends
                     $openTokens--;
                     $truncated[] = $token;
                 } else {
                     if ($token instanceof \HTMLPurifier_Token_Empty) {
                         //Self contained tags, i.e. <img/> etc.
                         $truncated[] = $token;
                     }
                 }
             }
         }
         if (0 === $openTokens && $totalCount >= $count) {
             break;
         }
     }
     $context = new \HTMLPurifier_Context();
     $generator = new \HTMLPurifier_Generator($config, $context);
     return $generator->generateFromTokens($truncated) . $suffix;
 }
Ejemplo n.º 16
0
 /**
  * Loads configuration values from $_GET/$_POST that were posted
  * via ConfigForm
  * @param $array $_GET or $_POST array to import
  * @param $index Index/name that the config variables are in
  * @param $allowed List of allowed namespaces/directives 
  * @param $mq_fix Boolean whether or not to enable magic quotes fix
  * @static
  */
 static function loadArrayFromForm($array, $index, $allowed = true, $mq_fix = true)
 {
     $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix);
     $config = HTMLPurifier_Config::create($ret);
     return $config;
 }
 function test_Allowed()
 {
     $config1 = HTMLPurifier_Config::create(array('HTML.AllowedElements' => array('b', 'i', 'p', 'a'), 'HTML.AllowedAttributes' => array('a@href', '*@id')));
     $config2 = HTMLPurifier_Config::create(array('HTML.Allowed' => 'b,i,p,a[href],*[id]'));
     $this->assertEqual($config1->getHTMLDefinition(), $config2->getHTMLDefinition());
 }
Ejemplo n.º 18
0
 public function __construct()
 {
     $this->parser = new \Parsedown();
     $purifierConfig = \HTMLPurifier_Config::create(array('Cache.DefinitionImpl' => null));
     $this->purifier = new \HTMLPurifier($purifierConfig);
 }
Ejemplo n.º 19
0
 /**
  * Filters an HTML snippet/document to be XSS-free and standards-compliant.
  * 
  * @param $html String of HTML to purify
  * @param $config HTMLPurifier_Config object for this operation, if omitted,
  *                defaults to the config object specified during this
  *                object's construction. The parameter can also be any type
  *                that HTMLPurifier_Config::create() supports.
  * @return Purified HTML
  */
 function purify($html, $config = null)
 {
     $config = $config ? HTMLPurifier_Config::create($config) : $this->config;
     // implementation is partially environment dependant, partially
     // configuration dependant
     $lexer = HTMLPurifier_Lexer::create($config);
     $context = new HTMLPurifier_Context();
     // our friendly neighborhood generator, all primed with configuration too!
     $this->generator->generateFromTokens(array(), $config, $context);
     $context->register('Generator', $this->generator);
     // set up global context variables
     if ($config->get('Core', 'CollectErrors')) {
         // may get moved out if other facilities use it
         $language_factory = HTMLPurifier_LanguageFactory::instance();
         $language = $language_factory->create($config, $context);
         $context->register('Locale', $language);
         $error_collector = new HTMLPurifier_ErrorCollector($context);
         $context->register('ErrorCollector', $error_collector);
     }
     $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context);
     for ($i = 0, $size = count($this->filters); $i < $size; $i++) {
         $html = $this->filters[$i]->preFilter($html, $config, $context);
     }
     // purified HTML
     $html = $this->generator->generateFromTokens($this->strategy->execute($lexer->tokenizeHTML($html, $config, $context), $config, $context), $config, $context);
     for ($i = $size - 1; $i >= 0; $i--) {
         $html = $this->filters[$i]->postFilter($html, $config, $context);
     }
     $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context);
     $this->context =& $context;
     return $html;
 }
Ejemplo n.º 20
0
 /**
  * Truncate a string while preserving the HTML.
  *
  * @param string $string The string to truncate
  * @param int $count
  * @param string $suffix String to append to the end of the truncated string.
  * @param string|bool $encoding
  * @return string
  * @since 2.0.1
  */
 protected static function truncateHtml($string, $count, $suffix, $encoding = false)
 {
     $config = \HTMLPurifier_Config::create(null);
     $config->set('Cache.SerializerPath', \Yii::$app->getRuntimePath());
     $lexer = \HTMLPurifier_Lexer::create($config);
     $tokens = $lexer->tokenizeHTML($string, $config, null);
     $openTokens = 0;
     $totalCount = 0;
     $truncated = [];
     foreach ($tokens as $token) {
         if ($token instanceof \HTMLPurifier_Token_Start) {
             //Tag begins
             $openTokens++;
             $truncated[] = $token;
         } elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) {
             //Text
             if (false === $encoding) {
                 preg_match('/^(\\s*)/um', $token->data, $prefixSpace) ?: ($prefixSpace = ['', '']);
                 $token->data = $prefixSpace[1] . self::truncateWords(ltrim($token->data), $count - $totalCount, '');
                 $currentCount = self::countWords($token->data);
             } else {
                 $token->data = self::truncate($token->data, $count - $totalCount, '', $encoding);
                 $currentCount = mb_strlen($token->data, $encoding);
             }
             $totalCount += $currentCount;
             $truncated[] = $token;
         } elseif ($token instanceof \HTMLPurifier_Token_End) {
             //Tag ends
             $openTokens--;
             $truncated[] = $token;
         } elseif ($token instanceof \HTMLPurifier_Token_Empty) {
             //Self contained tags, i.e. <img/> etc.
             $truncated[] = $token;
         }
         if (0 === $openTokens && $totalCount >= $count) {
             break;
         }
     }
     $context = new \HTMLPurifier_Context();
     $generator = new \HTMLPurifier_Generator($config, $context);
     return $generator->generateFromTokens($truncated) . ($totalCount >= $count ? $suffix : '');
 }
Ejemplo n.º 21
0
 public function test_loadArrayFromForm()
 {
     $this->schema->add('Pancake.Mix', 'buttermilk', 'string', false);
     $this->schema->add('Pancake.Served', true, 'bool', false);
     $this->schema->add('Toppings.Syrup', true, 'bool', false);
     $this->schema->add('Toppings.Flavor', 'maple', 'string', false);
     $this->schema->add('Toppings.Strawberries', 3, 'int', false);
     $this->schema->add('Toppings.Calories', 2000, 'int', true);
     $this->schema->add('Toppings.DefinitionID', null, 'string', true);
     $this->schema->add('Toppings.DefinitionRev', 1, 'int', false);
     $this->schema->add('Toppings.Protected', 1, 'int', false);
     $get = array('breakfast' => array('Pancake.Mix' => 'nasty', 'Pancake.Served' => '0', 'Toppings.Syrup' => '0', 'Toppings.Flavor' => "juice", 'Toppings.Strawberries' => '999', 'Toppings.Calories' => '', 'Null_Toppings.Calories' => '1', 'Toppings.DefinitionID' => '<argh>', 'Toppings.DefinitionRev' => '65', 'Toppings.Protected' => '4'));
     $config_expect = HTMLPurifier_Config::create(array('Pancake.Served' => false, 'Toppings.Syrup' => false, 'Toppings.Flavor' => "juice", 'Toppings.Strawberries' => 999, 'Toppings.Calories' => null), $this->schema);
     $config_result = HTMLPurifier_Config::loadArrayFromForm($get, 'breakfast', array('Pancake.Served', 'Toppings', '-Toppings.Protected'), false, $this->schema);
     $this->assertEqual($config_expect, $config_result);
     /*
     MAGIC QUOTES NOT TESTED!!!
     
     $get = array(
         'breakfast' => array(
             'Pancake.Mix' => 'n\\asty'
         )
     );
     $config_expect = HTMLPurifier_Config::create(array(
         'Pancake.Mix' => 'n\\asty'
     ));
     $config_result = HTMLPurifier_Config::loadArrayFromForm($get, 'breakfast', true, false);
     $this->assertEqual($config_expect, $config_result);
     */
 }
Ejemplo n.º 22
0
 function test_addElement()
 {
     $config = HTMLPurifier_Config::create(array('HTML.DefinitionID' => 'HTMLPurifier_HTMLDefinitionTest->test_addElement'));
     $def = $config->getHTMLDefinition(true);
     $def->addElement('marquee', 'Inline', 'Inline', 'Common', array('width' => 'Length'));
     $purifier = new HTMLPurifier($config);
     $input = '<span><marquee width="50">Foobar</marquee></span>';
     $output = $purifier->purify($input);
     $this->assertIdentical($input, $output);
 }
 /**
  * use html purifier to remove 'bad' tags/attributes from html body
  *
  * @param string $_content
  * @param string $messageId
  * @return string
  */
 protected function _purifyBodyContent($_content, $messageId)
 {
     if (!defined('HTMLPURIFIER_PREFIX')) {
         define('HTMLPURIFIER_PREFIX', realpath(dirname(__FILE__) . '/../../library/HTMLPurifier'));
     }
     $config = Tinebase_Core::getConfig();
     $path = $config->caching && $config->caching->active && $config->caching->path ? $config->caching->path : Tinebase_Core::getTempDir();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Purifying html body. (cache path: ' . $path . ')');
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Current mem usage before purify: ' . memory_get_usage() / 1024 / 1024);
     }
     // add custom schema for passing message id to URIScheme
     $configSchema = HTMLPurifier_ConfigSchema::makeFromSerial();
     $configSchema->add('Felamimail.messageId', NULL, 'string', TRUE);
     $config = HTMLPurifier_Config::create(NULL, $configSchema);
     $config->set('HTML.DefinitionID', 'purify message body contents');
     $config->set('HTML.DefinitionRev', 1);
     // @see: http://htmlpurifier.org/live/configdoc/plain.html#Attr.EnableID
     $config->set('Attr.EnableID', TRUE);
     $config->set('Attr.IDPrefix', 'felamimail_inline_');
     // @see: http://htmlpurifier.org/live/configdoc/plain.html#HTML.TidyLevel
     $config->set('HTML.TidyLevel', 'heavy');
     // some config values to consider
     /*
     $config->set('Attr.EnableID', true);
     $config->set('Attr.ClassUseCDATA', true);
     $config->set('CSS.AllowTricky', true);
     */
     $config->set('Cache.SerializerPath', $path);
     $config->set('URI.AllowedSchemes', array('http' => true, 'https' => true, 'mailto' => true, 'data' => true, 'cid' => true));
     $config->set('Felamimail.messageId', $messageId);
     $this->_transformBodyTags($config);
     // add uri filter
     $uri = $config->getDefinition('URI');
     $uri->addFilter(new Felamimail_HTMLPurifier_URIFilter_TransformURI(), $config);
     // add cid uri scheme
     require_once dirname(dirname(__FILE__)) . '/HTMLPurifier/URIScheme/cid.php';
     $purifier = new HTMLPurifier($config);
     $content = $purifier->purify($_content);
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Current mem usage after purify: ' . memory_get_usage() / 1024 / 1024);
     }
     return $content;
 }
Ejemplo n.º 24
0
 /**
  * Filters an HTML snippet/document to be XSS-free and standards-compliant.
  *
  * @param $html String of HTML to purify
  * @param $config HTMLPurifier_Config object for this operation, if omitted,
  *                defaults to the config object specified during this
  *                object's construction. The parameter can also be any type
  *                that HTMLPurifier_Config::create() supports.
  * @return Purified HTML
  */
 public function purify($html, $config = null)
 {
     // :TODO: make the config merge in, instead of replace
     $config = $config ? HTMLPurifier_Config::create($config) : $this->config;
     // implementation is partially environment dependant, partially
     // configuration dependant
     $lexer = HTMLPurifier_Lexer::create($config);
     $context = new HTMLPurifier_Context();
     // setup HTML generator
     $this->generator = new HTMLPurifier_Generator($config, $context);
     $context->register('Generator', $this->generator);
     // set up global context variables
     if ($config->get('Core.CollectErrors')) {
         // may get moved out if other facilities use it
         $language_factory = HTMLPurifier_LanguageFactory::instance();
         $language = $language_factory->create($config, $context);
         $context->register('Locale', $language);
         $error_collector = new HTMLPurifier_ErrorCollector($context);
         $context->register('ErrorCollector', $error_collector);
     }
     // setup id_accumulator context, necessary due to the fact that
     // AttrValidator can be called from many places
     $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);
     $context->register('IDAccumulator', $id_accumulator);
     $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context);
     // setup filters
     $filter_flags = $config->getBatch('Filter');
     $custom_filters = $filter_flags['Custom'];
     unset($filter_flags['Custom']);
     $filters = array();
     foreach ($filter_flags as $filter => $flag) {
         if (!$flag) {
             continue;
         }
         if (strpos($filter, '.') !== false) {
             continue;
         }
         $class = "HTMLPurifier_Filter_{$filter}";
         $filters[] = new $class();
     }
     foreach ($custom_filters as $filter) {
         // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat
         $filters[] = $filter;
     }
     $filters = array_merge($filters, $this->filters);
     // maybe prepare(), but later
     for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) {
         $html = $filters[$i]->preFilter($html, $config, $context);
     }
     // purified HTML
     $html = $this->generator->generateFromTokens($this->strategy->execute($lexer->tokenizeHTML($html, $config, $context), $config, $context));
     for ($i = $filter_size - 1; $i >= 0; $i--) {
         $html = $filters[$i]->postFilter($html, $config, $context);
     }
     $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context);
     $this->context =& $context;
     return $html;
 }
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Laravel\IoC::singleton('HTMLPurifier', function () {
    if (!class_exists('HTMLPurifier_Config', false)) {
        if (Config::get('purifier.preload')) {
            // Load the all of HTML Purifier right now.
            // This increases performance with a slight hit to memory usage.
            require dirname(__FILE__) . '/library/HTMLPurifier.includes.php';
        }
        // Load the HTML Purifier auto loader
        require dirname(__FILE__) . '/library/HTMLPurifier.auto.php';
    }
    // Create a new configuration object
    $config = HTMLPurifier_Config::createDefault();
    if (!Config::get('purifier.finalize')) {
        // Allow configuration to be modified
        $config->autoFinalize = false;
    }
    // Use the same character set as Laravel
    $config->set('Core.Encoding', Config::get('application.encoding'));
    if (is_array($settings = Config::get('purifier.settings'))) {
        // Load the settings
        $config->loadArray($settings);
    }
    // Configure additional options
    $config = HTMLPurifier_Config::create($config);
    // Return the purifier instance
    return new HTMLPurifier($config);
});
 protected function getExerciseHtmlPurifier_Config_DefaultService()
 {
     return $this->services['exercise_html_purifier.config.default'] = \HTMLPurifier_Config::create(array('Cache.SerializerPath' => __DIR__ . '/htmlpurifier'));
 }
 /**
  * Loads configuration values from $_GET/$_POST that were posted
  * via ConfigForm
  *
  * @param array $array $_GET or $_POST array to import
  * @param string|bool $index Index/name that the config variables are in
  * @param array|bool $allowed List of allowed namespaces/directives
  * @param bool $mq_fix Boolean whether or not to enable magic quotes fix
  * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy
  *
  * @return mixed
  */
 public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null)
 {
     $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
     $config = HTMLPurifier_Config::create($ret, $schema);
     return $config;
 }
Ejemplo n.º 28
0
 /**
  * Loads configuration values from $_GET/$_POST that were posted
  * via ConfigForm
  *
  * @param $array $_GET or $_POST array to import
  * @param $index Index/name that the config variables are in
  * @param $allowed List of allowed namespaces/directives
  * @param $mq_fix Boolean whether or not to enable magic quotes fix
  * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
  */
 public static function loadArrayFromForm($array, $index = FALSE, $allowed = TRUE, $mq_fix = TRUE, $schema = NULL)
 {
     $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
     $config = HTMLPurifier_Config::create($ret, $schema);
     return $config;
 }