当前位置: 首页>>代码示例>>PHP>>正文


PHP HTMLPurifier_Generator类代码示例

本文整理汇总了PHP中HTMLPurifier_Generator的典型用法代码示例。如果您正苦于以下问题:PHP HTMLPurifier_Generator类的具体用法?PHP HTMLPurifier_Generator怎么用?PHP HTMLPurifier_Generator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了HTMLPurifier_Generator类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: truncateHtml

 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;
 }
开发者ID:gouchaoer,项目名称:yii2-starter-kit,代码行数:52,代码来源:StringHelper.php

示例2: execute

 /**
  * @param HTMLPurifier_Token[] $tokens
  * @param HTMLPurifier_Config $config
  * @param HTMLPurifier_Context $context
  * @return array|HTMLPurifier_Token[]
  */
 public function execute($tokens, $config, $context)
 {
     $definition = $config->getHTMLDefinition();
     $generator = new HTMLPurifier_Generator($config, $context);
     $result = array();
     $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
     $remove_invalid_img = $config->get('Core.RemoveInvalidImg');
     // currently only used to determine if comments should be kept
     $trusted = $config->get('HTML.Trusted');
     $comment_lookup = $config->get('HTML.AllowedComments');
     $comment_regexp = $config->get('HTML.AllowedCommentsRegexp');
     $check_comments = $comment_lookup !== array() || $comment_regexp !== null;
     $remove_script_contents = $config->get('Core.RemoveScriptContents');
     $hidden_elements = $config->get('Core.HiddenElements');
     // remove script contents compatibility
     if ($remove_script_contents === true) {
         $hidden_elements['script'] = true;
     } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) {
         unset($hidden_elements['script']);
     }
     $attr_validator = new HTMLPurifier_AttrValidator();
     // removes tokens until it reaches a closing tag with its value
     $remove_until = false;
     // converts comments into text tokens when this is equal to a tag name
     $textify_comments = false;
     $token = false;
     $context->register('CurrentToken', $token);
     $e = false;
     if ($config->get('Core.CollectErrors')) {
         $e =& $context->get('ErrorCollector');
     }
     foreach ($tokens as $token) {
         if ($remove_until) {
             if (empty($token->is_tag) || $token->name !== $remove_until) {
                 continue;
             }
         }
         if (!empty($token->is_tag)) {
             // DEFINITION CALL
             // before any processing, try to transform the element
             if (isset($definition->info_tag_transform[$token->name])) {
                 $original_name = $token->name;
                 // there is a transformation for this tag
                 // DEFINITION CALL
                 $token = $definition->info_tag_transform[$token->name]->transform($token, $config, $context);
                 if ($e) {
                     $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name);
                 }
             }
             if (isset($definition->info[$token->name])) {
                 // mostly everything's good, but
                 // we need to make sure required attributes are in order
                 if (($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) && $definition->info[$token->name]->required_attr && ($token->name != 'img' || $remove_invalid_img)) {
                     $attr_validator->validateToken($token, $config, $context);
                     $ok = true;
                     foreach ($definition->info[$token->name]->required_attr as $name) {
                         if (!isset($token->attr[$name])) {
                             $ok = false;
                             break;
                         }
                     }
                     if (!$ok) {
                         if ($e) {
                             $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Missing required attribute', $name);
                         }
                         continue;
                     }
                     $token->armor['ValidateAttributes'] = true;
                 }
                 if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) {
                     $textify_comments = $token->name;
                 } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) {
                     $textify_comments = false;
                 }
             } elseif ($escape_invalid_tags) {
                 // invalid tag, generate HTML representation and insert in
                 if ($e) {
                     $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text');
                 }
                 $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token));
             } else {
                 // check if we need to destroy all of the tag's children
                 // CAN BE GENERICIZED
                 if (isset($hidden_elements[$token->name])) {
                     if ($token instanceof HTMLPurifier_Token_Start) {
                         $remove_until = $token->name;
                     } elseif ($token instanceof HTMLPurifier_Token_Empty) {
                         // do nothing: we're still looking
                     } else {
                         $remove_until = false;
                     }
                     if ($e) {
                         $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed');
                     }
//.........这里部分代码省略.........
开发者ID:dingdong2310,项目名称:g5_theme,代码行数:101,代码来源:HTMLPurifier.standalone.php

示例3: assertGeneration

 protected function assertGeneration($tokens, $expect)
 {
     $generator = new HTMLPurifier_Generator($this->config, $this->context);
     $result = $generator->generateFromTokens($tokens);
     $this->assertIdentical($expect, $result);
 }
开发者ID:Jaaviieer,项目名称:PrograWeb,代码行数:6,代码来源:GeneratorTest.php

示例4: execute

 function execute($tokens, $config, &$context)
 {
     $definition = $config->getHTMLDefinition();
     $generator = new HTMLPurifier_Generator();
     $result = array();
     $escape_invalid_tags = $config->get('Core', 'EscapeInvalidTags');
     $remove_invalid_img = $config->get('Core', 'RemoveInvalidImg');
     $remove_script_contents = $config->get('Core', 'RemoveScriptContents');
     $hidden_elements = $config->get('Core', 'HiddenElements');
     // remove script contents compatibility
     if ($remove_script_contents === true) {
         $hidden_elements['script'] = true;
     } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) {
         unset($hidden_elements['script']);
     }
     $attr_validator = new HTMLPurifier_AttrValidator();
     // removes tokens until it reaches a closing tag with its value
     $remove_until = false;
     // converts comments into text tokens when this is equal to a tag name
     $textify_comments = false;
     $token = false;
     $context->register('CurrentToken', $token);
     $e = false;
     if ($config->get('Core', 'CollectErrors')) {
         $e =& $context->get('ErrorCollector');
     }
     foreach ($tokens as $token) {
         if ($remove_until) {
             if (empty($token->is_tag) || $token->name !== $remove_until) {
                 continue;
             }
         }
         if (!empty($token->is_tag)) {
             // DEFINITION CALL
             // before any processing, try to transform the element
             if (isset($definition->info_tag_transform[$token->name])) {
                 $original_name = $token->name;
                 // there is a transformation for this tag
                 // DEFINITION CALL
                 $token = $definition->info_tag_transform[$token->name]->transform($token, $config, $context);
                 if ($e) {
                     $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name);
                 }
             }
             if (isset($definition->info[$token->name])) {
                 // mostly everything's good, but
                 // we need to make sure required attributes are in order
                 if (($token->type === 'start' || $token->type === 'empty') && $definition->info[$token->name]->required_attr && ($token->name != 'img' || $remove_invalid_img)) {
                     $attr_validator->validateToken($token, $config, $context);
                     $ok = true;
                     foreach ($definition->info[$token->name]->required_attr as $name) {
                         if (!isset($token->attr[$name])) {
                             $ok = false;
                             break;
                         }
                     }
                     if (!$ok) {
                         if ($e) {
                             $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Missing required attribute', $name);
                         }
                         continue;
                     }
                     $token->armor['ValidateAttributes'] = true;
                 }
                 if (isset($hidden_elements[$token->name]) && $token->type == 'start') {
                     $textify_comments = $token->name;
                 } elseif ($token->name === $textify_comments && $token->type == 'end') {
                     $textify_comments = false;
                 }
             } elseif ($escape_invalid_tags) {
                 // invalid tag, generate HTML representation and insert in
                 if ($e) {
                     $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text');
                 }
                 $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token, $config, $context));
             } else {
                 // check if we need to destroy all of the tag's children
                 // CAN BE GENERICIZED
                 if (isset($hidden_elements[$token->name])) {
                     if ($token->type == 'start') {
                         $remove_until = $token->name;
                     } elseif ($token->type == 'empty') {
                         // do nothing: we're still looking
                     } else {
                         $remove_until = false;
                     }
                     if ($e) {
                         $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed');
                     }
                 } else {
                     if ($e) {
                         $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed');
                     }
                 }
                 continue;
             }
         } elseif ($token->type == 'comment') {
             // textify comments in script tags when they are allowed
             if ($textify_comments !== false) {
                 $data = $token->data;
//.........这里部分代码省略.........
开发者ID:fferriere,项目名称:web,代码行数:101,代码来源:RemoveForeignElements.php

示例5: truncateHtml

 /**
  * 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;
 }
开发者ID:aoopvn,项目名称:EduSec4.0.0,代码行数:59,代码来源:BaseStringHelper.php

示例6: execute

 public function execute($tokens, $config, $context)
 {
     $definition = $config->getHTMLDefinition();
     // local variables
     $generator = new HTMLPurifier_Generator($config, $context);
     $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
     $e = $context->get('ErrorCollector', true);
     $t = false;
     // token index
     $i = false;
     // injector index
     $token = false;
     // the current token
     $reprocess = false;
     // whether or not to reprocess the same token
     $stack = array();
     // member variables
     $this->stack =& $stack;
     $this->t =& $t;
     $this->tokens =& $tokens;
     $this->config = $config;
     $this->context = $context;
     // context variables
     $context->register('CurrentNesting', $stack);
     $context->register('InputIndex', $t);
     $context->register('InputTokens', $tokens);
     $context->register('CurrentToken', $token);
     // -- begin INJECTOR --
     $this->injectors = array();
     $injectors = $config->getBatch('AutoFormat');
     $def_injectors = $definition->info_injector;
     $custom_injectors = $injectors['Custom'];
     unset($injectors['Custom']);
     // special case
     foreach ($injectors as $injector => $b) {
         // XXX: Fix with a legitimate lookup table of enabled filters
         if (strpos($injector, '.') !== false) {
             continue;
         }
         $injector = "HTMLPurifier_Injector_{$injector}";
         if (!$b) {
             continue;
         }
         $this->injectors[] = new $injector();
     }
     foreach ($def_injectors as $injector) {
         // assumed to be objects
         $this->injectors[] = $injector;
     }
     foreach ($custom_injectors as $injector) {
         if (is_string($injector)) {
             $injector = "HTMLPurifier_Injector_{$injector}";
             $injector = new $injector();
         }
         $this->injectors[] = $injector;
     }
     // give the injectors references to the definition and context
     // variables for performance reasons
     foreach ($this->injectors as $ix => $injector) {
         $error = $injector->prepare($config, $context);
         if (!$error) {
             continue;
         }
         array_splice($this->injectors, $ix, 1);
         // rm the injector
         trigger_error("Cannot enable {$injector->name} injector because {$error} is not allowed", E_USER_WARNING);
     }
     // -- end INJECTOR --
     // a note on punting:
     //      In order to reduce code duplication, whenever some code needs
     //      to make HTML changes in order to make things "correct", the
     //      new HTML gets sent through the purifier, regardless of its
     //      status. This means that if we add a start token, because it
     //      was totally necessary, we don't have to update nesting; we just
     //      punt ($reprocess = true; continue;) and it does that for us.
     // isset is in loop because $tokens size changes during loop exec
     for ($t = 0; $t == 0 || isset($tokens[$t - 1]); $reprocess ? $reprocess = false : $t++) {
         // check for a rewind
         if (is_int($i) && $i >= 0) {
             // possibility: disable rewinding if the current token has a
             // rewind set on it already. This would offer protection from
             // infinite loop, but might hinder some advanced rewinding.
             $rewind_to = $this->injectors[$i]->getRewind();
             if (is_int($rewind_to) && $rewind_to < $t) {
                 if ($rewind_to < 0) {
                     $rewind_to = 0;
                 }
                 while ($t > $rewind_to) {
                     $t--;
                     $prev = $tokens[$t];
                     // indicate that other injectors should not process this token,
                     // but we need to reprocess it
                     unset($prev->skip[$i]);
                     $prev->rewind = $i;
                     if ($prev instanceof HTMLPurifier_Token_Start) {
                         array_pop($this->stack);
                     } elseif ($prev instanceof HTMLPurifier_Token_End) {
                         $this->stack[] = $prev->start;
                     }
                 }
//.........这里部分代码省略.........
开发者ID:hiwilson,项目名称:gallery3,代码行数:101,代码来源:MakeWellFormed.php

示例7: execute

 public function execute($tokens, $config, $context)
 {
     $definition = $config->getHTMLDefinition();
     // local variables
     $result = array();
     $generator = new HTMLPurifier_Generator();
     $escape_invalid_tags = $config->get('Core', 'EscapeInvalidTags');
     $e = $context->get('ErrorCollector', true);
     // member variables
     $this->currentNesting = array();
     $this->inputIndex = false;
     $this->inputTokens =& $tokens;
     $this->outputTokens =& $result;
     // context variables
     $context->register('CurrentNesting', $this->currentNesting);
     $context->register('InputIndex', $this->inputIndex);
     $context->register('InputTokens', $tokens);
     // -- begin INJECTOR --
     $this->injectors = array();
     $injectors = $config->getBatch('AutoFormat');
     $custom_injectors = $injectors['Custom'];
     unset($injectors['Custom']);
     // special case
     foreach ($injectors as $injector => $b) {
         $injector = "HTMLPurifier_Injector_{$injector}";
         if (!$b) {
             continue;
         }
         $this->injectors[] = new $injector();
     }
     foreach ($custom_injectors as $injector) {
         if (is_string($injector)) {
             $injector = "HTMLPurifier_Injector_{$injector}";
             $injector = new $injector();
         }
         $this->injectors[] = $injector;
     }
     // array index of the injector that resulted in an array
     // substitution. This enables processTokens() to know which
     // injectors are affected by the added tokens and which are
     // not (namely, the ones after the current injector are not
     // affected)
     $this->currentInjector = false;
     // give the injectors references to the definition and context
     // variables for performance reasons
     foreach ($this->injectors as $i => $injector) {
         $error = $injector->prepare($config, $context);
         if (!$error) {
             continue;
         }
         array_splice($this->injectors, $i, 1);
         // rm the injector
         trigger_error("Cannot enable {$injector->name} injector because {$error} is not allowed", E_USER_WARNING);
     }
     // warning: most foreach loops follow the convention $i => $injector.
     // Don't define these as loop-wide variables, please!
     // -- end INJECTOR --
     $token = false;
     $context->register('CurrentToken', $token);
     // isset is in loop because $tokens size changes during loop exec
     for ($this->inputIndex = 0; isset($tokens[$this->inputIndex]); $this->inputIndex++) {
         // if all goes well, this token will be passed through unharmed
         $token = $tokens[$this->inputIndex];
         //printTokens($tokens, $this->inputIndex);
         foreach ($this->injectors as $injector) {
             if ($injector->skip > 0) {
                 $injector->skip--;
             }
         }
         // quick-check: if it's not a tag, no need to process
         if (empty($token->is_tag)) {
             if ($token->type === 'text') {
                 // injector handler code; duplicated for performance reasons
                 foreach ($this->injectors as $i => $injector) {
                     if (!$injector->skip) {
                         $injector->handleText($token);
                     }
                     if (is_array($token)) {
                         $this->currentInjector = $i;
                         break;
                     }
                 }
             }
             $this->processToken($token, $config, $context);
             continue;
         }
         $info = $definition->info[$token->name]->child;
         // quick tag checks: anything that's *not* an end tag
         $ok = false;
         if ($info->type == 'empty' && $token->type == 'start') {
             // test if it claims to be a start tag but is empty
             $token = new HTMLPurifier_Token_Empty($token->name, $token->attr);
             $ok = true;
         } elseif ($info->type != 'empty' && $token->type == 'empty') {
             // claims to be empty but really is a start tag
             $token = array(new HTMLPurifier_Token_Start($token->name, $token->attr), new HTMLPurifier_Token_End($token->name));
             $ok = true;
         } elseif ($token->type == 'empty') {
             // real empty token
             $ok = true;
//.........这里部分代码省略.........
开发者ID:jbzdak,项目名称:wikidot,代码行数:101,代码来源:MakeWellFormed.php

示例8: validateChildren

 public function validateChildren($tokens_of_children, $config, $context)
 {
     // Flag for subclasses
     $this->whitespace = false;
     // if there are no tokens, delete parent node
     if (empty($tokens_of_children)) {
         return false;
     }
     // the new set of children
     $result = array();
     // current depth into the nest
     $nesting = 0;
     // whether or not we're deleting a node
     $is_deleting = false;
     // whether or not parsed character data is allowed
     // this controls whether or not we silently drop a tag
     // or generate escaped HTML from it
     $pcdata_allowed = isset($this->elements['#PCDATA']);
     // a little sanity check to make sure it's not ALL whitespace
     $all_whitespace = true;
     // some configuration
     $escape_invalid_children = $config->get('Core', 'EscapeInvalidChildren');
     // generator
     $gen = new HTMLPurifier_Generator($config, $context);
     foreach ($tokens_of_children as $token) {
         if (!empty($token->is_whitespace)) {
             $result[] = $token;
             continue;
         }
         $all_whitespace = false;
         // phew, we're not talking about whitespace
         $is_child = $nesting == 0;
         if ($token instanceof HTMLPurifier_Token_Start) {
             $nesting++;
         } elseif ($token instanceof HTMLPurifier_Token_End) {
             $nesting--;
         }
         if ($is_child) {
             $is_deleting = false;
             if (!isset($this->elements[$token->name])) {
                 $is_deleting = true;
                 if ($pcdata_allowed && $token instanceof HTMLPurifier_Token_Text) {
                     $result[] = $token;
                 } elseif ($pcdata_allowed && $escape_invalid_children) {
                     $result[] = new HTMLPurifier_Token_Text($gen->generateFromToken($token));
                 }
                 continue;
             }
         }
         if (!$is_deleting || $pcdata_allowed && $token instanceof HTMLPurifier_Token_Text) {
             $result[] = $token;
         } elseif ($pcdata_allowed && $escape_invalid_children) {
             $result[] = new HTMLPurifier_Token_Text($gen->generateFromToken($token));
         } else {
             // drop silently
         }
     }
     if (empty($result)) {
         return false;
     }
     if ($all_whitespace) {
         $this->whitespace = true;
         return false;
     }
     if ($tokens_of_children == $result) {
         return true;
     }
     return $result;
 }
开发者ID:BackupTheBerlios,项目名称:oos-svn,代码行数:69,代码来源:Required.php

示例9: printTokens

/**
 * Debugging function that prints tokens in a user-friendly manner.
 */
function printTokens($tokens, $index = null)
{
    $string = '<pre>';
    $generator = new HTMLPurifier_Generator(HTMLPurifier_Config::createDefault(), new HTMLPurifier_Context());
    foreach ($tokens as $i => $token) {
        if ($index === $i) {
            $string .= '[<strong>';
        }
        $string .= "<sup>{$i}</sup>";
        $string .= $generator->escape($generator->generateFromToken($token));
        if ($index === $i) {
            $string .= '</strong>]';
        }
    }
    $string .= '</pre>';
    echo $string;
}
开发者ID:laiello,项目名称:lion-framework,代码行数:20,代码来源:common.php

示例10: generate

 /**
  * Generate textual HTML from tokens
  */
 protected function generate($tokens)
 {
     $generator = new HTMLPurifier_Generator($this->config, $this->context);
     return $generator->generateFromTokens($tokens);
 }
开发者ID:Jaaviieer,项目名称:PrograWeb,代码行数:8,代码来源:ComplexHarness.php

示例11: truncateHtml

 /**
  * 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 : '');
 }
开发者ID:arogachev,项目名称:yii2,代码行数:52,代码来源:BaseStringHelper.php

示例12: execute

 public function execute($tokens, $config, $context)
 {
     $definition = $config->getHTMLDefinition();
     $generator = new HTMLPurifier_Generator($config, $context);
     $result = array();
     $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
     $remove_invalid_img = $config->get('Core.RemoveInvalidImg');
     $trusted = $config->get('HTML.Trusted');
     $comment_lookup = $config->get('HTML.AllowedComments');
     $comment_regexp = $config->get('HTML.AllowedCommentsRegexp');
     $check_comments = $comment_lookup !== array() || $comment_regexp !== null;
     $remove_script_contents = $config->get('Core.RemoveScriptContents');
     $hidden_elements = $config->get('Core.HiddenElements');
     if ($remove_script_contents === true) {
         $hidden_elements['script'] = true;
     } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) {
         unset($hidden_elements['script']);
     }
     $attr_validator = new HTMLPurifier_AttrValidator();
     $remove_until = false;
     $textify_comments = false;
     $token = false;
     $context->register('CurrentToken', $token);
     $e = false;
     if ($config->get('Core.CollectErrors')) {
         $e =& $context->get('ErrorCollector');
     }
     foreach ($tokens as $token) {
         if ($remove_until) {
             if (empty($token->is_tag) || $token->name !== $remove_until) {
                 continue;
             }
         }
         if (!empty($token->is_tag)) {
             if (isset($definition->info_tag_transform[$token->name])) {
                 $original_name = $token->name;
                 $token = $definition->info_tag_transform[$token->name]->transform($token, $config, $context);
                 if ($e) {
                     $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name);
                 }
             }
             if (isset($definition->info[$token->name])) {
                 if (($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) && $definition->info[$token->name]->required_attr && ($token->name != 'img' || $remove_invalid_img)) {
                     $attr_validator->validateToken($token, $config, $context);
                     $ok = true;
                     foreach ($definition->info[$token->name]->required_attr as $name) {
                         if (!isset($token->attr[$name])) {
                             $ok = false;
                             break;
                         }
                     }
                     if (!$ok) {
                         if ($e) {
                             $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Missing required attribute', $name);
                         }
                         continue;
                     }
                     $token->armor['ValidateAttributes'] = true;
                 }
                 if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) {
                     $textify_comments = $token->name;
                 } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) {
                     $textify_comments = false;
                 }
             } elseif ($escape_invalid_tags) {
                 if ($e) {
                     $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text');
                 }
                 $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token));
             } else {
                 if (isset($hidden_elements[$token->name])) {
                     if ($token instanceof HTMLPurifier_Token_Start) {
                         $remove_until = $token->name;
                     } elseif ($token instanceof HTMLPurifier_Token_Empty) {
                     } else {
                         $remove_until = false;
                     }
                     if ($e) {
                         $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed');
                     }
                 } else {
                     if ($e) {
                         $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed');
                     }
                 }
                 continue;
             }
         } elseif ($token instanceof HTMLPurifier_Token_Comment) {
             if ($textify_comments !== false) {
                 $data = $token->data;
                 $token = new HTMLPurifier_Token_Text($data);
             } elseif ($trusted || $check_comments) {
                 $trailing_hyphen = false;
                 if ($e) {
                     if (substr($token->data, -1) == '-') {
                         $trailing_hyphen = true;
                     }
                 }
                 $token->data = rtrim($token->data, '-');
                 $found_double_hyphen = false;
//.........这里部分代码省略.........
开发者ID:harrylongworth,项目名称:tv-bb,代码行数:101,代码来源:HTMLPurifier.standalone.php


注:本文中的HTMLPurifier_Generator类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。