to the DevNetwork Community for their help (see docs/ref-devnetwork.html for
more details), Feyd especially (namely IPv6 and optimization). Thanks to RSnake
for letting me package his fantastic XSS cheatsheet for a smoketest.
+
+ vim: et sw=4 sts=4
<?php
/*! @mainpage
- *
+ *
* HTML Purifier is an HTML filter that will take an arbitrary snippet of
* HTML and rigorously test, validate and filter it into a version that
* is safe for output onto webpages. It achieves this by:
- *
+ *
* -# Lexing (parsing into tokens) the document,
* -# Executing various strategies on the tokens:
* -# Removing all elements not in the whitelist,
* -# Fixing the nesting of the nodes, and
* -# Validating attributes of the nodes; and
* -# Generating HTML from the purified tokens.
- *
+ *
* However, most users will only need to interface with the HTMLPurifier
* and HTMLPurifier_Config.
*/
/*
- HTML Purifier 3.2.0 - Standards Compliant HTML Filtering
+ HTML Purifier 3.3.0 - Standards Compliant HTML Filtering
Copyright (C) 2006-2008 Edward Z. Yang
This library is free software; you can redistribute it and/or
/**
* Facade that coordinates HTML Purifier's subsystems in order to purify HTML.
- *
- * @note There are several points in which configuration can be specified
+ *
+ * @note There are several points in which configuration can be specified
* for HTML Purifier. The precedence of these (from lowest to
* highest) is as follows:
* -# Instance: new HTMLPurifier($config)
* -# Invocation: purify($html, $config)
* These configurations are entirely independent of each other and
* are *not* merged (this behavior may change in the future).
- *
+ *
* @todo We need an easier way to inject strategies using the configuration
* object.
*/
class HTMLPurifier
{
-
+
/** Version of HTML Purifier */
- public $version = '3.2.0';
-
+ public $version = '3.3.0';
+
/** Constant with version of HTML Purifier */
- const VERSION = '3.2.0';
-
+ const VERSION = '3.3.0';
+
/** Global configuration object */
public $config;
-
+
/** Array of extra HTMLPurifier_Filter objects to run on HTML, for backwards compatibility */
private $filters = array();
-
+
/** Single instance of HTML Purifier */
private static $instance;
-
+
protected $strategy, $generator;
-
+
/**
* Resultant HTMLPurifier_Context of last run purification. Is an array
* of contexts if the last called method was purifyArray().
*/
public $context;
-
+
/**
* Initializes the purifier.
* @param $config Optional HTMLPurifier_Config object for all instances of
* HTMLPurifier_Config::create() supports.
*/
public function __construct($config = null) {
-
+
$this->config = HTMLPurifier_Config::create($config);
-
+
$this->strategy = new HTMLPurifier_Strategy_Core();
-
+
}
-
+
/**
* Adds a filter to process the output. First come first serve
* @param $filter HTMLPurifier_Filter object
trigger_error('HTMLPurifier->addFilter() is deprecated, use configuration directives in the Filter namespace or Filter.Custom', E_USER_WARNING);
$this->filters[] = $filter;
}
-
+
/**
* 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
* @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'];
}
$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 =
+ $html =
$this->generator->generateFromTokens(
// list of tokens
$this->strategy->execute(
$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;
}
-
+
/**
* Filters an array of HTML snippets
* @param $config Optional HTMLPurifier_Config object for this operation.
$this->context = $context_array;
return $array_of_html;
}
-
+
/**
* Singleton for enforcing just one HTML Purifier in your system
* @param $prototype Optional prototype HTMLPurifier instance to
}
return self::$instance;
}
-
+
/**
* @note Backwards compatibility, see instance()
*/
public static function getInstance($prototype = null) {
return HTMLPurifier::instance($prototype);
}
-
+
}
+
+// vim: et sw=4 sts=4
* the core files required by HTML Purifier. This is a convenience stub that
* includes all files using dirname(__FILE__) and require_once. PLEASE DO NOT
* EDIT THIS FILE, changes will be overwritten the next time the script is run.
- *
+ *
* Changes to include_path are not necessary.
*/
require_once $__dir . '/HTMLPurifier/Length.php';
require_once $__dir . '/HTMLPurifier/Lexer.php';
require_once $__dir . '/HTMLPurifier/PercentEncoder.php';
+require_once $__dir . '/HTMLPurifier/PropertyList.php';
+require_once $__dir . '/HTMLPurifier/PropertyListIterator.php';
require_once $__dir . '/HTMLPurifier/Strategy.php';
require_once $__dir . '/HTMLPurifier/StringHash.php';
require_once $__dir . '/HTMLPurifier/StringHashParser.php';
class HTMLPurifier_AttrCollections
{
-
+
/**
* Associative array of attribute collections, indexed by name
*/
public $info = array();
-
+
/**
* Performs all expansions on internal data for use by other inclusions
* It also collects all attribute collection extensions from
$this->expandIdentifiers($this->info[$name], $attr_types);
}
}
-
+
/**
* Takes a reference to an attribute associative array and performs
* all inclusions specified by the zero index.
}
unset($attr[0]);
}
-
+
/**
* Expands all string identifiers in an attribute array by replacing
* them with the appropriate values inside HTMLPurifier_AttrTypes
* @param $attr_types HTMLPurifier_AttrTypes instance
*/
public function expandIdentifiers(&$attr, $attr_types) {
-
+
// because foreach will process new elements we add, make sure we
// skip duplicates
$processed = array();
-
+
foreach ($attr as $def_i => $def) {
// skip inclusions
if ($def_i === 0) continue;
-
+
if (isset($processed[$def_i])) continue;
-
+
// determine whether or not attribute is required
if ($required = (strpos($def_i, '*') !== false)) {
// rename the definition
$def_i = trim($def_i, '*');
$attr[$def_i] = $def;
}
-
+
$processed[$def_i] = true;
-
+
// if we've already got a literal object, move on
if (is_object($def)) {
// preserve previous required
$attr[$def_i]->required = ($required || $attr[$def_i]->required);
continue;
}
-
+
if ($def === false) {
unset($attr[$def_i]);
continue;
}
-
+
if ($t = $attr_types->get($def)) {
$attr[$def_i] = $t;
$attr[$def_i]->required = $required;
unset($attr[$def_i]);
}
}
-
+
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Base class for all validating attribute definitions.
- *
+ *
* This family of classes forms the core for not only HTML attribute validation,
* but also any sort of string that needs to be validated or cleaned (which
- * means CSS properties and composite definitions are defined here too).
+ * means CSS properties and composite definitions are defined here too).
* Besides defining (through code) what precisely makes the string valid,
* subclasses are also responsible for cleaning the code if possible.
*/
abstract class HTMLPurifier_AttrDef
{
-
+
/**
* Tells us whether or not an HTML attribute is minimized. Has no
* meaning in other contexts.
*/
public $minimized = false;
-
+
/**
* Tells us whether or not an HTML attribute is required. Has no
* meaning in other contexts
*/
public $required = false;
-
+
/**
* Validates and cleans passed string according to a definition.
- *
+ *
* @param $string String to be validated and cleaned.
* @param $config Mandatory HTMLPurifier_Config object.
* @param $context Mandatory HTMLPurifier_AttrContext object.
*/
abstract public function validate($string, $config, $context);
-
+
/**
* Convenience method that parses a string as if it were CDATA.
- *
+ *
* This method process a string in the manner specified at
* <http://www.w3.org/TR/html4/types.html#h-6.2> by removing
* leading and trailing whitespace, ignoring line feeds, and replacing
* carriage returns and tabs with spaces. While most useful for HTML
* attributes specified as CDATA, it can also be applied to most CSS
* values.
- *
+ *
* @note This method is not entirely standards compliant, as trim() removes
* more types of whitespace than specified in the spec. In practice,
* this is rarely a problem, as those extra characters usually have
* already been removed by HTMLPurifier_Encoder.
- *
+ *
* @warning This processing is inconsistent with XML's whitespace handling
* as specified by section 3.3.3 and referenced XHTML 1.0 section
* 4.7. However, note that we are NOT necessarily
$string = str_replace(array("\n", "\t", "\r"), ' ', $string);
return $string;
}
-
+
/**
* Factory method for creating this class from a string.
* @param $string String construction info
// to clone or instantiate new copies. (Instantiation is safer.)
return $this;
}
-
+
/**
* Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work
* properly. THIS IS A HACK!
protected function mungeRgb($string) {
return preg_replace('/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/', 'rgb(\1,\2,\3)', $string);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef
{
-
+
public function validate($css, $config, $context) {
-
+
$css = $this->parseCDATA($css);
-
+
$definition = $config->getCSSDefinition();
-
+
// we're going to break the spec and explode by semicolons.
// This is because semicolon rarely appears in escaped form
// Doing this is generally flaky but fast
// IT MIGHT APPEAR IN URIs, see HTMLPurifier_AttrDef_CSSURI
// for details
-
+
$declarations = explode(';', $css);
$propvalues = array();
-
+
/**
* Name of the current CSS property being validated.
*/
$property = false;
$context->register('CurrentCSSProperty', $property);
-
+
foreach ($declarations as $declaration) {
if (!$declaration) continue;
if (!strpos($declaration, ':')) continue;
if ($result === false) continue;
$propvalues[$property] = $result;
}
-
+
$context->destroy('CurrentCSSProperty');
-
+
// procedure does not write the new CSS simultaneously, so it's
// slightly inefficient, but it's the only way of getting rid of
// duplicates. Perhaps config to optimize it, but not now.
-
+
$new_declarations = '';
foreach ($propvalues as $prop => $value) {
$new_declarations .= "$prop:$value;";
}
-
+
return $new_declarations ? $new_declarations : false;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_AttrDef_CSS_AlphaValue extends HTMLPurifier_AttrDef_CSS_Number
{
-
+
public function __construct() {
parent::__construct(false); // opacity is non-negative, but we will clamp it
}
-
+
public function validate($number, $config, $context) {
$result = parent::validate($number, $config, $context);
if ($result === false) return $result;
if ($float > 1.0) $result = '1';
return $result;
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_Background extends HTMLPurifier_AttrDef
{
-
+
/**
* Local copy of component validators.
* @note See HTMLPurifier_AttrDef_Font::$info for a similar impl.
*/
protected $info;
-
+
public function __construct($config) {
$def = $config->getCSSDefinition();
$this->info['background-color'] = $def->info['background-color'];
$this->info['background-attachment'] = $def->info['background-attachment'];
$this->info['background-position'] = $def->info['background-position'];
}
-
+
public function validate($string, $config, $context) {
-
+
// regular pre-processing
$string = $this->parseCDATA($string);
if ($string === '') return false;
-
+
// munge rgb() decl if necessary
$string = $this->mungeRgb($string);
-
+
// assumes URI doesn't have spaces in it
$bits = explode(' ', strtolower($string)); // bits to process
-
+
$caught = array();
$caught['color'] = false;
$caught['image'] = false;
$caught['repeat'] = false;
$caught['attachment'] = false;
$caught['position'] = false;
-
+
$i = 0; // number of catches
$none = false;
-
+
foreach ($bits as $bit) {
if ($bit === '') continue;
foreach ($caught as $key => $status) {
break;
}
}
-
+
if (!$i) return false;
if ($caught['position'] !== false) {
$caught['position'] = $this->info['background-position']->
validate($caught['position'], $config, $context);
}
-
+
$ret = array();
foreach ($caught as $value) {
if ($value === false) continue;
$ret[] = $value;
}
-
+
if (empty($ret)) return false;
return implode(' ', $ret);
-
+
}
-
+
}
+// vim: et sw=4 sts=4
[
<percentage> | <length> | left | center | right
]
- [
+ [
<percentage> | <length> | top | center | bottom
]?
] |
/* QuirksMode says:
keyword + length/percentage must be ordered correctly, as per W3C
-
+
Internet Explorer and Opera, however, support arbitrary ordering. We
should fix it up.
-
+
Minor issue though, not strictly necessary.
*/
*/
class HTMLPurifier_AttrDef_CSS_BackgroundPosition extends HTMLPurifier_AttrDef
{
-
+
protected $length;
protected $percentage;
-
+
public function __construct() {
$this->length = new HTMLPurifier_AttrDef_CSS_Length();
$this->percentage = new HTMLPurifier_AttrDef_CSS_Percentage();
}
-
+
public function validate($string, $config, $context) {
$string = $this->parseCDATA($string);
$bits = explode(' ', $string);
-
+
$keywords = array();
$keywords['h'] = false; // left, right
$keywords['v'] = false; // top, bottom
$keywords['c'] = false; // center
$measures = array();
-
+
$i = 0;
-
+
$lookup = array(
'top' => 'v',
'bottom' => 'v',
'right' => 'h',
'center' => 'c'
);
-
+
foreach ($bits as $bit) {
if ($bit === '') continue;
-
+
// test for keyword
$lbit = ctype_lower($bit) ? $bit : strtolower($bit);
if (isset($lookup[$lbit])) {
$keywords[$status] = $lbit;
$i++;
}
-
+
// test for length
$r = $this->length->validate($bit, $config, $context);
if ($r !== false) {
$measures[] = $r;
$i++;
}
-
+
// test for percentage
$r = $this->percentage->validate($bit, $config, $context);
if ($r !== false) {
$measures[] = $r;
$i++;
}
-
+
}
-
+
if (!$i) return false; // no valid values were caught
-
-
+
+
$ret = array();
-
+
// first keyword
if ($keywords['h']) $ret[] = $keywords['h'];
elseif (count($measures)) $ret[] = array_shift($measures);
$ret[] = $keywords['c'];
$keywords['c'] = false; // prevent re-use: center = center center
}
-
+
if ($keywords['v']) $ret[] = $keywords['v'];
elseif (count($measures)) $ret[] = array_shift($measures);
elseif ($keywords['c']) $ret[] = $keywords['c'];
-
+
if (empty($ret)) return false;
return implode(' ', $ret);
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_Border extends HTMLPurifier_AttrDef
{
-
+
/**
* Local copy of properties this property is shorthand for.
*/
protected $info = array();
-
+
public function __construct($config) {
$def = $config->getCSSDefinition();
$this->info['border-width'] = $def->info['border-width'];
$this->info['border-style'] = $def->info['border-style'];
$this->info['border-top-color'] = $def->info['border-top-color'];
}
-
+
public function validate($string, $config, $context) {
$string = $this->parseCDATA($string);
$string = $this->mungeRgb($string);
}
return rtrim($ret);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef
{
-
+
public function validate($color, $config, $context) {
-
+
static $colors = null;
if ($colors === null) $colors = $config->get('Core', 'ColorKeywords');
-
+
$color = trim($color);
if ($color === '') return false;
-
+
$lower = strtolower($color);
if (isset($colors[$lower])) return $colors[$lower];
-
+
if (strpos($color, 'rgb(') !== false) {
// rgb literal handling
$length = strlen($color);
if ($length !== 3 && $length !== 6) return false;
if (!ctype_xdigit($hex)) return false;
}
-
+
return $color;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Allows multiple validators to attempt to validate attribute.
- *
+ *
* Composite is just what it sounds like: a composite of many validators.
* This means that multiple HTMLPurifier_AttrDef objects will have a whack
* at the string. If one of them passes, that's what is returned. This is
*/
class HTMLPurifier_AttrDef_CSS_Composite extends HTMLPurifier_AttrDef
{
-
+
/**
* List of HTMLPurifier_AttrDef objects that may process strings
* @todo Make protected
*/
public $defs;
-
+
/**
* @param $defs List of HTMLPurifier_AttrDef objects
*/
public function __construct($defs) {
$this->defs = $defs;
}
-
+
public function validate($string, $config, $context) {
foreach ($this->defs as $i => $def) {
$result = $this->defs[$i]->validate($string, $config, $context);
}
return false;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_DenyElementDecorator extends HTMLPurifier_AttrDef
{
- protected $def, $element;
-
+ public $def, $element;
+
/**
* @param $def Definition to wrap
* @param $element Element to deny
return $this->def->validate($string, $config, $context);
}
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_Filter extends HTMLPurifier_AttrDef
{
-
+
protected $intValidator;
-
+
public function __construct() {
$this->intValidator = new HTMLPurifier_AttrDef_Integer();
}
-
+
public function validate($value, $config, $context) {
$value = $this->parseCDATA($value);
if ($value === 'none') return $value;
$ret_function = "$function($ret_parameters)";
return $ret_function;
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_Font extends HTMLPurifier_AttrDef
{
-
+
/**
* Local copy of component validators.
- *
+ *
* @note If we moved specific CSS property definitions to their own
* classes instead of having them be assembled at run time by
* CSSDefinition, this wouldn't be necessary. We'd instantiate
* our own copies.
*/
protected $info = array();
-
+
public function __construct($config) {
$def = $config->getCSSDefinition();
$this->info['font-style'] = $def->info['font-style'];
$this->info['line-height'] = $def->info['line-height'];
$this->info['font-family'] = $def->info['font-family'];
}
-
+
public function validate($string, $config, $context) {
-
+
static $system_fonts = array(
'caption' => true,
'icon' => true,
'small-caption' => true,
'status-bar' => true
);
-
+
// regular pre-processing
$string = $this->parseCDATA($string);
if ($string === '') return false;
-
+
// check if it's one of the keywords
$lowercase_string = strtolower($string);
if (isset($system_fonts[$lowercase_string])) {
return $lowercase_string;
}
-
+
$bits = explode(' ', $string); // bits to process
$stage = 0; // this indicates what we're looking for
$caught = array(); // which stage 0 properties have we caught?
$stage_1 = array('font-style', 'font-variant', 'font-weight');
$final = ''; // output
-
+
for ($i = 0, $size = count($bits); $i < $size; $i++) {
if ($bits[$i] === '') continue;
switch ($stage) {
-
+
// attempting to catch font-style, font-variant or font-weight
case 0:
foreach ($stage_1 as $validator_name) {
// all three caught, continue on
if (count($caught) >= 3) $stage = 1;
if ($r !== false) break;
-
+
// attempting to catch font-size and perhaps line-height
case 1:
$found_slash = false;
break;
}
return false;
-
+
// attempting to catch font-family
case 2:
$font_family =
}
return false;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef
{
-
+
public function validate($string, $config, $context) {
static $generic_names = array(
'serif' => true,
'fantasy' => true,
'cursive' => true
);
-
+
// assume that no font names contain commas in them
$fonts = explode(',', $string);
$final = '';
$quote = $font[0];
if ($font[$length - 1] !== $quote) continue;
$font = substr($font, 1, $length - 2);
-
+
$new_font = '';
for ($i = 0, $c = strlen($font); $i < $c; $i++) {
if ($font[$i] === '\\') {
}
$new_font .= $font[$i];
}
-
+
$font = $new_font;
}
// $font is a pure representation of the font name
-
+
if (ctype_alnum($font) && $font !== '') {
// very simple font, allow it in unharmed
$final .= $font . ', ';
continue;
}
-
+
// complicated font, requires quoting
-
+
// armor single quotes and new lines
$font = str_replace("\\", "\\\\", $font);
$font = str_replace("'", "\\'", $font);
if ($final === '') return false;
return $final;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_ImportantDecorator extends HTMLPurifier_AttrDef
{
- protected $def, $allow;
-
+ public $def, $allow;
+
/**
* @param $def Definition to wrap
* @param $allow Whether or not to allow !important
return $string;
}
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_Length extends HTMLPurifier_AttrDef
{
-
+
protected $min, $max;
-
+
/**
* @param HTMLPurifier_Length $max Minimum length, or null for no bound. String is also acceptable.
* @param HTMLPurifier_Length $max Maximum length, or null for no bound. String is also acceptable.
$this->min = $min !== null ? HTMLPurifier_Length::make($min) : null;
$this->max = $max !== null ? HTMLPurifier_Length::make($max) : null;
}
-
+
public function validate($string, $config, $context) {
$string = $this->parseCDATA($string);
-
+
// Optimizations
if ($string === '') return false;
if ($string === '0') return '0';
if (strlen($string) === 1) return false;
-
+
$length = HTMLPurifier_Length::make($string);
if (!$length->isValid()) return false;
-
+
if ($this->min) {
$c = $length->compareTo($this->min);
if ($c === false) return false;
if ($c === false) return false;
if ($c > 0) return false;
}
-
+
return $length->toString();
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_ListStyle extends HTMLPurifier_AttrDef
{
-
+
/**
* Local copy of component validators.
* @note See HTMLPurifier_AttrDef_CSS_Font::$info for a similar impl.
*/
protected $info;
-
+
public function __construct($config) {
$def = $config->getCSSDefinition();
$this->info['list-style-type'] = $def->info['list-style-type'];
$this->info['list-style-position'] = $def->info['list-style-position'];
$this->info['list-style-image'] = $def->info['list-style-image'];
}
-
+
public function validate($string, $config, $context) {
-
+
// regular pre-processing
$string = $this->parseCDATA($string);
if ($string === '') return false;
-
+
// assumes URI doesn't have spaces in it
$bits = explode(' ', strtolower($string)); // bits to process
-
+
$caught = array();
$caught['type'] = false;
$caught['position'] = false;
$caught['image'] = false;
-
+
$i = 0; // number of catches
$none = false;
-
+
foreach ($bits as $bit) {
if ($i >= 3) return; // optimization bit
if ($bit === '') continue;
break;
}
}
-
+
if (!$i) return false;
-
+
$ret = array();
-
+
// construct type
if ($caught['type']) $ret[] = $caught['type'];
-
+
// construct image
if ($caught['image']) $ret[] = $caught['image'];
-
+
// construct position
if ($caught['position']) $ret[] = $caught['position'];
-
+
if (empty($ret)) return false;
return implode(' ', $ret);
-
+
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Framework class for strings that involve multiple values.
- *
+ *
* Certain CSS properties such as border-width and margin allow multiple
* lengths to be specified. This class can take a vanilla border-width
* definition and multiply it, usually into a max of four.
- *
+ *
* @note Even though the CSS specification isn't clear about it, inherit
* can only be used alone: it will never manifest as part of a multi
* shorthand declaration. Thus, this class does not allow inherit.
*/
class HTMLPurifier_AttrDef_CSS_Multiple extends HTMLPurifier_AttrDef
{
-
+
/**
* Instance of component definition to defer validation to.
* @todo Make protected
*/
public $single;
-
+
/**
* Max number of values allowed.
* @todo Make protected
*/
public $max;
-
+
/**
* @param $single HTMLPurifier_AttrDef to multiply
* @param $max Max number of values allowed (usually four)
$this->single = $single;
$this->max = $max;
}
-
+
public function validate($string, $config, $context) {
$string = $this->parseCDATA($string);
if ($string === '') return false;
if ($final === '') return false;
return rtrim($final);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef
{
-
+
/**
* Bool indicating whether or not only positive values allowed.
*/
protected $non_negative = false;
-
+
/**
* @param $non_negative Bool indicating whether negatives are forbidden
*/
public function __construct($non_negative = false) {
$this->non_negative = $non_negative;
}
-
+
/**
* @warning Some contexts do not pass $config, $context. These
* variables should not be used without checking HTMLPurifier_Length
*/
public function validate($number, $config, $context) {
-
+
$number = $this->parseCDATA($number);
-
+
if ($number === '') return false;
if ($number === '0') return '0';
-
+
$sign = '';
switch ($number[0]) {
case '-':
case '+':
$number = substr($number, 1);
}
-
+
if (ctype_digit($number)) {
$number = ltrim($number, '0');
return $number ? $sign . $number : '0';
}
-
+
// Period is the only non-numeric character allowed
if (strpos($number, '.') === false) return false;
-
+
list($left, $right) = explode('.', $number, 2);
-
+
if ($left === '' && $right === '') return false;
if ($left !== '' && !ctype_digit($left)) return false;
-
+
$left = ltrim($left, '0');
$right = rtrim($right, '0');
-
+
if ($right === '') {
return $left ? $sign . $left : '0';
} elseif (!ctype_digit($right)) {
return false;
}
-
+
return $sign . $left . '.' . $right;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_Percentage extends HTMLPurifier_AttrDef
{
-
+
/**
* Instance of HTMLPurifier_AttrDef_CSS_Number to defer number validation
*/
protected $number_def;
-
+
/**
* @param Bool indicating whether to forbid negative values
*/
public function __construct($non_negative = false) {
$this->number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative);
}
-
+
public function validate($string, $config, $context) {
-
+
$string = $this->parseCDATA($string);
-
+
if ($string === '') return false;
$length = strlen($string);
if ($length === 1) return false;
if ($string[$length - 1] !== '%') return false;
-
+
$number = substr($string, 0, $length - 1);
$number = $this->number_def->validate($number, $config, $context);
-
+
if ($number === false) return false;
return "$number%";
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_TextDecoration extends HTMLPurifier_AttrDef
{
-
+
public function validate($string, $config, $context) {
-
+
static $allowed_values = array(
'line-through' => true,
'overline' => true,
'underline' => true,
);
-
+
$string = strtolower($this->parseCDATA($string));
-
+
if ($string === 'none') return $string;
-
+
$parts = explode(' ', $string);
$final = '';
foreach ($parts as $part) {
$final = rtrim($final);
if ($final === '') return false;
return $final;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_CSS_URI extends HTMLPurifier_AttrDef_URI
{
-
+
public function __construct() {
parent::__construct(true); // always embedded
}
-
+
public function validate($uri_string, $config, $context) {
// parse the URI out of the string and then pass it onto
// the parent object
-
+
$uri_string = $this->parseCDATA($uri_string);
if (strpos($uri_string, 'url(') !== 0) return false;
$uri_string = substr($uri_string, 4);
$new_length = strlen($uri_string) - 1;
if ($uri_string[$new_length] != ')') return false;
$uri = trim(substr($uri_string, 0, $new_length));
-
+
if (!empty($uri) && ($uri[0] == "'" || $uri[0] == '"')) {
$quote = $uri[0];
$new_length = strlen($uri) - 1;
if ($uri[$new_length] !== $quote) return false;
$uri = substr($uri, 1, $new_length - 1);
}
-
+
$keys = array( '(', ')', ',', ' ', '"', "'");
$values = array('\\(', '\\)', '\\,', '\\ ', '\\"', "\\'");
$uri = str_replace($values, $keys, $uri);
-
+
$result = parent::validate($uri, $config, $context);
-
+
if ($result === false) return false;
-
+
// escape necessary characters according to CSS spec
// except for the comma, none of these should appear in the
// URI at all
$result = str_replace($keys, $values, $result);
-
+
return "url($result)";
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_Enum extends HTMLPurifier_AttrDef
{
-
+
/**
* Lookup table of valid values.
* @todo Make protected
*/
public $valid_values = array();
-
+
/**
* Bool indicating whether or not enumeration is case sensitive.
* @note In general this is always case insensitive.
*/
protected $case_sensitive = false; // values according to W3C spec
-
+
/**
* @param $valid_values List of valid values
* @param $case_sensitive Bool indicating whether or not case sensitive
$this->valid_values = array_flip($valid_values);
$this->case_sensitive = $case_sensitive;
}
-
+
public function validate($string, $config, $context) {
$string = trim($string);
if (!$this->case_sensitive) {
$string = ctype_lower($string) ? $string : strtolower($string);
}
$result = isset($this->valid_values[$string]);
-
+
return $result ? $string : false;
}
-
+
/**
* @param $string In form of comma-delimited list of case-insensitive
* valid values. Example: "foo,bar,baz". Prepend "s:" to make
$values = explode(',', $string);
return new HTMLPurifier_AttrDef_Enum($values, $sensitive);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_HTML_Bool extends HTMLPurifier_AttrDef
{
-
+
protected $name;
public $minimized = true;
-
+
public function __construct($name = false) {$this->name = $name;}
-
+
public function validate($string, $config, $context) {
if (empty($string)) return false;
return $this->name;
}
-
+
/**
* @param $string Name of attribute
*/
public function make($string) {
return new HTMLPurifier_AttrDef_HTML_Bool($string);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_HTML_Color extends HTMLPurifier_AttrDef
{
-
+
public function validate($string, $config, $context) {
-
+
static $colors = null;
if ($colors === null) $colors = $config->get('Core', 'ColorKeywords');
-
+
$string = trim($string);
-
+
if (empty($string)) return false;
if (isset($colors[$string])) return $colors[$string];
if ($string[0] === '#') $hex = substr($string, 1);
else $hex = $string;
-
+
$length = strlen($hex);
if ($length !== 3 && $length !== 6) return false;
if (!ctype_xdigit($hex)) return false;
if ($length === 3) $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
-
+
return "#$hex";
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_HTML_FrameTarget extends HTMLPurifier_AttrDef_Enum
{
-
+
public $valid_values = false; // uninitialized value
protected $case_sensitive = false;
-
+
public function __construct() {}
-
+
public function validate($string, $config, $context) {
if ($this->valid_values === false) $this->valid_values = $config->get('Attr', 'AllowedFrameTargets');
return parent::validate($string, $config, $context);
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_AttrDef_HTML_ID extends HTMLPurifier_AttrDef
{
-
+
// ref functionality disabled, since we also have to verify
// whether or not the ID it refers to exists
-
+
public function validate($id, $config, $context) {
-
+
if (!$config->get('Attr', 'EnableID')) return false;
-
+
$id = trim($id); // trim it first
-
+
if ($id === '') return false;
-
+
$prefix = $config->get('Attr', 'IDPrefix');
if ($prefix !== '') {
$prefix .= $config->get('Attr', 'IDPrefixLocal');
trigger_error('%Attr.IDPrefixLocal cannot be used unless '.
'%Attr.IDPrefix is set', E_USER_WARNING);
}
-
+
//if (!$this->ref) {
$id_accumulator =& $context->get('IDAccumulator');
if (isset($id_accumulator->ids[$id])) return false;
//}
-
+
// we purposely avoid using regex, hopefully this is faster
-
+
if (ctype_alpha($id)) {
$result = true;
} else {
);
$result = ($trim === '');
}
-
+
$regexp = $config->get('Attr', 'IDBlacklistRegexp');
if ($regexp && preg_match($regexp, $id)) {
return false;
}
-
+
if (/*!$this->ref && */$result) $id_accumulator->add($id);
-
+
// if no change was made to the ID, return the result
// else, return the new id if stripping whitespace made it
// valid, or return false.
return $result ? $id : false;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Validates the HTML type length (not to be confused with CSS's length).
- *
+ *
* This accepts integer pixels or percentages as lengths for certain
* HTML attributes.
*/
class HTMLPurifier_AttrDef_HTML_Length extends HTMLPurifier_AttrDef_HTML_Pixels
{
-
+
public function validate($string, $config, $context) {
-
+
$string = trim($string);
if ($string === '') return false;
-
+
$parent_result = parent::validate($string, $config, $context);
if ($parent_result !== false) return $parent_result;
-
+
$length = strlen($string);
$last_char = $string[$length - 1];
-
+
if ($last_char !== '%') return false;
-
+
$points = substr($string, 0, $length - 1);
-
+
if (!is_numeric($points)) return false;
-
+
$points = (int) $points;
-
+
if ($points < 0) return '0%';
if ($points > 100) return '100%';
-
+
return ((string) $points) . '%';
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_HTML_LinkTypes extends HTMLPurifier_AttrDef
{
-
+
/** Name config attribute to pull. */
protected $name;
-
+
public function __construct($name) {
$configLookup = array(
'rel' => 'AllowedRel',
}
$this->name = $configLookup[$name];
}
-
+
public function validate($string, $config, $context) {
-
+
$allowed = $config->get('Attr', $this->name);
if (empty($allowed)) return false;
-
+
$string = $this->parseCDATA($string);
$parts = explode(' ', $string);
-
+
// lookup to prevent duplicates
$ret_lookup = array();
foreach ($parts as $part) {
if (!isset($allowed[$part])) continue;
$ret_lookup[$part] = true;
}
-
+
if (empty($ret_lookup)) return false;
$string = implode(' ', array_keys($ret_lookup));
-
+
return $string;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Validates a MultiLength as defined by the HTML spec.
- *
+ *
* A multilength is either a integer (pixel count), a percentage, or
* a relative number.
*/
class HTMLPurifier_AttrDef_HTML_MultiLength extends HTMLPurifier_AttrDef_HTML_Length
{
-
+
public function validate($string, $config, $context) {
-
+
$string = trim($string);
if ($string === '') return false;
-
+
$parent_result = parent::validate($string, $config, $context);
if ($parent_result !== false) return $parent_result;
-
+
$length = strlen($string);
$last_char = $string[$length - 1];
-
+
if ($last_char !== '*') return false;
-
+
$int = substr($string, 0, $length - 1);
-
+
if ($int == '') return '*';
if (!is_numeric($int)) return false;
-
+
$int = (int) $int;
-
+
if ($int < 0) return false;
if ($int == 0) return '0';
if ($int == 1) return '*';
return ((string) $int) . '*';
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_HTML_Nmtokens extends HTMLPurifier_AttrDef
{
-
+
public function validate($string, $config, $context) {
-
+
$string = trim($string);
-
+
// early abort: '' and '0' (strings that convert to false) are invalid
if (!$string) return false;
-
+
// OPTIMIZABLE!
// do the preg_match, capture all subpatterns for reformulation
-
+
// we don't support U+00A1 and up codepoints or
// escaping because I don't know how to do that with regexps
// and plus it would complicate optimization efforts (you never
'((?:--|-?[A-Za-z_])[A-Za-z_\-0-9]*)'.
'(?:(?=\s)|\z)/'; // look ahead for space or string end
preg_match_all($pattern, $string, $matches);
-
+
if (empty($matches[1])) return false;
-
+
// reconstruct string
$new_string = '';
foreach ($matches[1] as $token) {
$new_string .= $token . ' ';
}
$new_string = rtrim($new_string);
-
+
return $new_string;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_HTML_Pixels extends HTMLPurifier_AttrDef
{
-
+
protected $max;
-
+
public function __construct($max = null) {
$this->max = $max;
}
-
+
public function validate($string, $config, $context) {
-
+
$string = trim($string);
if ($string === '0') return $string;
if ($string === '') return false;
}
if (!is_numeric($string)) return false;
$int = (int) $string;
-
+
if ($int < 0) return '0';
-
+
// upper-bound value, extremely high values can
// crash operating systems, see <http://ha.ckers.org/imagecrash.html>
// WARNING, above link WILL crash you if you're using Windows
-
+
if ($this->max !== null && $int > $this->max) return (string) $this->max;
-
+
return (string) $int;
-
+
}
-
+
public function make($string) {
if ($string === '') $max = null;
else $max = (int) $string;
$class = get_class($this);
return new $class($max);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_Integer extends HTMLPurifier_AttrDef
{
-
+
/**
* Bool indicating whether or not negative values are allowed
*/
protected $negative = true;
-
+
/**
* Bool indicating whether or not zero is allowed
*/
protected $zero = true;
-
+
/**
* Bool indicating whether or not positive values are allowed
*/
protected $positive = true;
-
+
/**
* @param $negative Bool indicating whether or not negative values are allowed
* @param $zero Bool indicating whether or not zero is allowed
$this->zero = $zero;
$this->positive = $positive;
}
-
+
public function validate($integer, $config, $context) {
-
+
$integer = $this->parseCDATA($integer);
if ($integer === '') return false;
-
+
// we could possibly simply typecast it to integer, but there are
// certain fringe cases that must not return an integer.
-
+
// clip leading sign
if ( $this->negative && $integer[0] === '-' ) {
$digits = substr($integer, 1);
} else {
$digits = $integer;
}
-
+
// test if it's numeric
if (!ctype_digit($digits)) return false;
-
+
// perform scope tests
if (!$this->zero && $integer == 0) return false;
if (!$this->positive && $integer > 0) return false;
if (!$this->negative && $integer < 0) return false;
-
+
return $integer;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_Lang extends HTMLPurifier_AttrDef
{
-
+
public function validate($string, $config, $context) {
// moodle change - we use special lang strings unfortunatelly
$string = trim($string);
if (!$string) return false;
-
+
$subtags = explode('-', $string);
$num_subtags = count($subtags);
-
+
if ($num_subtags == 0) return false; // sanity check
-
+
// process primary subtag : $subtags[0]
$length = strlen($subtags[0]);
switch ($length) {
default:
return false;
}
-
+
$new_string = $subtags[0];
if ($num_subtags == 1) return $new_string;
-
+
// process second subtag : $subtags[1]
$length = strlen($subtags[1]);
if ($length == 0 || ($length == 1 && $subtags[1] != 'x') || $length > 8 || !ctype_alnum($subtags[1])) {
return $new_string;
}
if (!ctype_lower($subtags[1])) $subtags[1] = strtolower($subtags[1]);
-
+
$new_string .= '-' . $subtags[1];
if ($num_subtags == 2) return $new_string;
-
+
// process all other subtags, index 2 and up
for ($i = 2; $i < $num_subtags; $i++) {
$length = strlen($subtags[$i]);
}
$new_string .= '-' . $subtags[$i];
}
-
+
return $new_string;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_Switch
{
-
+
protected $tag;
protected $withTag, $withoutTag;
-
+
/**
* @param string $tag Tag name to switch upon
* @param HTMLPurifier_AttrDef $with_tag Call if token matches tag
$this->withTag = $with_tag;
$this->withoutTag = $without_tag;
}
-
+
public function validate($string, $config, $context) {
$token = $context->get('CurrentToken', true);
if (!$token || $token->name !== $this->tag) {
return $this->withTag->validate($string, $config, $context);
}
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_Text extends HTMLPurifier_AttrDef
{
-
+
public function validate($string, $config, $context) {
return $this->parseCDATA($string);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_URI extends HTMLPurifier_AttrDef
{
-
+
protected $parser;
protected $embedsResource;
-
+
/**
* @param $embeds_resource_resource Does the URI here result in an extra HTTP request?
*/
$this->parser = new HTMLPurifier_URIParser();
$this->embedsResource = (bool) $embeds_resource;
}
-
+
public function make($string) {
$embeds = (bool) $string;
return new HTMLPurifier_AttrDef_URI($embeds);
}
-
+
public function validate($uri, $config, $context) {
-
+
if ($config->get('URI', 'Disable')) return false;
-
+
$uri = $this->parseCDATA($uri);
-
+
// parse the URI
$uri = $this->parser->parse($uri);
if ($uri === false) return false;
-
+
// add embedded flag to context for validators
- $context->register('EmbeddedURI', $this->embedsResource);
-
+ $context->register('EmbeddedURI', $this->embedsResource);
+
$ok = false;
do {
-
+
// generic validation
$result = $uri->validate($config, $context);
if (!$result) break;
-
+
// chained filtering
$uri_def = $config->getDefinition('URI');
$result = $uri_def->filter($uri, $config, $context);
if (!$result) break;
-
- // scheme-specific validation
+
+ // scheme-specific validation
$scheme_obj = $uri->getSchemeObj($config, $context);
if (!$scheme_obj) break;
if ($this->embedsResource && !$scheme_obj->browsable) break;
$result = $scheme_obj->validate($uri, $config, $context);
if (!$result) break;
-
+
// Post chained filtering
$result = $uri_def->postFilter($uri, $config, $context);
if (!$result) break;
-
+
// survived gauntlet
$ok = true;
-
+
} while (false);
-
+
$context->destroy('EmbeddedURI');
if (!$ok) return false;
-
+
// back to string
return $uri->toString();
-
+
}
-
-}
+}
+// vim: et sw=4 sts=4
abstract class HTMLPurifier_AttrDef_URI_Email extends HTMLPurifier_AttrDef
{
-
+
/**
* Unpacks a mailbox into its display-name and address
*/
function unpack($string) {
// needs to be implemented
}
-
+
}
// sub-implementations
+
+// vim: et sw=4 sts=4
<?php
/**
- * Primitive email validation class based on the regexp found at
+ * Primitive email validation class based on the regexp found at
* http://www.regular-expressions.info/email.html
*/
class HTMLPurifier_AttrDef_URI_Email_SimpleCheck extends HTMLPurifier_AttrDef_URI_Email
{
-
+
public function validate($string, $config, $context) {
// no support for named mailboxes i.e. "Bob <bob@example.com>"
// that needs more percent encoding to be done
$result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $string);
return $result ? $string : false;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_URI_Host extends HTMLPurifier_AttrDef
{
-
+
/**
* Instance of HTMLPurifier_AttrDef_URI_IPv4 sub-validator
*/
protected $ipv4;
-
+
/**
* Instance of HTMLPurifier_AttrDef_URI_IPv6 sub-validator
*/
protected $ipv6;
-
+
public function __construct() {
$this->ipv4 = new HTMLPurifier_AttrDef_URI_IPv4();
$this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6();
}
-
+
public function validate($string, $config, $context) {
$length = strlen($string);
if ($string === '') return '';
if ($valid === false) return false;
return '['. $valid . ']';
}
-
+
// need to do checks on unusual encodings too
$ipv4 = $this->ipv4->validate($string, $config, $context);
if ($ipv4 !== false) return $ipv4;
-
+
// A regular domain name.
-
+
// This breaks I18N domain names, but we don't have proper IRI support,
- // so force users to insert Punycode. If there's complaining we'll
+ // so force users to insert Punycode. If there's complaining we'll
// try to fix things into an international friendly form.
-
+
// The productions describing this are:
$a = '[a-z]'; // alpha
$an = '[a-z0-9]'; // alphanum
// hostname = *( domainlabel "." ) toplabel [ "." ]
$match = preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string);
if (!$match) return false;
-
+
return $string;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_URI_IPv4 extends HTMLPurifier_AttrDef
{
-
+
/**
* IPv4 regex, protected so that IPv6 can reuse it
*/
protected $ip4;
-
+
public function validate($aIP, $config, $context) {
-
+
if (!$this->ip4) $this->_loadRegex();
-
+
if (preg_match('#^' . $this->ip4 . '$#s', $aIP))
{
return $aIP;
}
-
+
return false;
-
+
}
-
+
/**
* Lazy load function to prevent regex from being stuffed in
* cache.
$oct = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'; // 0-255
$this->ip4 = "(?:{$oct}\\.{$oct}\\.{$oct}\\.{$oct})";
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrDef_URI_IPv6 extends HTMLPurifier_AttrDef_URI_IPv4
{
-
+
public function validate($aIP, $config, $context) {
-
+
if (!$this->ip4) $this->_loadRegex();
-
+
$original = $aIP;
-
+
$hex = '[0-9a-fA-F]';
$blk = '(?:' . $hex . '{1,4})';
$pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128
-
+
// prefix check
if (strpos($aIP, '/') !== false)
{
return false;
}
}
-
- // IPv4-compatiblity check
+
+ // IPv4-compatiblity check
if (preg_match('#(?<=:'.')' . $this->ip4 . '$#s', $aIP, $find))
{
$aIP = substr($aIP, 0, 0-strlen($find[0]));
$aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3];
unset($find, $ip);
}
-
+
// compression check
$aIP = explode('::', $aIP);
$c = count($aIP);
list($first, $second) = $aIP;
$first = explode(':', $first);
$second = explode(':', $second);
-
+
if (count($first) + count($second) > 8)
{
return false;
}
-
+
while(count($first) < 8)
{
array_push($first, '0');
$aIP = explode(':', $aIP[0]);
}
$c = count($aIP);
-
+
if ($c != 8)
{
return false;
}
-
+
// All the pieces should be 16-bit hex strings. Are they?
foreach ($aIP as $piece)
{
return false;
}
}
-
+
return $original;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Processes an entire attribute array for corrections needing multiple values.
- *
+ *
* Occasionally, a certain attribute will need to be removed and popped onto
* another value. Instead of creating a complex return syntax for
* HTMLPurifier_AttrDef, we just pass the whole attribute array to a
* specialized object and have that do the special work. That is the
* family of HTMLPurifier_AttrTransform.
- *
+ *
* An attribute transformation can be assigned to run before or after
* HTMLPurifier_AttrDef validation. See HTMLPurifier_HTMLDefinition for
* more details.
abstract class HTMLPurifier_AttrTransform
{
-
+
/**
* Abstract: makes changes to the attributes dependent on multiple values.
- *
+ *
* @param $attr Assoc array of attributes, usually from
* HTMLPurifier_Token_Tag::$attr
* @param $config Mandatory HTMLPurifier_Config object.
* @returns Processed attribute array.
*/
abstract public function transform($attr, $config, $context);
-
+
/**
* Prepends CSS properties to the style attribute, creating the
* attribute if it doesn't exist.
$attr['style'] = isset($attr['style']) ? $attr['style'] : '';
$attr['style'] = $css . $attr['style'];
}
-
+
/**
* Retrieves and removes an attribute
* @param $attr Attribute array to process (passed by reference)
unset($attr[$key]);
return $value;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_AttrTransform_Background extends HTMLPurifier_AttrTransform {
public function transform($attr, $config, $context) {
-
+
if (!isset($attr['background'])) return $attr;
-
+
$background = $this->confiscateAttr($attr, 'background');
// some validation should happen here
-
+
$this->prependCSS($attr, "background-image:url($background);");
-
+
return $attr;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrTransform_BdoDir extends HTMLPurifier_AttrTransform
{
-
+
public function transform($attr, $config, $context) {
if (isset($attr['dir'])) return $attr;
$attr['dir'] = $config->get('Attr', 'DefaultTextDir');
return $attr;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_AttrTransform_BgColor extends HTMLPurifier_AttrTransform {
public function transform($attr, $config, $context) {
-
+
if (!isset($attr['bgcolor'])) return $attr;
-
+
$bgcolor = $this->confiscateAttr($attr, 'bgcolor');
// some validation should happen here
-
+
$this->prependCSS($attr, "background-color:$bgcolor;");
-
+
return $attr;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
* Pre-transform that changes converts a boolean attribute to fixed CSS
*/
class HTMLPurifier_AttrTransform_BoolToCSS extends HTMLPurifier_AttrTransform {
-
+
/**
* Name of boolean attribute that is trigger
*/
protected $attr;
-
+
/**
* CSS declarations to add to style, needs trailing semicolon
*/
protected $css;
-
+
/**
* @param $attr string attribute name to convert from
* @param $css string CSS declarations to add to style (needs semicolon)
$this->attr = $attr;
$this->css = $css;
}
-
+
public function transform($attr, $config, $context) {
if (!isset($attr[$this->attr])) return $attr;
unset($attr[$this->attr]);
$this->prependCSS($attr, $this->css);
return $attr;
}
-
+
}
+// vim: et sw=4 sts=4
$this->prependCSS($attr, "border:{$border_width}px solid;");
return $attr;
}
-
+
}
+// vim: et sw=4 sts=4
* values (enumerated) to CSS.
*/
class HTMLPurifier_AttrTransform_EnumToCSS extends HTMLPurifier_AttrTransform {
-
+
/**
* Name of attribute to transform from
*/
protected $attr;
-
+
/**
* Lookup array of attribute values to CSS
*/
protected $enumToCSS = array();
-
+
/**
* Case sensitivity of the matching
* @warning Currently can only be guaranteed to work with ASCII
* values.
*/
protected $caseSensitive = false;
-
+
/**
* @param $attr String attribute name to transform from
* @param $enumToCSS Lookup array of attribute values to CSS
$this->enumToCSS = $enum_to_css;
$this->caseSensitive = (bool) $case_sensitive;
}
-
+
public function transform($attr, $config, $context) {
-
+
if (!isset($attr[$this->attr])) return $attr;
-
+
$value = trim($attr[$this->attr]);
unset($attr[$this->attr]);
-
+
if (!$this->caseSensitive) $value = strtolower($value);
-
+
if (!isset($this->enumToCSS[$value])) {
return $attr;
}
-
+
$this->prependCSS($attr, $this->enumToCSS[$value]);
-
+
return $attr;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrTransform_ImgRequired extends HTMLPurifier_AttrTransform
{
-
+
public function transform($attr, $config, $context) {
-
+
$src = true;
if (!isset($attr['src'])) {
if ($config->get('Core', 'RemoveInvalidImg')) return $attr;
$attr['src'] = $config->get('Attr', 'DefaultInvalidImage');
$src = false;
}
-
+
if (!isset($attr['alt'])) {
if ($src) {
$alt = $config->get('Attr', 'DefaultImageAlt');
$attr['alt'] = $config->get('Attr', 'DefaultInvalidImageAlt');
}
}
-
+
return $attr;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
* Pre-transform that changes deprecated hspace and vspace attributes to CSS
*/
class HTMLPurifier_AttrTransform_ImgSpace extends HTMLPurifier_AttrTransform {
-
+
protected $attr;
protected $css = array(
'hspace' => array('left', 'right'),
'vspace' => array('top', 'bottom')
);
-
+
public function __construct($attr) {
$this->attr = $attr;
if (!isset($this->css[$attr])) {
trigger_error(htmlspecialchars($attr) . ' is not valid space attribute');
}
}
-
+
public function transform($attr, $config, $context) {
-
+
if (!isset($attr[$this->attr])) return $attr;
-
+
$width = $this->confiscateAttr($attr, $this->attr);
// some validation could happen here
-
+
if (!isset($this->css[$this->attr])) return $attr;
-
+
$style = '';
foreach ($this->css[$this->attr] as $suffix) {
$property = "margin-$suffix";
$style .= "$property:{$width}px;";
}
-
+
$this->prependCSS($attr, $style);
-
+
return $attr;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
* input elements. This is meant to be a post-transform.
*/
class HTMLPurifier_AttrTransform_Input extends HTMLPurifier_AttrTransform {
-
+
protected $pixels;
-
+
public function __construct() {
$this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels();
}
-
+
public function transform($attr, $config, $context) {
if (!isset($attr['type'])) $t = 'text';
else $t = strtolower($attr['type']);
}
return $attr;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrTransform_Lang extends HTMLPurifier_AttrTransform
{
-
+
public function transform($attr, $config, $context) {
-
+
$lang = isset($attr['lang']) ? $attr['lang'] : false;
$xml_lang = isset($attr['xml:lang']) ? $attr['xml:lang'] : false;
-
+
if ($lang !== false && $xml_lang === false) {
$attr['xml:lang'] = $lang;
} elseif ($xml_lang !== false) {
$attr['lang'] = $xml_lang;
}
-
+
return $attr;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrTransform_Length extends HTMLPurifier_AttrTransform
{
-
+
protected $name;
protected $cssName;
-
+
public function __construct($name, $css_name = null) {
$this->name = $name;
$this->cssName = $css_name ? $css_name : $name;
}
-
+
public function transform($attr, $config, $context) {
if (!isset($attr[$this->name])) return $attr;
$length = $this->confiscateAttr($attr, $this->name);
$this->prependCSS($attr, $this->cssName . ":$length;");
return $attr;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrTransform_Name extends HTMLPurifier_AttrTransform
{
-
+
public function transform($attr, $config, $context) {
if (!isset($attr['name'])) return $attr;
$id = $this->confiscateAttr($attr, 'name');
$attr['id'] = $id;
return $attr;
}
-
+
}
+// vim: et sw=4 sts=4
<?php
-class HTMLPurifier_AttrTransform_SafeEmbed extends HTMLPurifier_AttrTransform
+class HTMLPurifier_AttrTransform_SafeEmbed extends HTMLPurifier_AttrTransform
{
public $name = "SafeEmbed";
return $attr;
}
}
+
+// vim: et sw=4 sts=4
return $attr;
}
}
+
+// vim: et sw=4 sts=4
* Validates name/value pairs in param tags to be used in safe objects. This
* will only allow name values it recognizes, and pre-fill certain attributes
* with required values.
- *
+ *
* @note
* This class only supports Flash. In the future, Quicktime support
* may be added.
- *
+ *
* @warning
* This class expects an injector to add the necessary parameters tags.
*/
-class HTMLPurifier_AttrTransform_SafeParam extends HTMLPurifier_AttrTransform
+class HTMLPurifier_AttrTransform_SafeParam extends HTMLPurifier_AttrTransform
{
public $name = "SafeParam";
private $uri;
-
+
public function __construct() {
$this->uri = new HTMLPurifier_AttrDef_URI(true); // embedded
}
-
+
public function transform($attr, $config, $context) {
// If we add support for other objects, we'll need to alter the
// transforms.
return $attr;
}
}
+
+// vim: et sw=4 sts=4
return $attr;
}
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform
{
-
+
public function transform($attr, $config, $context) {
// Calculated from Firefox
if (!isset($attr['cols'])) $attr['cols'] = '22';
if (!isset($attr['rows'])) $attr['rows'] = '3';
return $attr;
}
-
-}
\ No newline at end of file
+
+}
+
+// vim: et sw=4 sts=4
* Lookup array of attribute string identifiers to concrete implementations
*/
protected $info = array();
-
+
/**
* Constructs the info array, supplying default implementations for attribute
* types.
// pseudo-types, must be instantiated via shorthand
$this->info['Enum'] = new HTMLPurifier_AttrDef_Enum();
$this->info['Bool'] = new HTMLPurifier_AttrDef_HTML_Bool();
-
+
$this->info['CDATA'] = new HTMLPurifier_AttrDef_Text();
$this->info['ID'] = new HTMLPurifier_AttrDef_HTML_ID();
$this->info['Length'] = new HTMLPurifier_AttrDef_HTML_Length();
$this->info['URI'] = new HTMLPurifier_AttrDef_URI();
$this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang();
$this->info['Color'] = new HTMLPurifier_AttrDef_HTML_Color();
-
+
// unimplemented aliases
$this->info['ContentType'] = new HTMLPurifier_AttrDef_Text();
$this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text();
$this->info['Charsets'] = new HTMLPurifier_AttrDef_Text();
$this->info['Character'] = new HTMLPurifier_AttrDef_Text();
-
+
// number is really a positive integer (one or more digits)
// FIXME: ^^ not always, see start and value of list items
$this->info['Number'] = new HTMLPurifier_AttrDef_Integer(false, false, true);
}
-
+
/**
* Retrieves a type
* @param $type String type name
* @return Object AttrDef for type
*/
public function get($type) {
-
+
// determine if there is any extra info tacked on
if (strpos($type, '#') !== false) list($type, $string) = explode('#', $type, 2);
else $string = '';
-
+
if (!isset($this->info[$type])) {
trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR);
return;
}
-
+
return $this->info[$type]->make($string);
-
+
}
-
+
/**
* Sets a new implementation for a type
* @param $type String type name
}
}
-
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_AttrValidator
{
-
+
/**
* Validates the attributes of a token, returning a modified token
* that has valid tokens
* @param $context Instance of HTMLPurifier_Context
*/
public function validateToken(&$token, &$config, $context) {
-
+
$definition = $config->getHTMLDefinition();
$e =& $context->get('ErrorCollector', true);
-
+
// initialize IDAccumulator if necessary
$ok =& $context->get('IDAccumulator', true);
if (!$ok) {
$id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);
$context->register('IDAccumulator', $id_accumulator);
}
-
+
// initialize CurrentToken if necessary
$current_token =& $context->get('CurrentToken', true);
if (!$current_token) $context->register('CurrentToken', $token);
-
+
if (
!$token instanceof HTMLPurifier_Token_Start &&
!$token instanceof HTMLPurifier_Token_Empty
) return $token;
-
+
// create alias to global definition array, see also $defs
// DEFINITION CALL
$d_defs = $definition->info_global_attr;
-
+
// don't update token until the very end, to ensure an atomic update
$attr = $token->attr;
-
+
// do global transformations (pre)
// nothing currently utilizes this
foreach ($definition->info_attr_transform_pre as $transform) {
if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
}
}
-
+
// do local transformations only applicable to this element (pre)
// ex. <p align="right"> to <p style="text-align:right;">
foreach ($definition->info[$token->name]->attr_transform_pre as $transform) {
if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
}
}
-
+
// create alias to this element's attribute definition array, see
// also $d_defs (global attribute definition array)
// DEFINITION CALL
$defs = $definition->info[$token->name]->attr;
-
+
$attr_key = false;
$context->register('CurrentAttr', $attr_key);
-
+
// iterate through all the attribute keypairs
// Watch out for name collisions: $key has previously been used
foreach ($attr as $attr_key => $value) {
-
+
// call the definition
if ( isset($defs[$attr_key]) ) {
// there is a local definition defined
// system never heard of the attribute? DELETE!
$result = false;
}
-
+
// put the results into effect
if ($result === false || $result === null) {
// this is a generic error message that should replaced
// with more specific ones when possible
if ($e) $e->send(E_ERROR, 'AttrValidator: Attribute removed');
-
+
// remove the attribute
unset($attr[$attr_key]);
} elseif (is_string($result)) {
// generally, if a substitution is happening, there
// was some sort of implicit correction going on. We'll
// delegate it to the attribute classes to say exactly what.
-
+
// simple substitution
$attr[$attr_key] = $result;
} else {
// nothing happens
}
-
+
// we'd also want slightly more complicated substitution
// involving an array as the return value,
// although we're not sure how colliding attributes would
// resolve (certain ones would be completely overriden,
// others would prepend themselves).
}
-
+
$context->destroy('CurrentAttr');
-
+
// post transforms
-
+
// global (error reporting untested)
foreach ($definition->info_attr_transform_post as $transform) {
$attr = $transform->transform($o = $attr, $config, $context);
if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
}
}
-
+
// local (error reporting untested)
foreach ($definition->info[$token->name]->attr_transform_post as $transform) {
$attr = $transform->transform($o = $attr, $config, $context);
if ($attr != $o) $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
}
}
-
+
$token->attr = $attr;
-
+
// destroy CurrentToken if we made it ourselves
if (!$current_token) $context->destroy('CurrentToken');
-
+
}
-
-
+
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Bootstrap
{
-
+
/**
* Autoload function for HTML Purifier
* @param $class Class to load
require HTMLPURIFIER_PREFIX . '/' . $file;
return true;
}
-
+
/**
* Returns the path for a specific class.
*/
if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) return false;
return $file;
}
-
+
/**
* "Pre-registers" our autoloader on the SPL stack.
*/
foreach ($funcs as $func) spl_autoload_register($func);
}
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition
{
-
+
public $type = 'CSS';
-
+
/**
* Assoc array of attribute name to definition object.
*/
public $info = array();
-
+
/**
* Constructs the info array. The meat of this class.
*/
protected function doSetup($config) {
-
+
$this->info['text-align'] = new HTMLPurifier_AttrDef_Enum(
array('left', 'right', 'center', 'justify'), false);
-
+
$border_style =
- $this->info['border-bottom-style'] =
- $this->info['border-right-style'] =
- $this->info['border-left-style'] =
+ $this->info['border-bottom-style'] =
+ $this->info['border-right-style'] =
+ $this->info['border-left-style'] =
$this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum(
array('none', 'hidden', 'dotted', 'dashed', 'solid', 'double',
'groove', 'ridge', 'inset', 'outset'), false);
-
+
$this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style);
-
+
$this->info['clear'] = new HTMLPurifier_AttrDef_Enum(
array('none', 'left', 'right', 'both'), false);
$this->info['float'] = new HTMLPurifier_AttrDef_Enum(
array('normal', 'italic', 'oblique'), false);
$this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum(
array('normal', 'small-caps'), false);
-
+
$uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite(
array(
new HTMLPurifier_AttrDef_Enum(array('none')),
new HTMLPurifier_AttrDef_CSS_URI()
)
);
-
+
$this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum(
array('inside', 'outside'), false);
$this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum(
array('disc', 'circle', 'square', 'decimal', 'lower-roman',
'upper-roman', 'lower-alpha', 'upper-alpha', 'none'), false);
$this->info['list-style-image'] = $uri_or_none;
-
+
$this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config);
-
+
$this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum(
array('capitalize', 'uppercase', 'lowercase', 'none'), false);
$this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color();
-
+
$this->info['background-image'] = $uri_or_none;
$this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum(
array('repeat', 'repeat-x', 'repeat-y', 'no-repeat')
array('scroll', 'fixed')
);
$this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition();
-
- $border_color =
- $this->info['border-top-color'] =
- $this->info['border-bottom-color'] =
- $this->info['border-left-color'] =
- $this->info['border-right-color'] =
+
+ $border_color =
+ $this->info['border-top-color'] =
+ $this->info['border-bottom-color'] =
+ $this->info['border-left-color'] =
+ $this->info['border-right-color'] =
$this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_Enum(array('transparent')),
new HTMLPurifier_AttrDef_CSS_Color()
));
-
+
$this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config);
-
+
$this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color);
-
- $border_width =
- $this->info['border-top-width'] =
- $this->info['border-bottom-width'] =
- $this->info['border-left-width'] =
+
+ $border_width =
+ $this->info['border-top-width'] =
+ $this->info['border-bottom-width'] =
+ $this->info['border-left-width'] =
$this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')),
new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative
));
-
+
$this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width);
-
+
$this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_Enum(array('normal')),
new HTMLPurifier_AttrDef_CSS_Length()
));
-
+
$this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_Enum(array('normal')),
new HTMLPurifier_AttrDef_CSS_Length()
));
-
+
$this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_Enum(array('xx-small', 'x-small',
'small', 'medium', 'large', 'x-large', 'xx-large',
new HTMLPurifier_AttrDef_CSS_Percentage(),
new HTMLPurifier_AttrDef_CSS_Length()
));
-
+
$this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_Enum(array('normal')),
new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives
new HTMLPurifier_AttrDef_CSS_Length('0'),
new HTMLPurifier_AttrDef_CSS_Percentage(true)
));
-
+
$margin =
- $this->info['margin-top'] =
- $this->info['margin-bottom'] =
- $this->info['margin-left'] =
+ $this->info['margin-top'] =
+ $this->info['margin-bottom'] =
+ $this->info['margin-left'] =
$this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_CSS_Length(),
new HTMLPurifier_AttrDef_CSS_Percentage(),
new HTMLPurifier_AttrDef_Enum(array('auto'))
));
-
+
$this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin);
-
+
// non-negative
$padding =
- $this->info['padding-top'] =
- $this->info['padding-bottom'] =
- $this->info['padding-left'] =
+ $this->info['padding-top'] =
+ $this->info['padding-bottom'] =
+ $this->info['padding-left'] =
$this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_CSS_Length('0'),
new HTMLPurifier_AttrDef_CSS_Percentage(true)
));
-
+
$this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding);
-
+
$this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_CSS_Length(),
new HTMLPurifier_AttrDef_CSS_Percentage()
));
-
+
$trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_CSS_Length('0'),
new HTMLPurifier_AttrDef_CSS_Percentage(true),
new HTMLPurifier_AttrDef_Enum(array('auto'))
));
$max = $config->get('CSS', 'MaxImgLength');
-
+
$this->info['width'] =
$this->info['height'] =
$max === null ?
- $trusted_wh :
+ $trusted_wh :
new HTMLPurifier_AttrDef_Switch('img',
// For img tags:
new HTMLPurifier_AttrDef_CSS_Composite(array(
// For everyone else:
$trusted_wh
);
-
+
$this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration();
-
+
$this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily();
-
+
// this could use specialized code
$this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum(
array('normal', 'bold', 'bolder', 'lighter', '100', '200', '300',
'400', '500', '600', '700', '800', '900'), false);
-
+
// MUST be called after other font properties, as it references
// a CSSDefinition object
$this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config);
-
+
// same here
$this->info['border'] =
- $this->info['border-bottom'] =
- $this->info['border-top'] =
- $this->info['border-left'] =
+ $this->info['border-bottom'] =
+ $this->info['border-top'] =
+ $this->info['border-left'] =
$this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config);
-
+
$this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum(array(
'collapse', 'separate'));
-
+
$this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum(array(
'top', 'bottom'));
-
+
$this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum(array(
'auto', 'fixed'));
-
+
$this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite(array(
new HTMLPurifier_AttrDef_Enum(array('baseline', 'sub', 'super',
'top', 'text-top', 'middle', 'bottom', 'text-bottom')),
new HTMLPurifier_AttrDef_CSS_Length(),
new HTMLPurifier_AttrDef_CSS_Percentage()
));
-
+
$this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2);
-
+
// partial support
$this->info['white-space'] = new HTMLPurifier_AttrDef_Enum(array('nowrap'));
-
+
if ($config->get('CSS', 'Proprietary')) {
$this->doSetupProprietary($config);
}
-
+
if ($config->get('CSS', 'AllowTricky')) {
$this->doSetupTricky($config);
}
-
+
$allow_important = $config->get('CSS', 'AllowImportant');
// wrap all attr-defs with decorator that handles !important
foreach ($this->info as $k => $v) {
$this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important);
}
-
+
$this->setupConfigStuff($config);
}
-
+
protected function doSetupProprietary($config) {
// Internet Explorer only scrollbar colors
$this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
$this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color();
$this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color();
$this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
-
+
// technically not proprietary, but CSS3, and no one supports it
$this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
$this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
$this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
-
+
// only opacity, for now
$this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter();
-
+
}
-
+
protected function doSetupTricky($config) {
$this->info['display'] = new HTMLPurifier_AttrDef_Enum(array(
'inline', 'block', 'list-item', 'run-in', 'compact',
$this->info['visibility'] = new HTMLPurifier_AttrDef_Enum(array(
'visible', 'hidden', 'collapse'
));
+ $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll'));
}
-
-
+
+
/**
* Performs extra config-based processing. Based off of
* HTMLPurifier_HTMLDefinition.
* composition, not inheritance).
*/
protected function setupConfigStuff($config) {
-
+
// setup allowed elements
$support = "(for information on implementing this, see the ".
"support forums) ";
trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING);
}
}
-
+
}
}
+// vim: et sw=4 sts=4
* Used occasionally in terms of context.
*/
public $type;
-
+
/**
* Bool that indicates whether or not an empty array of children is okay
- *
+ *
* This is necessary for redundant checking when changes affecting
* a child node may cause a parent node to now be disallowed.
*/
public $allow_empty;
-
+
/**
* Lookup array of all elements that this definition could possibly allow
*/
public $elements = array();
-
+
/**
* Get lookup of tag names that should not close this element automatically.
* All other elements will do so.
*/
- public function getNonAutoCloseElements($config) {
+ public function getAllowedElements($config) {
return $this->elements;
}
-
+
/**
* Validates nodes according to definition and returns modification.
- *
+ *
* @param $tokens_of_children Array of HTMLPurifier_Token
* @param $config HTMLPurifier_Config object
* @param $context HTMLPurifier_Context object
abstract public function validateChildren($tokens_of_children, $config, $context);
}
-
+// vim: et sw=4 sts=4
/**
* Definition that uses different definitions depending on context.
- *
+ *
* The del and ins tags are notable because they allow different types of
* elements depending on whether or not they're in a block or inline context.
* Chameleon allows this behavior to happen by using two different
*/
class HTMLPurifier_ChildDef_Chameleon extends HTMLPurifier_ChildDef
{
-
+
/**
* Instance of the definition object to use when inline. Usually stricter.
*/
public $inline;
-
+
/**
* Instance of the definition object to use when block.
*/
public $block;
-
+
public $type = 'chameleon';
-
+
/**
* @param $inline List of elements to allow when inline.
* @param $block List of elements to allow when block.
$this->block = new HTMLPurifier_ChildDef_Optional($block);
$this->elements = $this->block->elements;
}
-
+
public function validateChildren($tokens_of_children, $config, $context) {
if ($context->get('IsInline') === false) {
return $this->block->validateChildren(
}
}
+// vim: et sw=4 sts=4
/**
* Custom validation class, accepts DTD child definitions
- *
+ *
* @warning Currently this class is an all or nothing proposition, that is,
* it will only give a bool return value.
*/
}
$el = '[#a-zA-Z0-9_.-]+';
$reg = $raw;
-
+
// COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M
// DOING! Seriously: if there's problems, please report them.
-
+
// collect all elements into the $elements array
preg_match_all("/$el/", $reg, $matches);
foreach ($matches[0] as $match) {
$this->elements[$match] = true;
}
-
+
// setup all elements as parentheticals with leading commas
$reg = preg_replace("/$el/", '(,\\0)', $reg);
-
+
// remove commas when they were not solicited
$reg = preg_replace("/([^,(|]\(+),/", '\\1', $reg);
-
+
// remove all non-paranthetical commas: they are handled by first regex
$reg = preg_replace("/,\(/", '(', $reg);
-
+
$this->_pcre_regex = $reg;
}
public function validateChildren($tokens_of_children, $config, $context) {
$nesting = 0; // depth into the nest
foreach ($tokens_of_children as $token) {
if (!empty($token->is_whitespace)) continue;
-
+
$is_child = ($nesting == 0); // direct
-
+
if ($token instanceof HTMLPurifier_Token_Start) {
$nesting++;
} elseif ($token instanceof HTMLPurifier_Token_End) {
$nesting--;
}
-
+
if ($is_child) {
$list_of_children .= $token->name . ',';
}
'/^,?'.$this->_pcre_regex.'$/',
$list_of_children
);
-
+
return (bool) $okay;
}
}
+// vim: et sw=4 sts=4
}
}
+// vim: et sw=4 sts=4
public $type = 'optional';
public function validateChildren($tokens_of_children, $config, $context) {
$result = parent::validateChildren($tokens_of_children, $config, $context);
+ // we assume that $tokens_of_children is not modified
if ($result === false) {
if (empty($tokens_of_children)) return true;
+ elseif ($this->whitespace) return $tokens_of_children;
else return array();
}
return $result;
}
}
+// vim: et sw=4 sts=4
* @public
*/
public $elements = array();
+ /**
+ * Whether or not the last passed node was all whitespace.
+ */
+ protected $whitespace = false;
/**
* @param $elements List of allowed element names (lowercase).
*/
public $allow_empty = false;
public $type = 'required';
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])) {
}
}
if (empty($result)) return false;
- if ($all_whitespace) return false;
+ if ($all_whitespace) {
+ $this->whitespace = true;
+ return false;
+ }
if ($tokens_of_children == $result) return true;
return $result;
}
}
+// vim: et sw=4 sts=4
public $allow_empty = true;
public $type = 'strictblockquote';
protected $init = false;
-
+
/**
* @note We don't want MakeWellFormed to auto-close inline elements since
* they might be allowed.
*/
- public function getNonAutoCloseElements($config) {
+ public function getAllowedElements($config) {
$this->init($config);
return $this->fake_elements;
}
-
+
public function validateChildren($tokens_of_children, $config, $context) {
-
+
$this->init($config);
-
+
// trick the parent class into thinking it allows more
$this->elements = $this->fake_elements;
$result = parent::validateChildren($tokens_of_children, $config, $context);
$this->elements = $this->real_elements;
-
+
if ($result === false) return array();
if ($result === true) $result = $tokens_of_children;
-
+
$def = $config->getHTMLDefinition();
$block_wrap_start = new HTMLPurifier_Token_Start($def->info_block_wrapper);
$block_wrap_end = new HTMLPurifier_Token_End( $def->info_block_wrapper);
$is_inline = false;
$depth = 0;
$ret = array();
-
+
// assuming that there are no comment tokens
foreach ($result as $i => $token) {
$token = $result[$i];
if ($is_inline) $ret[] = $block_wrap_end;
return $ret;
}
-
+
private function init($config) {
if (!$this->init) {
$def = $config->getHTMLDefinition();
}
}
+// vim: et sw=4 sts=4
public function __construct() {}
public function validateChildren($tokens_of_children, $config, $context) {
if (empty($tokens_of_children)) return false;
-
+
// this ensures that the loop gets run one last time before closing
// up. It's a little bit of a hack, but it works! Just make sure you
// get rid of the token later.
$tokens_of_children[] = false;
-
+
// only one of these elements is allowed in a table
$caption = false;
$thead = false;
$tfoot = false;
-
+
// as many of these as you want
$cols = array();
$content = array();
-
+
$nesting = 0; // current depth so we can determine nodes
$is_collecting = false; // are we globbing together tokens to package
// into one of the collectors?
$collection = array(); // collected nodes
$tag_index = 0; // the first node might be whitespace,
// so this tells us where the start tag is
-
+
foreach ($tokens_of_children as $token) {
$is_child = ($nesting == 0);
-
+
if ($token === false) {
// terminating sequence started
} elseif ($token instanceof HTMLPurifier_Token_Start) {
} elseif ($token instanceof HTMLPurifier_Token_End) {
$nesting--;
}
-
+
// handle node collection
if ($is_collecting) {
if ($is_child) {
$collection[] = $token;
}
}
-
+
// terminate
if ($token === false) break;
-
+
if ($is_child) {
// determine what we're dealing with
if ($token->name == 'col') {
$collection[] = $token;
continue;
default:
- if ($token instanceof HTMLPurifier_Token_Text && $token->is_whitespace) {
+ if (!empty($token->is_whitespace)) {
$collection[] = $token;
$tag_index++;
}
}
}
}
-
+
if (empty($content)) return false;
-
+
$ret = array();
if ($caption !== false) $ret = array_merge($ret, $caption);
if ($cols !== false) foreach ($cols as $token_array) $ret = array_merge($ret, $token_array);
// grab the trailing space
$ret = array_merge($ret, $collection);
}
-
+
array_pop($tokens_of_children); // remove phantom token
-
+
return ($ret === $tokens_of_children) ? true : $ret;
-
+
}
}
+// vim: et sw=4 sts=4
*
* @warning This class is strongly defined: that means that the class
* will fail if an undefined directive is retrieved or set.
- *
+ *
* @note Many classes that could (although many times don't) use the
* configuration object make it a mandatory parameter. This is
* because a configuration object should always be forwarded,
* otherwise, you run the risk of missing a parameter and then
* being stumped when a configuration directive doesn't work.
- *
+ *
* @todo Reconsider some of the public member variables
*/
class HTMLPurifier_Config
{
-
+
/**
* HTML Purifier's version
*/
- public $version = '3.2.0';
-
+ public $version = '3.3.0';
+
/**
- * Bool indicator whether or not to automatically finalize
+ * Bool indicator whether or not to automatically finalize
* the object if a read operation is done
*/
public $autoFinalize = true;
-
+
// protected member variables
-
+
/**
* Namespace indexed array of serials for specific namespaces (see
* getSerial() for more info).
*/
protected $serials = array();
-
+
/**
* Serial for entire configuration object
*/
protected $serial;
-
- /**
- * Two-level associative array of configuration directives
- */
- protected $conf;
-
+
/**
* Parser for variables
*/
protected $parser;
-
+
/**
* Reference HTMLPurifier_ConfigSchema for value checking
* @note This is public for introspective purposes. Please don't
* abuse!
*/
public $def;
-
+
/**
* Indexed array of definitions
*/
protected $definitions;
-
+
/**
* Bool indicator whether or not config is finalized
*/
protected $finalized = false;
-
+
+ /**
+ * Property list containing configuration directives.
+ */
+ protected $plist;
+
/**
* @param $definition HTMLPurifier_ConfigSchema that defines what directives
* are allowed.
*/
public function __construct($definition) {
- $this->conf = $definition->defaults; // set up, copy in defaults
- $this->def = $definition; // keep a copy around for checking
+ $this->plist = new HTMLPurifier_PropertyList($definition->defaultPlist);
+ $this->def = $definition; // keep a copy around for checking
$this->parser = new HTMLPurifier_VarParser_Flexible();
}
-
+
/**
* Convenience constructor that creates a config object based on a mixed var
* @param mixed $config Variable that defines the state of the config
elseif (is_array($config)) $ret->loadArray($config);
return $ret;
}
-
+
/**
* Convenience constructor that creates a default configuration object.
* @return Default HTMLPurifier_Config object.
$config = new HTMLPurifier_Config($definition);
return $config;
}
-
+
/**
* Retreives a value from the configuration.
* @param $namespace String namespace
* @param $key String key
*/
public function get($namespace, $key) {
- if (!$this->finalized && $this->autoFinalize) $this->finalize();
+ if (!$this->finalized) $this->autoFinalize ? $this->finalize() : $this->plist->squash(true);
if (!isset($this->def->info[$namespace][$key])) {
// can't add % due to SimpleTest bug
trigger_error('Cannot retrieve value of undefined directive ' . htmlspecialchars("$namespace.$key"),
E_USER_ERROR);
return;
}
- return $this->conf[$namespace][$key];
+ return $this->plist->get("$namespace.$key");
}
-
+
/**
* Retreives an array of directives to values from a given namespace
* @param $namespace String namespace
*/
public function getBatch($namespace) {
- if (!$this->finalized && $this->autoFinalize) $this->finalize();
+ if (!$this->finalized) $this->autoFinalize ? $this->finalize() : $this->plist->squash(true);
if (!isset($this->def->info[$namespace])) {
trigger_error('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace),
E_USER_WARNING);
return;
}
- return $this->conf[$namespace];
+ $full = $this->getAll();
+ return $full[$namespace];
}
-
+
/**
* Returns a md5 signature of a segment of the configuration object
* that uniquely identifies that particular configuration
}
return $this->serials[$namespace];
}
-
+
/**
* Returns a md5 signature for the entire configuration object
* that uniquely identifies that particular configuration
}
return $this->serial;
}
-
+
/**
* Retrieves all directives, organized by namespace
*/
public function getAll() {
- if (!$this->finalized && $this->autoFinalize) $this->finalize();
- return $this->conf;
+ if (!$this->finalized) $this->autoFinalize ? $this->finalize() : $this->plist->squash(true);
+ $ret = array();
+ foreach ($this->plist->squash() as $name => $value) {
+ list($ns, $key) = explode('.', $name, 2);
+ $ret[$ns][$key] = $value;
+ }
+ return $ret;
}
-
+
/**
* Sets a value to configuration.
* @param $namespace String namespace
return;
}
$def = $this->def->info[$namespace][$key];
-
+
if (isset($def->isAlias)) {
if ($from_alias) {
trigger_error('Double-aliases not allowed, please fix '.
trigger_error("$namespace.$key is an alias, preferred directive name is $new_ns.$new_dir", E_USER_NOTICE);
return;
}
-
+
// Raw type might be negative when using the fully optimized form
// of stdclass, which indicates allow_null == true
$rtype = is_int($def) ? $def : $def->type;
$type = $rtype;
$allow_null = isset($def->allow_null);
}
-
+
try {
$value = $this->parser->parse($value, $type, $allow_null);
} catch (HTMLPurifier_VarParserException $e) {
return;
}
}
- $this->conf[$namespace][$key] = $value;
-
+ $this->plist->set("$namespace.$key", $value);
+
// reset definitions if the directives they depend on changed
- // this is a very costly process, so it's discouraged
+ // this is a very costly process, so it's discouraged
// with finalization
if ($namespace == 'HTML' || $namespace == 'CSS') {
$this->definitions[$namespace] = null;
}
-
+
$this->serials[$namespace] = false;
}
-
+
/**
* Convenience function for error reporting
*/
foreach ($lookup as $name => $b) $list[] = $name;
return implode(', ', $list);
}
-
+
/**
* Retrieves object reference to the HTML definition.
* @param $raw Return a copy that has not been setup yet. Must be
public function getHTMLDefinition($raw = false) {
return $this->getDefinition('HTML', $raw);
}
-
+
/**
* Retrieves object reference to the CSS definition
* @param $raw Return a copy that has not been setup yet. Must be
public function getCSSDefinition($raw = false) {
return $this->getDefinition('CSS', $raw);
}
-
+
/**
* Retrieves a definition
* @param $type Type of definition: HTML, CSS, etc
* @param $raw Whether or not definition should be returned raw
*/
public function getDefinition($type, $raw = false) {
- if (!$this->finalized && $this->autoFinalize) $this->finalize();
+ if (!$this->finalized) $this->autoFinalize ? $this->finalize() : $this->plist->squash(true);
$factory = HTMLPurifier_DefinitionCacheFactory::instance();
$cache = $factory->create($type, $this);
if (!$raw) {
$cache->set($this->definitions[$type], $this);
return $this->definitions[$type];
}
-
+
/**
* Loads configuration values from an array with the following structure:
* Namespace.Directive => Value
}
}
}
-
+
/**
* Returns a list of array(namespace, directive) for all directives
* that are allowed in a web-form context as per an allowed
}
return $ret;
}
-
+
/**
* 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 $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
*/
$config = HTMLPurifier_Config::create($ret, $schema);
return $config;
}
-
+
/**
* Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
* @note Same parameters as loadArrayFromForm
$ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
$this->loadArray($ret);
}
-
+
/**
* Prepares an array from a form into something usable for the more
* strict parts of HTMLPurifier_Config
public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
$mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
-
+
$allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
$ret = array();
foreach ($allowed as $key) {
}
return $ret;
}
-
+
/**
* Loads configuration values from an ini file
* @param $filename Name of ini file
$array = parse_ini_file($filename, true);
$this->loadArray($array);
}
-
+
/**
* Checks whether or not the configuration object is finalized.
* @param $error String error message, or false for no error
}
return $this->finalized;
}
-
+
/**
* Finalizes configuration only if auto finalize is on and not
* already finalized
public function autoFinalize() {
if (!$this->finalized && $this->autoFinalize) $this->finalize();
}
-
+
/**
* Finalizes a configuration object, prohibiting further change
*/
public function finalize() {
$this->finalized = true;
}
-
-}
-
+}
+// vim: et sw=4 sts=4
+++ /dev/null
-<?php
-
-/**
- * Base class for configuration entity
- */
-abstract class HTMLPurifier_ConfigDef {
- public $class = false;
-}
-
+++ /dev/null
-<?php
-
-/**
- * Structure object containing definition of a directive.
- * @note This structure does not contain default values
- */
-class HTMLPurifier_ConfigDef_Directive extends HTMLPurifier_ConfigDef
-{
-
- public $class = 'directive';
-
- public function __construct(
- $type = null,
- $allow_null = null,
- $allowed = null,
- $aliases = null
- ) {
- if ( $type !== null) $this->type = $type;
- if ( $allow_null !== null) $this->allow_null = $allow_null;
- if ( $allowed !== null) $this->allowed = $allowed;
- if ( $aliases !== null) $this->aliases = $aliases;
- }
-
- /**
- * Allowed type of the directive. Values are:
- * - string
- * - istring (case insensitive string)
- * - int
- * - float
- * - bool
- * - lookup (array of value => true)
- * - list (regular numbered index array)
- * - hash (array of key => value)
- * - mixed (anything goes)
- */
- public $type = 'mixed';
-
- /**
- * Is null allowed? Has no effect for mixed type.
- * @bool
- */
- public $allow_null = false;
-
- /**
- * Lookup table of allowed values of the element, bool true if all allowed.
- */
- public $allowed = true;
-
- /**
- * Hash of value aliases, i.e. values that are equivalent.
- */
- public $aliases = array();
-
-}
-
+++ /dev/null
-<?php
-
-/**
- * Structure object describing a directive alias
- */
-class HTMLPurifier_ConfigDef_DirectiveAlias extends HTMLPurifier_ConfigDef
-{
- public $class = 'alias';
-
- /**
- * Namespace being aliased to
- */
- public $namespace;
- /**
- * Directive being aliased to
- */
- public $name;
-
- public function __construct($namespace, $name) {
- $this->namespace = $namespace;
- $this->name = $name;
- }
-}
-
+++ /dev/null
-<?php
-
-/**
- * Structure object describing of a namespace
- */
-class HTMLPurifier_ConfigDef_Namespace extends HTMLPurifier_ConfigDef
-{
- public $class = 'namespace';
-}
-
* Configuration definition, defines directives and their defaults.
*/
class HTMLPurifier_ConfigSchema {
-
+
/**
* Defaults of the directives and namespaces.
* @note This shares the exact same structure as HTMLPurifier_Config::$conf
*/
public $defaults = array();
-
+
+ /**
+ * The default property list. Do not edit this property list.
+ */
+ public $defaultPlist;
+
/**
* Definition of the directives. The structure of this is:
- *
+ *
* array(
* 'Namespace' => array(
* 'Directive' => new stdclass(),
* )
* )
- *
+ *
* The stdclass may have the following properties:
- *
+ *
* - If isAlias isn't set:
* - type: Integer type of directive, see HTMLPurifier_VarParser for definitions
* - allow_null: If set, this directive allows null values
* - If isAlias is set:
* - namespace: Namespace this directive aliases to
* - name: Directive name this directive aliases to
- *
+ *
* In certain degenerate cases, stdclass will actually be an integer. In
* that case, the value is equivalent to an stdclass with the type
* property set to the integer. If the integer is negative, type is
* equal to the absolute value of integer, and allow_null is true.
- *
+ *
* This class is friendly with HTMLPurifier_Config. If you need introspection
* about the schema, you're better of using the ConfigSchema_Interchange,
* which uses more memory but has much richer information.
*/
public $info = array();
-
+
/**
* Application-wide singleton
*/
static protected $singleton;
-
+
+ public function __construct() {
+ $this->defaultPlist = new HTMLPurifier_PropertyList();
+ }
+
/**
* Unserializes the default ConfigSchema.
*/
public static function makeFromSerial() {
return unserialize(file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser'));
}
-
+
/**
* Retrieves an instance of the application-wide configuration definition.
*/
}
return HTMLPurifier_ConfigSchema::$singleton;
}
-
+
/**
* Defines a directive for configuration
* @warning Will fail of directive's namespace is defined.
if ($allow_null) $obj->allow_null = true;
$this->info[$namespace][$name] = $obj;
$this->defaults[$namespace][$name] = $default;
+ $this->defaultPlist->set("$namespace.$name", $default);
}
-
+
/**
* Defines a namespace for directives to be put into.
* @warning This is slightly different from the corresponding static
$this->info[$namespace] = array();
$this->defaults[$namespace] = array();
}
-
+
/**
* Defines a directive value alias.
- *
+ *
* Directive value aliases are convenient for developers because it lets
* them set a directive to several values and get the same result.
* @param $namespace Directive's namespace
$this->info[$namespace][$name]->aliases[$alias] = $real;
}
}
-
+
/**
* Defines a set of allowed values for a directive.
* @warning This is slightly different from the corresponding static
public function addAllowedValues($namespace, $name, $allowed) {
$this->info[$namespace][$name]->allowed = $allowed;
}
-
+
/**
* Defines a directive alias for backwards compatibility
* @param $namespace
$obj->isAlias = true;
$this->info[$namespace][$name] = $obj;
}
-
+
/**
* Replaces any stdclass that only has the type property with type integer.
*/
}
}
}
-
+
// DEPRECATED METHODS
-
+
/** @see HTMLPurifier_ConfigSchema->set() */
public static function define($namespace, $name, $default, $type, $description) {
HTMLPurifier_ConfigSchema::deprecated(__METHOD__);
$def = HTMLPurifier_ConfigSchema::instance();
$def->add($namespace, $name, $default, $type, $allow_null);
}
-
+
/** @see HTMLPurifier_ConfigSchema->addNamespace() */
public static function defineNamespace($namespace, $description) {
HTMLPurifier_ConfigSchema::deprecated(__METHOD__);
$def = HTMLPurifier_ConfigSchema::instance();
$def->addNamespace($namespace);
}
-
+
/** @see HTMLPurifier_ConfigSchema->addValueAliases() */
public static function defineValueAliases($namespace, $name, $aliases) {
HTMLPurifier_ConfigSchema::deprecated(__METHOD__);
$def = HTMLPurifier_ConfigSchema::instance();
$def->addValueAliases($namespace, $name, $aliases);
}
-
+
/** @see HTMLPurifier_ConfigSchema->addAllowedValues() */
public static function defineAllowedValues($namespace, $name, $allowed_values) {
HTMLPurifier_ConfigSchema::deprecated(__METHOD__);
$def = HTMLPurifier_ConfigSchema::instance();
$def->addAllowedValues($namespace, $name, $allowed);
}
-
+
/** @see HTMLPurifier_ConfigSchema->addAlias() */
public static function defineAlias($namespace, $name, $new_namespace, $new_name) {
HTMLPurifier_ConfigSchema::deprecated(__METHOD__);
$def = HTMLPurifier_ConfigSchema::instance();
$def->addAlias($namespace, $name, $new_namespace, $new_name);
}
-
+
/** @deprecated, use HTMLPurifier_VarParser->parse() */
public function validate($a, $b, $c = false) {
trigger_error("HTMLPurifier_ConfigSchema->validate deprecated, use HTMLPurifier_VarParser->parse instead", E_USER_NOTICE);
$parser = new HTMLPurifier_VarParser();
return $parser->parse($a, $b, $c);
}
-
+
/**
* Throws an E_USER_NOTICE stating that a method is deprecated.
*/
private static function deprecated($method) {
trigger_error("Static HTMLPurifier_ConfigSchema::$method deprecated, use add*() method instead", E_USER_NOTICE);
}
-
-}
+}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_Builder_ConfigSchema
{
-
+
public function build($interchange) {
$schema = new HTMLPurifier_ConfigSchema();
foreach ($interchange->namespaces as $n) {
$schema->postProcess();
return $schema;
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_Builder_Xml extends XMLWriter
{
-
+
protected $interchange;
-
+
protected function writeHTMLDiv($html) {
$this->startElement('div');
-
+
$purifier = HTMLPurifier::getInstance();
$html = $purifier->purify($html);
$this->writeAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
$this->writeRaw($html);
-
+
$this->endElement(); // div
}
-
+
protected function export($var) {
if ($var === array()) return 'array()';
return var_export($var, true);
}
-
+
public function build($interchange) {
// global access, only use as last resort
$this->interchange = $interchange;
-
+
$this->setIndent(true);
$this->startDocument('1.0', 'UTF-8');
$this->startElement('configdoc');
$this->writeElement('title', $interchange->name);
-
+
foreach ($interchange->namespaces as $namespace) {
$this->buildNamespace($namespace);
}
-
+
$this->endElement(); // configdoc
$this->flush();
}
-
+
public function buildNamespace($namespace) {
$this->startElement('namespace');
$this->writeAttribute('id', $namespace->namespace);
-
+
$this->writeElement('name', $namespace->namespace);
$this->startElement('description');
$this->writeHTMLDiv($namespace->description);
$this->endElement(); // description
-
+
foreach ($this->interchange->directives as $directive) {
if ($directive->id->namespace !== $namespace->namespace) continue;
$this->buildDirective($directive);
}
-
+
$this->endElement(); // namespace
}
-
+
public function buildDirective($directive) {
$this->startElement('directive');
$this->writeAttribute('id', $directive->id->toString());
-
+
$this->writeElement('name', $directive->id->directive);
-
+
$this->startElement('aliases');
foreach ($directive->aliases as $alias) $this->writeElement('alias', $alias->toString());
$this->endElement(); // aliases
-
+
$this->startElement('constraints');
if ($directive->version) $this->writeElement('version', $directive->version);
$this->startElement('type');
$this->endElement();
}
$this->endElement(); // constraints
-
+
if ($directive->deprecatedVersion) {
$this->startElement('deprecated');
$this->writeElement('version', $directive->deprecatedVersion);
$this->writeElement('use', $directive->deprecatedUse->toString());
$this->endElement(); // deprecated
}
-
+
$this->startElement('description');
$this->writeHTMLDiv($directive->description);
$this->endElement(); // description
-
+
$this->endElement(); // directive
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_Exception extends HTMLPurifier_Exception
{
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_Interchange
{
-
+
/**
* Name of the application this schema is describing.
*/
public $name;
-
+
/**
* Array of Namespace ID => array(namespace info)
*/
public $namespaces = array();
-
+
/**
* Array of Directive ID => array(directive info)
*/
public $directives = array();
-
+
/**
* Adds a namespace array to $namespaces
*/
}
$this->namespaces[$i] = $namespace;
}
-
+
/**
* Adds a directive array to $directives
*/
}
$this->directives[$i] = $directive;
}
-
+
/**
* Convenience function to perform standard validation. Throws exception
* on failed validation.
$validator = new HTMLPurifier_ConfigSchema_Validator();
return $validator->validate($this);
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_Interchange_Directive
{
-
+
/**
* ID of directive, instance of HTMLPurifier_ConfigSchema_Interchange_Id.
*/
public $id;
-
+
/**
* String type, e.g. 'integer' or 'istring'.
*/
public $type;
-
+
/**
* Default value, e.g. 3 or 'DefaultVal'.
*/
public $default;
-
+
/**
* HTML description.
*/
public $description;
-
+
/**
* Boolean whether or not null is allowed as a value.
*/
public $typeAllowsNull = false;
-
+
/**
* Lookup table of allowed scalar values, e.g. array('allowed' => true).
* Null if all values are allowed.
*/
public $allowed;
-
+
/**
* List of aliases for the directive,
* e.g. array(new HTMLPurifier_ConfigSchema_Interchange_Id('Ns', 'Dir'))).
*/
public $aliases = array();
-
+
/**
* Hash of value aliases, e.g. array('alt' => 'real'). Null if value
* aliasing is disabled (necessary for non-scalar types).
*/
public $valueAliases;
-
+
/**
* Version of HTML Purifier the directive was introduced, e.g. '1.3.1'.
* Null if the directive has always existed.
*/
public $version;
-
+
/**
* ID of directive that supercedes this old directive, is an instance
* of HTMLPurifier_ConfigSchema_Interchange_Id. Null if not deprecated.
*/
public $deprecatedUse;
-
+
/**
* Version of HTML Purifier this directive was deprecated. Null if not
* deprecated.
*/
public $deprecatedVersion;
-
+
/**
* List of external projects this directive depends on, e.g. array('CSSTidy').
*/
public $external = array();
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_Interchange_Id
{
-
+
public $namespace, $directive;
-
+
public function __construct($namespace, $directive) {
$this->namespace = $namespace;
$this->directive = $directive;
}
-
+
/**
* @warning This is NOT magic, to ensure that people don't abuse SPL and
* cause problems for PHP 5.0 support.
public function toString() {
return $this->namespace . '.' . $this->directive;
}
-
+
public static function make($id) {
list($namespace, $directive) = explode('.', $id);
return new HTMLPurifier_ConfigSchema_Interchange_Id($namespace, $directive);
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_Interchange_Namespace
{
-
+
/**
* Name of namespace defined.
*/
public $namespace;
-
+
/**
* HTML description.
*/
public $description;
-
+
}
+
+// vim: et sw=4 sts=4
class HTMLPurifier_ConfigSchema_InterchangeBuilder
{
-
+
/**
* Used for processing DEFAULT, nothing else.
*/
protected $varParser;
-
+
public function __construct($varParser = null) {
$this->varParser = $varParser ? $varParser : new HTMLPurifier_VarParser_Native();
}
-
+
public static function buildFromDirectory($dir = null) {
$parser = new HTMLPurifier_StringHashParser();
$builder = new HTMLPurifier_ConfigSchema_InterchangeBuilder();
$interchange = new HTMLPurifier_ConfigSchema_Interchange();
-
+
if (!$dir) $dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema/';
$info = parse_ini_file($dir . 'info.ini');
$interchange->name = $info['name'];
-
+
$files = array();
$dh = opendir($dir);
while (false !== ($file = readdir($dh))) {
$files[] = $file;
}
closedir($dh);
-
+
sort($files);
foreach ($files as $file) {
$builder->build(
new HTMLPurifier_StringHash( $parser->parseFile($dir . $file) )
);
}
-
+
return $interchange;
}
-
+
/**
* Builds an interchange object based on a hash.
* @param $interchange HTMLPurifier_ConfigSchema_Interchange object to build
}
$this->_findUnused($hash);
}
-
+
public function buildNamespace($interchange, $hash) {
$namespace = new HTMLPurifier_ConfigSchema_Interchange_Namespace();
$namespace->namespace = $hash->offsetGet('ID');
}
$interchange->addNamespace($namespace);
}
-
+
public function buildDirective($interchange, $hash) {
$directive = new HTMLPurifier_ConfigSchema_Interchange_Directive();
-
+
// These are required elements:
$directive->id = $this->id($hash->offsetGet('ID'));
$id = $directive->id->toString(); // convenience
-
+
if (isset($hash['TYPE'])) {
$type = explode('/', $hash->offsetGet('TYPE'));
if (isset($type[1])) $directive->typeAllowsNull = true;
} else {
throw new HTMLPurifier_ConfigSchema_Exception("TYPE in directive hash '$id' not defined");
}
-
+
if (isset($hash['DEFAULT'])) {
try {
$directive->default = $this->varParser->parse($hash->offsetGet('DEFAULT'), $directive->type, $directive->typeAllowsNull);
throw new HTMLPurifier_ConfigSchema_Exception($e->getMessage() . " in DEFAULT in directive hash '$id'");
}
}
-
+
if (isset($hash['DESCRIPTION'])) {
$directive->description = $hash->offsetGet('DESCRIPTION');
}
-
+
if (isset($hash['ALLOWED'])) {
$directive->allowed = $this->lookup($this->evalArray($hash->offsetGet('ALLOWED')));
}
-
+
if (isset($hash['VALUE-ALIASES'])) {
$directive->valueAliases = $this->evalArray($hash->offsetGet('VALUE-ALIASES'));
}
-
+
if (isset($hash['ALIASES'])) {
$raw_aliases = trim($hash->offsetGet('ALIASES'));
$aliases = preg_split('/\s*,\s*/', $raw_aliases);
$directive->aliases[] = $this->id($alias);
}
}
-
+
if (isset($hash['VERSION'])) {
$directive->version = $hash->offsetGet('VERSION');
}
-
+
if (isset($hash['DEPRECATED-USE'])) {
$directive->deprecatedUse = $this->id($hash->offsetGet('DEPRECATED-USE'));
}
-
+
if (isset($hash['DEPRECATED-VERSION'])) {
$directive->deprecatedVersion = $hash->offsetGet('DEPRECATED-VERSION');
}
-
+
if (isset($hash['EXTERNAL'])) {
$directive->external = preg_split('/\s*,\s*/', trim($hash->offsetGet('EXTERNAL')));
}
-
+
$interchange->addDirective($directive);
}
-
+
/**
* Evaluates an array PHP code string without array() wrapper
*/
protected function evalArray($contents) {
return eval('return array('. $contents .');');
}
-
+
/**
* Converts an array list into a lookup array.
*/
foreach ($array as $val) $ret[$val] = true;
return $ret;
}
-
+
/**
* Convenience function that creates an HTMLPurifier_ConfigSchema_Interchange_Id
* object based on a string Id.
protected function id($id) {
return HTMLPurifier_ConfigSchema_Interchange_Id::make($id);
}
-
+
/**
* Triggers errors for any unused keys passed in the hash; such keys
* may indicate typos, missing values, etc.
}
}
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_Validator
{
-
+
/**
* Easy to access global objects.
*/
protected $interchange, $aliases;
-
+
/**
* Context-stack to provide easy to read error messages.
*/
protected $context = array();
-
+
/**
* HTMLPurifier_VarParser to test default's type.
*/
protected $parser;
-
+
public function __construct() {
$this->parser = new HTMLPurifier_VarParser();
}
-
+
/**
* Validates a fully-formed interchange object. Throws an
* HTMLPurifier_ConfigSchema_Exception if there's a problem.
}
return true;
}
-
+
/**
* Validates a HTMLPurifier_ConfigSchema_Interchange_Namespace object.
*/
->assertIsString(); // handled by InterchangeBuilder
array_pop($this->context);
}
-
+
/**
* Validates a HTMLPurifier_ConfigSchema_Interchange_Id object.
*/
->assertAlnum(); // implicit assertIsString handled by InterchangeBuilder
array_pop($this->context);
}
-
+
/**
* Validates a HTMLPurifier_ConfigSchema_Interchange_Directive object.
*/
$id = $d->id->toString();
$this->context[] = "directive '$id'";
$this->validateId($d->id);
-
+
$this->with($d, 'description')
->assertNotEmpty();
-
+
// BEGIN - handled by InterchangeBuilder
$this->with($d, 'type')
->assertNotEmpty();
$this->error('default', 'had error: ' . $e->getMessage());
}
// END - handled by InterchangeBuilder
-
+
if (!is_null($d->allowed) || !empty($d->valueAliases)) {
// allowed and valueAliases require that we be dealing with
// strings, so check for that early.
$this->error('type', 'must be a string type when used with allowed or value aliases');
}
}
-
+
$this->validateDirectiveAllowed($d);
$this->validateDirectiveValueAliases($d);
$this->validateDirectiveAliases($d);
-
+
array_pop($this->context);
}
-
+
/**
* Extra validation if $allowed member variable of
* HTMLPurifier_ConfigSchema_Interchange_Directive is defined.
}
array_pop($this->context);
}
-
+
/**
* Extra validation if $valueAliases member variable of
* HTMLPurifier_ConfigSchema_Interchange_Directive is defined.
}
array_pop($this->context);
}
-
+
/**
* Extra validation if $aliases member variable of
* HTMLPurifier_ConfigSchema_Interchange_Directive is defined.
}
array_pop($this->context);
}
-
+
// protected helper functions
-
+
/**
* Convenience function for generating HTMLPurifier_ConfigSchema_ValidatorAtom
* for validating simple member variables of objects.
protected function with($obj, $member) {
return new HTMLPurifier_ConfigSchema_ValidatorAtom($this->getFormattedContext(), $obj, $member);
}
-
+
/**
* Emits an error, providing helpful context.
*/
else $prefix = ucfirst($this->getFormattedContext());
throw new HTMLPurifier_ConfigSchema_Exception(trim($prefix . ' ' . $msg));
}
-
+
/**
* Returns a formatted context string.
*/
protected function getFormattedContext() {
return implode(' in ', array_reverse($this->context));
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ConfigSchema_ValidatorAtom
{
-
+
protected $context, $obj, $member, $contents;
-
+
public function __construct($context, $obj, $member) {
$this->context = $context;
$this->obj = $obj;
$this->member = $member;
$this->contents =& $obj->$member;
}
-
+
public function assertIsString() {
if (!is_string($this->contents)) $this->error('must be a string');
return $this;
}
-
+
public function assertIsBool() {
if (!is_bool($this->contents)) $this->error('must be a boolean');
return $this;
}
-
+
public function assertIsArray() {
if (!is_array($this->contents)) $this->error('must be an array');
return $this;
}
-
+
public function assertNotNull() {
if ($this->contents === null) $this->error('must not be null');
return $this;
}
-
+
public function assertAlnum() {
$this->assertIsString();
if (!ctype_alnum($this->contents)) $this->error('must be alphanumeric');
return $this;
}
-
+
public function assertNotEmpty() {
if (empty($this->contents)) $this->error('must not be empty');
return $this;
}
-
+
public function assertIsLookup() {
$this->assertIsArray();
foreach ($this->contents as $v) {
}
return $this;
}
-
+
protected function error($msg) {
throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg);
}
-
-}
+}
+// vim: et sw=4 sts=4
so this directive will have no effect in that doctype. XHTML 1.1 does not
enable the Target module by default, you will have to manually enable it
(see the module documentation for more details.)
+--# vim: et sw=4 sts=4
--DESCRIPTION--
List of allowed forward document relationships in the rel attribute. Common
values may be nofollow or print. By default, this is empty, meaning that no
-document relationships are allowed.
+document relationships are allowed.
+--# vim: et sw=4 sts=4
--DESCRIPTION--
List of allowed reverse document relationships in the rev attribute. This
attribute is a bit of an edge-case; if you don't know what it is for, stay
-away.
+away.
+--# vim: et sw=4 sts=4
Attr.DefaultImageAlt
TYPE: string/null
DEFAULT: null
+VERSION: 3.2.0
--DESCRIPTION--
This is the content of the alt tag of an image if the user had not
previously specified an alt attribute. This applies to all images without
a valid alt attribute, as opposed to %Attr.DefaultInvalidImageAlt, which
only applies to invalid images, and overrides in the case of an invalid image.
Default behavior with null is to use the basename of the src tag for the alt.
+--# vim: et sw=4 sts=4
a valid src attribute. In future versions, we may allow the image tag to
be removed completely, but due to design issues, this is not possible right
now.
+--# vim: et sw=4 sts=4
This is the content of the alt tag of an invalid image if the user had not
previously specified an alt attribute. It has no effect when the image is
valid but there was no alt attribute present.
+--# vim: et sw=4 sts=4
HTML, or ltr if that is not specified.
--ALLOWED--
'ltr', 'rtl'
+--# vim: et sw=4 sts=4
pre-1.2.0 versions.
--ALIASES--
HTML.EnableAttrID
+--# vim: et sw=4 sts=4
TYPE: list
DEFAULT: array()
DESCRIPTION: Array of IDs not allowed in the document.
+--# vim: et sw=4 sts=4
--DESCRIPTION--
PCRE regular expression to be matched against all IDs. If the expression is
matches, the ID is rejected. Use this with care: may cause significant
-degradation. ID matching is done after all other validation.
+degradation. ID matching is done after all other validation.
+--# vim: et sw=4 sts=4
that they are still usable, but will not conflict with core page IDs.
Example: setting the directive to 'user_' will result in a user submitted
'foo' to become 'user_foo' Be sure to set %HTML.EnableAttrID to true
-before using this.
+before using this.
+--# vim: et sw=4 sts=4
clobber each other. Ideal values are unique identifiers for the content it
represents (i.e. the id of the row in the database). Be sure to add a
seperator (like an underscore) at the end. Warning: this directive will
-not work unless %Attr.IDPrefix is set to a non-empty value!
+not work unless %Attr.IDPrefix is set to a non-empty value!
+--# vim: et sw=4 sts=4
Attr
DESCRIPTION: Features regarding attribute validation.
+--# vim: et sw=4 sts=4
in <code>div</code> tags (the behavior is slightly different outside of
the root node.)
</p>
+--# vim: et sw=4 sts=4
<p>
This directive can be used to add custom auto-format injectors.
Specify an array of injector names (class name minus the prefix)
- or concrete implementations. Injector class must exist.
+ or concrete implementations. Injector class must exist.
</p>
-
+--# vim: et sw=4 sts=4
those links. For example, <a href="http://example.com">example</a> becomes
example (<a>http://example.com</a>).
</p>
+--# vim: et sw=4 sts=4
<p>
This directive turns on linkification, auto-linking http, ftp and
https URLs. <code>a</code> tags with the <code>href</code> attribute
- must be allowed.
+ must be allowed.
</p>
-
+--# vim: et sw=4 sts=4
syntax <a>%Namespace.Directive</a> to links. <code>a</code> tags
with the <code>href</code> attribute must be allowed.
</p>
-
+--# vim: et sw=4 sts=4
if a tag looked empty on the way end, it will get removed; if HTML Purifier
made it empty, it will stay.
</p>
+--# vim: et sw=4 sts=4
AutoFormat
DESCRIPTION: Configuration for activating auto-formatting functionality (also known as <code>Injector</code>s)
+--# vim: et sw=4 sts=4
<p>
Location of configuration documentation to link to, let %s substitute
into the configuration's namespace and directive names sans the percent
- sign.
+ sign.
</p>
-
+--# vim: et sw=4 sts=4
AutoFormatParam
DESCRIPTION: Configuration for customizing auto-formatting functionality
+--# vim: et sw=4 sts=4
--DESCRIPTION--
This parameter determines whether or not !important cascade modifiers should
be allowed in user CSS. If false, !important will stripped.
+--# vim: et sw=4 sts=4
be used for deceptive practices but do not directly constitute a security risk.
For example, <code>display:none;</code> is considered a tricky property that
will only be allowed if this directive is set to true.
+--# vim: et sw=4 sts=4
--DESCRIPTION--
<p>
- If HTML Purifier's style attributes set is unsatisfactory for your needs,
- you can overload it with your own list of tags to allow. Note that this
- method is subtractive: it does its job by taking away from HTML Purifier
- usual feature set, so you cannot add an attribute that HTML Purifier never
+ If HTML Purifier's style attributes set is unsatisfactory for your needs,
+ you can overload it with your own list of tags to allow. Note that this
+ method is subtractive: it does its job by taking away from HTML Purifier
+ usual feature set, so you cannot add an attribute that HTML Purifier never
supported in the first place.
</p>
<p>
- <strong>Warning:</strong> If another directive conflicts with the
- elements here, <em>that</em> directive will win and override.
+ <strong>Warning:</strong> If another directive conflicts with the
+ elements here, <em>that</em> directive will win and override.
</p>
+--# vim: et sw=4 sts=4
<p>
Revision identifier for your custom definition. See
- %HTML.DefinitionRev for details.
+ %HTML.DefinitionRev for details.
</p>
-
+--# vim: et sw=4 sts=4
subtle differences in the input format (the CSS max is a number with
a unit).
</p>
+--# vim: et sw=4 sts=4
--DESCRIPTION--
<p>
- Whether or not to allow safe, proprietary CSS values.
+ Whether or not to allow safe, proprietary CSS values.
</p>
-
+--# vim: et sw=4 sts=4
CSS
DESCRIPTION: Configuration regarding allowed CSS.
+--# vim: et sw=4 sts=4
This directive defines which method to use when caching definitions,
the complex data-type that makes HTML Purifier tick. Set to null
to disable caching (not recommended, as you will see a definite
-performance degradation).
+performance degradation).
--ALIASES--
Core.DefinitionCache
+--# vim: et sw=4 sts=4
Absolute path with no trailing slash to store serialized definitions in.
Default is within the
HTML Purifier library inside DefinitionCache/Serializer. This
- path must be writable by the webserver.
+ path must be writable by the webserver.
</p>
-
+--# vim: et sw=4 sts=4
Cache
DESCRIPTION: Configuration for DefinitionCache and related subclasses.
+--# vim: et sw=4 sts=4
<p>
<strong>Notice:</strong> This directive's default turned from false to true
in HTML Purifier 3.2.0.
-</p>
\ No newline at end of file
+</p>
+--# vim: et sw=4 sts=4
is a useful way to give feedback to your users. <strong>Warning:</strong>
Currently this feature is very patchy and experimental, with lots of
possible error messages not yet implemented. It will not cause any
-problems, but it may not help your users either.
+problems, but it may not help your users either.
+--# vim: et sw=4 sts=4
Lookup array of color names to six digit hexadecimal number corresponding
to color, with preceding hash mark. Used when parsing colors.
-
-
+--# vim: et sw=4 sts=4
--ALIASES--
Core.AcceptFullDocuments
+--# vim: et sw=4 sts=4
performance, and this is only strictly necessary if the counting
algorithm is buggy (in which case you should report it as a bug).
This has no effect when %Core.MaintainLineNumbers is disabled or DirectLex is
- not being used.
+ not being used.
</p>
-
+--# vim: et sw=4 sts=4
applications, although %Core.EscapeNonASCIICharacters offers fixes this
trouble with another tradeoff. This directive only accepts ISO-8859-1 if
iconv is not enabled.
+--# vim: et sw=4 sts=4
false, that element and all internal tags will be dropped, though text will
be preserved. There is no option for dropping the element but preserving
child nodes.
+--# vim: et sw=4 sts=4
--DESCRIPTION--
When true, invalid tags will be written back to the document as plain text.
Otherwise, they are silently dropped.
+--# vim: et sw=4 sts=4
can be expressed in the non-UTF-8 encoding will be entity-ized, which can
be a real downer for encodings like Big5. It also assumes that the ASCII
repetoire is available, although this is the case for almost all encodings.
-Anyway, use UTF-8!
+Anyway, use UTF-8!
+--# vim: et sw=4 sts=4
<p>
This directive is a lookup array of elements which should have their
contents removed when they are not allowed by the HTML definition.
- For example, the contents of a <code>script</code> tag are not
+ For example, the contents of a <code>script</code> tag are not
normally shown in a document, so if script tags are to be removed,
their contents should be removed to. This is opposed to a <code>b</code>
tag, which defines some presentational changes but does not hide its
contents.
</p>
-
+--# vim: et sw=4 sts=4
ISO 639 language code for localizable things in HTML Purifier to use,
which is mainly error reporting. There is currently only an English (en)
translation, so this directive is currently useless.
-
-
+--# vim: et sw=4 sts=4
to use it.
</dd>
</dl>
+--# vim: et sw=4 sts=4
This is useful when error reporting is turned on, but can result in
significant performance degradation and should not be used when
unnecessary. This directive must be used with the DirectLex lexer,
- as the DOMLex lexer does not (yet) support this functionality.
+ as the DOMLex lexer does not (yet) support this functionality.
If the value is null, an appropriate value will be selected based
- on other configuration.
+ on other configuration.
</p>
-
+--# vim: et sw=4 sts=4
--DESCRIPTION--
<p>
- This directive enables pre-emptive URI checking in <code>img</code>
- tags, as the attribute validation strategy is not authorized to
+ This directive enables pre-emptive URI checking in <code>img</code>
+ tags, as the attribute validation strategy is not authorized to
remove elements from the document. Revert to pre-1.3.0 behavior by setting to false.
</p>
-
+--# vim: et sw=4 sts=4
This directive enables HTML Purifier to remove not only script tags
but all of their contents.
</p>
+--# vim: et sw=4 sts=4
Core
DESCRIPTION: Core features that are always available.
+--# vim: et sw=4 sts=4
equivalent of the now deprecated <code>HTMLPurifier->addFilter()</code>
method. Specify an array of concrete implementations.
</p>
+--# vim: et sw=4 sts=4
<?php
require_once '/path/to/library/HTMLPurifier.auto.php';
require_once '/path/to/csstidy.class.php';
-
+
$dirty = '<style>body {color:#F00;}</style> Some text';
$config = HTMLPurifier_Config::createDefault();
$config->set('Filter', 'ExtractStyleBlocks', true);
$purifier = new HTMLPurifier($config);
-
+
$html = $purifier->purify($dirty);
-
+
// This implementation writes the stylesheets to the styles/ directory.
// You can also echo the styles inside the document, but it's a bit
// more difficult to make sure they get interpreted properly by
height (somewhat reasonable). Whether or not these measures should be
used is left to the reader.
</p>
+--# vim: et sw=4 sts=4
<a href="http://htmlpurifier.org/docs/enduser-youtube.html">this document
on embedding videos</a> for more information on what this filter does.
</p>
+--# vim: et sw=4 sts=4
Filter
DESCRIPTION: Directives for turning filters on and off, or specifying custom filters.
+--# vim: et sw=4 sts=4
Whether or not to escape the dangerous characters <, > and &
as \3C, \3E and \26, respectively. This is can be safely set to false
if the contents of StyleBlocks will be placed in an external stylesheet,
- where there is no risk of it being interpreted as HTML.
+ where there is no risk of it being interpreted as HTML.
</p>
-
+--# vim: et sw=4 sts=4
Purifier, and I am working to get it fixed. Until then, HTML Purifier
performs a basic check to prevent this.
</p>
+--# vim: et sw=4 sts=4
disable cleaning. In addition, you can supply your own concrete implementation
of Tidy's interface to use, although I don't know why you'd want to do that.
</p>
+--# vim: et sw=4 sts=4
FilterParam
DESCRIPTION: Configuration for filters.
+--# vim: et sw=4 sts=4
broken whitelists. If %HTML.AllowedElements or %HTML.AllowedAttributes
are set, this directive has no effect.
</p>
-
+--# vim: et sw=4 sts=4
--DESCRIPTION--
<p>
- If HTML Purifier's attribute set is unsatisfactory, overload it!
- The syntax is "tag.attr" or "*.attr" for the global attributes
+ If HTML Purifier's attribute set is unsatisfactory, overload it!
+ The syntax is "tag.attr" or "*.attr" for the global attributes
(style, id, class, dir, lang, xml:lang).
</p>
<p>
- <strong>Warning:</strong> If another directive conflicts with the
- elements here, <em>that</em> directive will win and override. For
- example, %HTML.EnableAttrID will take precedence over *.id in this
- directive. You must set that directive to true before you can use
- IDs at all.
+ <strong>Warning:</strong> If another directive conflicts with the
+ elements here, <em>that</em> directive will win and override. For
+ example, %HTML.EnableAttrID will take precedence over *.id in this
+ directive. You must set that directive to true before you can use
+ IDs at all.
</p>
-
+--# vim: et sw=4 sts=4
DEFAULT: NULL
--DESCRIPTION--
<p>
- If HTML Purifier's tag set is unsatisfactory for your needs, you
- can overload it with your own list of tags to allow. Note that this
- method is subtractive: it does its job by taking away from HTML Purifier
- usual feature set, so you cannot add a tag that HTML Purifier never
- supported in the first place (like embed, form or head). If you
+ If HTML Purifier's tag set is unsatisfactory for your needs, you
+ can overload it with your own list of tags to allow. Note that this
+ method is subtractive: it does its job by taking away from HTML Purifier
+ usual feature set, so you cannot add a tag that HTML Purifier never
+ supported in the first place (like embed, form or head). If you
change this, you probably also want to change %HTML.AllowedAttributes.
</p>
<p>
- <strong>Warning:</strong> If another directive conflicts with the
- elements here, <em>that</em> directive will win and override.
+ <strong>Warning:</strong> If another directive conflicts with the
+ elements here, <em>that</em> directive will win and override.
</p>
-
+--# vim: et sw=4 sts=4
If you specify a module that does not exist, the manager will silently
fail to use it, so be careful! User-defined modules are not affected
by this directive. Modules defined in %HTML.CoreModules are not
- affected by this directive.
+ affected by this directive.
</p>
-
+--# vim: et sw=4 sts=4
<code><blockquote>Foo</blockquote></code> would become
<code><blockquote><p>Foo</p></blockquote></code>.
The <code><p></code> tags can be replaced with whatever you desire,
- as long as it is a block level element.
+ as long as it is a block level element.
</p>
-
+--# vim: et sw=4 sts=4
that must be included for the doctype to be an conforming document
type: put those modules here. By default, XHTML's core modules
are used. You can set this to a blank array to disable core module
- protection, but this is not recommended.
+ protection, but this is not recommended.
</p>
-
+--# vim: et sw=4 sts=4
A custom doctype for power-users who defined there own document
type. This directive only applies when %HTML.Doctype is blank.
-
-
+--# vim: et sw=4 sts=4
You <em>must</em> specify a value to this directive to use the
advanced API features.
</p>
-
+--# vim: et sw=4 sts=4
context: revision 3 is more up-to-date then revision 2. Thus, when
this gets incremented, the cache handling is smart enough to clean
up any older revisions of your definition as well as flush the
- cache.
+ cache.
</p>
-
+--# vim: et sw=4 sts=4
older directives like %HTML.XHTML or %HTML.Strict.
--ALLOWED--
'HTML 4.01 Transitional', 'HTML 4.01 Strict', 'XHTML 1.0 Transitional', 'XHTML 1.0 Strict', 'XHTML 1.1'
+--# vim: et sw=4 sts=4
out that directive for a discussion of why you
should think twice before using this directive.
</p>
+--# vim: et sw=4 sts=4
a nasty surprise when people start using the <code>background-image</code>
CSS property.
</p>
+--# vim: et sw=4 sts=4
This directive is similar to %CSS.MaxImgLength, and both should be
concurrently edited, although there are
subtle differences in the input format (the HTML max is an integer).
-</p>
\ No newline at end of file
+</p>
+--# vim: et sw=4 sts=4
--DESCRIPTION--
<p>
- String name of element that HTML fragment passed to library will be
- inserted in. An interesting variation would be using span as the
- parent element, meaning that only inline tags would be allowed.
+ String name of element that HTML fragment passed to library will be
+ inserted in. An interesting variation would be using span as the
+ parent element, meaning that only inline tags would be allowed.
</p>
-
+--# vim: et sw=4 sts=4
<strong>Warning:</strong> This can cause your documents to stop
validating!
</p>
+--# vim: et sw=4 sts=4
element and will cause your website to stop validating. You probably want
to enable this with %HTML.SafeObject.
<strong>Highly experimental.</strong>
-</p>
\ No newline at end of file
+</p>
+--# vim: et sw=4 sts=4
<p>
Whether or not to permit object tags in documents, with a number of extra
security features added to prevent script execution. This is similar to
- what websites like MySpace do to object tags. You may also want to
+ what websites like MySpace do to object tags. You may also want to
enable %HTML.SafeEmbed for maximum interoperability with Internet Explorer,
although embed tags will cause your website to stop validating.
<strong>Highly experimental.</strong>
</p>
+--# vim: et sw=4 sts=4
DEPRECATED-USE: HTML.Doctype
--DESCRIPTION--
Determines whether or not to use Transitional (loose) or Strict rulesets.
+--# vim: et sw=4 sts=4
DEFAULT: array()
--DESCRIPTION--
-Fixes to add to the default set of Tidy fixes as per your level.
-
+Fixes to add to the default set of Tidy fixes as per your level.
+--# vim: et sw=4 sts=4
--ALLOWED--
'none', 'light', 'medium', 'heavy'
+--# vim: et sw=4 sts=4
DEFAULT: array()
--DESCRIPTION--
-Fixes to remove from the default set of Tidy fixes as per your level.
-
+Fixes to remove from the default set of Tidy fixes as per your level.
+--# vim: et sw=4 sts=4
DEFAULT: false
--DESCRIPTION--
Indicates whether or not the user input is trusted or not. If the input is
-trusted, a more expansive set of allowed tags and attributes will be used.
+trusted, a more expansive set of allowed tags and attributes will be used.
+--# vim: et sw=4 sts=4
Determines whether or not output is XHTML 1.0 or HTML 4.01 flavor.
--ALIASES--
Core.XHTML
+--# vim: et sw=4 sts=4
HTML
DESCRIPTION: Configuration regarding allowed HTML.
+--# vim: et sw=4 sts=4
DEFAULT: true
--DESCRIPTION--
Determines whether or not HTML Purifier should attempt to fix up the
-contents of script tags for legacy browsers with comments.
+contents of script tags for legacy browsers with comments.
--ALIASES--
Core.CommentScriptContents
+--# vim: et sw=4 sts=4
Newline string to format final output with. If left null, HTML Purifier
will auto-detect the default newline type of the system and use that;
you can manually override it here. Remember, \r\n is Windows, \r
- is Mac, and \n is Unix.
+ is Mac, and \n is Unix.
</p>
-
+--# vim: et sw=4 sts=4
to text diffs. If you're not seeing this bug, chances are, you don't need
this directive.
</p>
+--# vim: et sw=4 sts=4
DEFAULT: false
--DESCRIPTION--
<p>
- Determines whether or not to run Tidy on the final output for pretty
+ Determines whether or not to run Tidy on the final output for pretty
formatting reasons, such as indentation and wrap.
</p>
<p>
</p>
--ALIASES--
Core.TidyFormat
+--# vim: et sw=4 sts=4
Output
DESCRIPTION: Configuration relating to the generation of (X)HTML.
+--# vim: et sw=4 sts=4
--DESCRIPTION--
When set to true, HTMLPurifier_Encoder will act as if iconv does not exist
and use only pure PHP implementations.
+--# vim: et sw=4 sts=4
Test
DESCRIPTION: Developer testing configuration for our unit tests.
+--# vim: et sw=4 sts=4
--DESCRIPTION--
Whitelist that defines the schemes that a URI is allowed to have. This
prevents XSS attacks from using pseudo-schemes like javascript or mocha.
+--# vim: et sw=4 sts=4
inserted into. This information is important if HTML Purifier needs
to calculate absolute URIs from relative URIs, such as when %URI.MakeAbsolute
is on. You may use a non-absolute URI for this value, but behavior
- may vary (%URI.MakeAbsolute deals nicely with both absolute and
+ may vary (%URI.MakeAbsolute deals nicely with both absolute and
relative paths, but forwards-compatibility is not guaranteed).
<strong>Warning:</strong> If set, the scheme on this URI
- overrides the one specified by %URI.DefaultScheme.
+ overrides the one specified by %URI.DefaultScheme.
</p>
-
+--# vim: et sw=4 sts=4
--DESCRIPTION--
<p>
- Defines through what scheme the output will be served, in order to
+ Defines through what scheme the output will be served, in order to
select the proper object validator when no scheme information is present.
</p>
-
+--# vim: et sw=4 sts=4
Unique identifier for a custom-built URI definition. If you want
to add custom URIFilters, you must specify this value.
</p>
-
+--# vim: et sw=4 sts=4
<p>
Revision identifier for your custom definition. See
- %HTML.DefinitionRev for details.
+ %HTML.DefinitionRev for details.
</p>
-
+--# vim: et sw=4 sts=4
--DESCRIPTION--
<p>
- Disables all URIs in all forms. Not sure why you'd want to do that
- (after all, the Internet's founded on the notion of a hyperlink).
+ Disables all URIs in all forms. Not sure why you'd want to do that
+ (after all, the Internet's founded on the notion of a hyperlink).
</p>
--ALIASES--
Attr.DisableURI
+--# vim: et sw=4 sts=4
and anti-pagerank-leech measure, but comes at a hefty price: nolinks or
images outside of your domain will be allowed. Non-linkified URIs will
still be preserved. If you want to be able to link to subdomains or use
-absolute URIs, specify %URI.Host for your website.
+absolute URIs, specify %URI.Host for your website.
+--# vim: et sw=4 sts=4
forging, goatse.cx posting, and other nasties, but also results in a loss
of end-user functionality (they can't directly post a pic they posted from
Flickr anymore). Use it if you don't have a robust user-content moderation
-team.
+team.
+--# vim: et sw=4 sts=4
<p>
Disables embedding resources, essentially meaning no pictures. You can
- still link to them though. See %URI.DisableExternalResources for why
- this might be a good idea.
+ still link to them though. See %URI.DisableExternalResources for why
+ this might be a good idea.
</p>
-
+--# vim: et sw=4 sts=4
--DESCRIPTION--
<p>
- Defines the domain name of the server, so we can determine whether or
- an absolute URI is from your website or not. Not strictly necessary,
- as users should be using relative URIs to reference resources on your
- website. It will, however, let you use absolute URIs to link to
- subdomains of the domain you post here: i.e. example.com will allow
- sub.example.com. However, higher up domains will still be excluded:
- if you set %URI.Host to sub.example.com, example.com will be blocked.
+ Defines the domain name of the server, so we can determine whether or
+ an absolute URI is from your website or not. Not strictly necessary,
+ as users should be using relative URIs to reference resources on your
+ website. It will, however, let you use absolute URIs to link to
+ subdomains of the domain you post here: i.e. example.com will allow
+ sub.example.com. However, higher up domains will still be excluded:
+ if you set %URI.Host to sub.example.com, example.com will be blocked.
<strong>Note:</strong> This directive overrides %URI.Base because
a given page may be on a sub-domain, but you wish HTML Purifier to be
more relaxed and allow some of the parent domains too.
</p>
-
+--# vim: et sw=4 sts=4
--DESCRIPTION--
List of strings that are forbidden in the host of any URI. Use it to kill
domain names of spam, etc. Note that it will catch anything in the domain,
-so <tt>moo.com</tt> will catch <tt>moo.com.example.com</tt>.
+so <tt>moo.com</tt> will catch <tt>moo.com.example.com</tt>.
+--# vim: et sw=4 sts=4
viewed in a different context (and setting an alternate base URI is
not possible). %URI.Base must be set for this directive to work.
</p>
+--# vim: et sw=4 sts=4
<p>
Munges all browsable (usually http, https and ftp)
absolute URIs into another URI, usually a URI redirection service.
- This directive accepts a URI, formatted with a <code>%s</code> where
- the url-encoded original URI should be inserted (sample:
+ This directive accepts a URI, formatted with a <code>%s</code> where
+ the url-encoded original URI should be inserted (sample:
<code>http://www.google.com/url?q=%s</code>).
</p>
<p>
</p>
<ul>
<li>
- Prevent PageRank leaks, while being fairly transparent
- to users (you may also want to add some client side JavaScript to
+ Prevent PageRank leaks, while being fairly transparent
+ to users (you may also want to add some client side JavaScript to
override the text in the statusbar). <strong>Notice</strong>:
- Many security experts believe that this form of protection does not deter spam-bots.
+ Many security experts believe that this form of protection does not deter spam-bots.
</li>
<li>
Redirect users to a splash page telling them they are leaving your
was picked because it came after n (and I couldn't use a), p is for
property.
</p>
+--# vim: et sw=4 sts=4
<strong>Warning:</strong> It is strongly advised you use this in conjunction
%URI.MungeSecretKey to mitigate the security risk of an open redirector.
</p>
+--# vim: et sw=4 sts=4
<p>
Remember this has no effect if %URI.Munge is not on.
</p>
+--# vim: et sw=4 sts=4
%URI.AllowedSchemes by simply registering a HTMLPurifier_URIScheme to the
registry. If false, you will also have to update that directive in order
to add more schemes.
+--# vim: et sw=4 sts=4
URI
DESCRIPTION: Features regarding Uniform Resource Identifiers.
+--# vim: et sw=4 sts=4
name = "HTML Purifier"
+
+; vim: et sw=4 sts=4
*/
class HTMLPurifier_ContentSets
{
-
+
/**
* List of content set strings (pipe seperators) indexed by name.
*/
public $info = array();
-
+
/**
* List of content set lookups (element => true) indexed by name.
* @note This is in HTMLPurifier_HTMLDefinition->info_content_sets
*/
public $lookup = array();
-
+
/**
* Synchronized list of defined content sets (keys of info)
*/
* Synchronized list of defined content values (values of info)
*/
protected $values = array();
-
+
/**
* Merges in module's content sets, expands identifiers in the content
* sets and populates the keys, values and lookup member variables.
$this->lookup[$i] += $add;
}
}
-
+
foreach ($this->lookup as $key => $lookup) {
$this->info[$key] = implode(' | ', array_keys($lookup));
}
$this->keys = array_keys($this->info);
$this->values = array_values($this->info);
}
-
+
/**
* Accepts a definition; generates and assigns a ChildDef for it
* @param $def HTMLPurifier_ElementDef reference
}
$def->child = $this->getChildDef($def, $module);
}
-
+
public function generateChildDefCallback($matches) {
return $this->info[$matches[0]];
}
-
+
/**
* Instantiates a ChildDef based on content_model and content_model_type
* member variables in HTMLPurifier_ElementDef
);
return false;
}
-
+
/**
* Converts a string list of elements separated by pipes into
* a lookup array.
}
return $ret;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Context
{
-
+
/**
* Private array that stores the references.
*/
private $_storage = array();
-
+
/**
* Registers a variable into the context.
* @param $name String name
}
$this->_storage[$name] =& $ref;
}
-
+
/**
* Retrieves a variable reference from the context.
* @param $name String name
}
return $this->_storage[$name];
}
-
+
/**
* Destorys a variable in the context.
* @param $name String name
}
unset($this->_storage[$name]);
}
-
+
/**
* Checks whether or not the variable exists.
* @param $name String name
public function exists($name) {
return isset($this->_storage[$name]);
}
-
+
/**
* Loads a series of variables from an associative array
* @param $context_array Assoc array of variables to load
$this->register($key, $context_array[$key]);
}
}
-
+
}
+// vim: et sw=4 sts=4
*/
abstract class HTMLPurifier_Definition
{
-
+
/**
* Has setup() been called yet?
*/
public $setup = false;
-
+
/**
* What type of definition is it?
*/
public $type;
-
+
/**
* Sets up the definition object into the final form, something
* not done by the constructor
* @param $config HTMLPurifier_Config instance
*/
abstract protected function doSetup($config);
-
+
/**
* Setup function that aborts if already setup
* @param $config HTMLPurifier_Config instance
$this->setup = true;
$this->doSetup($config);
}
-
+
}
+// vim: et sw=4 sts=4
*/
abstract class HTMLPurifier_DefinitionCache
{
-
+
public $type;
-
+
/**
* @param $name Type of definition objects this instance of the
* cache will handle.
public function __construct($type) {
$this->type = $type;
}
-
+
/**
* Generates a unique identifier for a particular configuration
* @param Instance of HTMLPurifier_Config
$config->getBatchSerial($this->type) . ',' .
$config->get($this->type, 'DefinitionRev');
}
-
+
/**
* Tests whether or not a key is old with respect to the configuration's
* version and revision number.
) return true;
return false;
}
-
+
/**
* Checks if a definition's type jives with the cache's type
* @note Throws an error on failure
}
return true;
}
-
+
/**
* Adds a definition object to the cache
*/
abstract public function add($def, $config);
-
+
/**
* Unconditionally saves a definition object to the cache
*/
abstract public function set($def, $config);
-
+
/**
* Replace an object in the cache
*/
abstract public function replace($def, $config);
-
+
/**
* Retrieves a definition object from the cache
*/
abstract public function get($config);
-
+
/**
* Removes a definition object to the cache
*/
abstract public function remove($config);
-
+
/**
* Clears all objects from cache
*/
abstract public function flush($config);
-
+
/**
* Clears all expired (older version or revision) objects from cache
* @note Be carefuly implementing this method as flush. Flush must
* should not be repeatedly called by userland code.
*/
abstract public function cleanup($config);
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_DefinitionCache_Decorator extends HTMLPurifier_DefinitionCache
{
-
+
/**
* Cache object we are decorating
*/
public $cache;
-
+
public function __construct() {}
-
+
/**
* Lazy decorator function
* @param $cache Reference to cache object to decorate
$decorator->type = $cache->type;
return $decorator;
}
-
+
/**
* Cross-compatible clone substitute
*/
public function copy() {
return new HTMLPurifier_DefinitionCache_Decorator();
}
-
+
public function add($def, $config) {
return $this->cache->add($def, $config);
}
-
+
public function set($def, $config) {
return $this->cache->set($def, $config);
}
-
+
public function replace($def, $config) {
return $this->cache->replace($def, $config);
}
-
+
public function get($config) {
return $this->cache->get($config);
}
-
+
public function remove($config) {
return $this->cache->remove($config);
}
-
+
public function flush($config) {
return $this->cache->flush($config);
}
-
+
public function cleanup($config) {
return $this->cache->cleanup($config);
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_DefinitionCache_Decorator_Cleanup extends
HTMLPurifier_DefinitionCache_Decorator
{
-
+
public $name = 'Cleanup';
-
+
public function copy() {
return new HTMLPurifier_DefinitionCache_Decorator_Cleanup();
}
-
+
public function add($def, $config) {
$status = parent::add($def, $config);
if (!$status) parent::cleanup($config);
return $status;
}
-
+
public function set($def, $config) {
$status = parent::set($def, $config);
if (!$status) parent::cleanup($config);
return $status;
}
-
+
public function replace($def, $config) {
$status = parent::replace($def, $config);
if (!$status) parent::cleanup($config);
return $status;
}
-
+
public function get($config) {
$ret = parent::get($config);
if (!$ret) parent::cleanup($config);
return $ret;
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Definition cache decorator class that saves all cache retrievals
- * to PHP's memory; good for unit tests or circumstances where
+ * to PHP's memory; good for unit tests or circumstances where
* there are lots of configuration objects floating around.
*/
class HTMLPurifier_DefinitionCache_Decorator_Memory extends
HTMLPurifier_DefinitionCache_Decorator
{
-
+
protected $definitions;
public $name = 'Memory';
-
+
public function copy() {
return new HTMLPurifier_DefinitionCache_Decorator_Memory();
}
-
+
public function add($def, $config) {
$status = parent::add($def, $config);
if ($status) $this->definitions[$this->generateKey($config)] = $def;
return $status;
}
-
+
public function set($def, $config) {
$status = parent::set($def, $config);
if ($status) $this->definitions[$this->generateKey($config)] = $def;
return $status;
}
-
+
public function replace($def, $config) {
$status = parent::replace($def, $config);
if ($status) $this->definitions[$this->generateKey($config)] = $def;
return $status;
}
-
+
public function get($config) {
$key = $this->generateKey($config);
if (isset($this->definitions[$key])) return $this->definitions[$key];
$this->definitions[$key] = parent::get($config);
return $this->definitions[$key];
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_DefinitionCache_Decorator_Template extends
HTMLPurifier_DefinitionCache_Decorator
{
-
+
var $name = 'Template'; // replace this
-
+
function copy() {
// replace class name with yours
return new HTMLPurifier_DefinitionCache_Decorator_Template();
}
-
+
// remove methods you don't need
-
+
function add($def, $config) {
return parent::add($def, $config);
}
-
+
function set($def, $config) {
return parent::set($def, $config);
}
-
+
function replace($def, $config) {
return parent::replace($def, $config);
}
-
+
function get($config) {
return parent::get($config);
}
-
+
function flush() {
return parent::flush();
}
-
+
function cleanup($config) {
return parent::cleanup($config);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_DefinitionCache_Null extends HTMLPurifier_DefinitionCache
{
-
+
public function add($def, $config) {
return false;
}
-
+
public function set($def, $config) {
return false;
}
-
+
public function replace($def, $config) {
return false;
}
-
+
public function remove($config) {
return false;
}
-
+
public function get($config) {
return false;
}
-
+
public function flush($config) {
return false;
}
-
+
public function cleanup($config) {
return false;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_DefinitionCache_Serializer extends
HTMLPurifier_DefinitionCache
{
-
+
public function add($def, $config) {
if (!$this->checkDefType($def)) return;
$file = $this->generateFilePath($config);
if (!$this->_prepareDir($config)) return false;
return $this->_write($file, serialize($def));
}
-
+
public function set($def, $config) {
if (!$this->checkDefType($def)) return;
$file = $this->generateFilePath($config);
if (!$this->_prepareDir($config)) return false;
return $this->_write($file, serialize($def));
}
-
+
public function replace($def, $config) {
if (!$this->checkDefType($def)) return;
$file = $this->generateFilePath($config);
if (!$this->_prepareDir($config)) return false;
return $this->_write($file, serialize($def));
}
-
+
public function get($config) {
$file = $this->generateFilePath($config);
if (!file_exists($file)) return false;
return unserialize(file_get_contents($file));
}
-
+
public function remove($config) {
$file = $this->generateFilePath($config);
if (!file_exists($file)) return false;
return unlink($file);
}
-
+
public function flush($config) {
if (!$this->_prepareDir($config)) return false;
$dir = $this->generateDirectoryPath($config);
unlink($dir . '/' . $filename);
}
}
-
+
public function cleanup($config) {
if (!$this->_prepareDir($config)) return false;
$dir = $this->generateDirectoryPath($config);
if ($this->isOld($key, $config)) unlink($dir . '/' . $filename);
}
}
-
+
/**
* Generates the file path to the serial file corresponding to
* the configuration and definition name
$key = $this->generateKey($config);
return $this->generateDirectoryPath($config) . '/' . $key . '.ser';
}
-
+
/**
* Generates the path to the directory contain this cache's serial files
* @note No trailing slash
$base = $this->generateBaseDirectoryPath($config);
return $base . '/' . $this->type;
}
-
+
/**
* Generates path to base directory that contains all definition type
* serials
$base = is_null($base) ? HTMLPURIFIER_PREFIX . '/HTMLPurifier/DefinitionCache/Serializer' : $base;
return $base;
}
-
+
/**
* Convenience wrapper function for file_put_contents
* @param $file File name to write to
private function _write($file, $data) {
return file_put_contents($file, $data);
}
-
+
/**
* Prepares the directory that this type stores the serials in
* @return True if successful
if (!is_dir($base)) {
trigger_error('Base directory '.$base.' does not exist,
please create or change using %Cache.SerializerPath',
- E_USER_ERROR);
+ E_USER_WARNING);
return false;
} elseif (!$this->_testPermissions($base)) {
return false;
}
return true;
}
-
+
/**
* Tests permissions on a directory and throws out friendly
* error messages and attempts to chmod it itself if possible
// generally, you'll want to handle this beforehand
// so a more specific error message can be given
trigger_error('Directory '.$dir.' does not exist',
- E_USER_ERROR);
+ E_USER_WARNING);
return false;
}
if (function_exists('posix_getuid')) {
}
trigger_error('Directory '.$dir.' not writable, '.
'please chmod to ' . $chmod,
- E_USER_ERROR);
+ E_USER_WARNING);
} else {
// generic error message
trigger_error('Directory '.$dir.' not writable, '.
'please alter file permissions',
- E_USER_ERROR);
+ E_USER_WARNING);
}
return false;
}
-
+
}
+// vim: et sw=4 sts=4
This is a dummy file to prevent Git from ignoring this empty directory.
+
+ vim: et sw=4 sts=4
*/
class HTMLPurifier_DefinitionCacheFactory
{
-
+
protected $caches = array('Serializer' => array());
protected $implementations = array();
protected $decorators = array();
-
+
/**
* Initialize default decorators
*/
public function setup() {
$this->addDecorator('Cleanup');
}
-
+
/**
* Retrieves an instance of global definition cache factory.
*/
}
return $instance;
}
-
+
/**
* Registers a new definition cache object
* @param $short Short name of cache object, for reference
- * @param $long Full class name of cache object, for construction
+ * @param $long Full class name of cache object, for construction
*/
public function register($short, $long) {
$this->implementations[$short] = $long;
}
-
+
/**
* Factory method that creates a cache object based on configuration
* @param $name Name of definitions handled by cache
$this->caches[$method][$type] = $cache;
return $this->caches[$method][$type];
}
-
+
/**
* Registers a decorator to add to all new cache objects
- * @param
+ * @param
*/
public function addDecorator($decorator) {
if (is_string($decorator)) {
}
$this->decorators[$decorator->name] = $decorator;
}
-
+
}
+// vim: et sw=4 sts=4
* Full name of doctype
*/
public $name;
-
+
/**
* List of standard modules (string identifiers or literal objects)
* that this doctype uses
*/
public $modules = array();
-
+
/**
* List of modules to use for tidying up code
*/
public $tidyModules = array();
-
+
/**
* Is the language derived from XML (i.e. XHTML)?
*/
public $xml = true;
-
+
/**
* List of aliases for this doctype
*/
public $aliases = array();
-
+
/**
* Public DTD identifier
*/
public $dtdPublic;
-
+
/**
* System DTD identifier
*/
public $dtdSystem;
-
+
public function __construct($name = null, $xml = true, $modules = array(),
$tidyModules = array(), $aliases = array(), $dtd_public = null, $dtd_system = null
) {
}
}
+// vim: et sw=4 sts=4
class HTMLPurifier_DoctypeRegistry
{
-
+
/**
* Hash of doctype names to doctype objects
*/
protected $doctypes;
-
+
/**
* Lookup table of aliases to real doctype names
*/
protected $aliases;
-
+
/**
* Registers a doctype to the registry
* @note Accepts a fully-formed doctype object, or the
if (isset($this->aliases[$name])) unset($this->aliases[$name]);
return $doctype;
}
-
+
/**
* Retrieves reference to a doctype of a certain name
* @note This function resolves aliases
}
return $this->doctypes[$doctype];
}
-
+
/**
* Creates a doctype based on a configuration object,
* will perform initialization on the doctype
public function make($config) {
return clone $this->get($this->getDoctypeFromConfig($config));
}
-
+
/**
* Retrieves the doctype from the configuration object
*/
}
return $doctype;
}
-
+
}
+// vim: et sw=4 sts=4
* HTMLPurifier_HTMLDefinition and HTMLPurifier_HTMLModule.
* @note This class is inspected by HTMLPurifier_Printer_HTMLDefinition.
* Please update that class too.
+ * @warning If you add new properties to this class, you MUST update
+ * the mergeIn() method.
*/
class HTMLPurifier_ElementDef
{
-
+
/**
* Does the definition work by itself, or is it created solely
* for the purpose of merging into another definition?
*/
public $standalone = true;
-
+
/**
* Associative array of attribute name to HTMLPurifier_AttrDef
* @note Before being processed by HTMLPurifier_AttrCollections
* HTMLPurifier_HTMLDefinition->setup() processing.
*/
public $attr = array();
-
+
/**
* Indexed list of tag's HTMLPurifier_AttrTransform to be done before validation
*/
public $attr_transform_pre = array();
-
+
/**
* Indexed list of tag's HTMLPurifier_AttrTransform to be done after validation
*/
public $attr_transform_post = array();
-
+
/**
* HTMLPurifier_ChildDef of this tag.
*/
public $child;
-
+
/**
* Abstract string representation of internal ChildDef rules. See
* HTMLPurifier_ContentSets for how this is parsed and then transformed
* being processed by HTMLDefinition
*/
public $content_model;
-
+
/**
* Value of $child->type, used to determine which ChildDef to use,
* used in combination with $content_model.
* being processed by HTMLDefinition
*/
public $content_model_type;
-
-
-
+
+
+
/**
* Does the element have a content model (#PCDATA | Inline)*? This
- * is important for chameleon ins and del processing in
+ * is important for chameleon ins and del processing in
* HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't
* have to worry about this one.
*/
public $descendants_are_inline = false;
-
+
/**
* List of the names of required attributes this element has. Dynamically
* populated by HTMLPurifier_HTMLDefinition::getElement
*/
public $required_attr = array();
-
+
/**
* Lookup table of tags excluded from all descendants of this tag.
* @note SGML permits exclusions for all descendants, but this is
* distinctions.
*/
public $excludes = array();
-
+
+ /**
+ * This tag is explicitly auto-closed by the following tags.
+ */
+ public $autoclose = array();
+
+ /**
+ * Whether or not this is a formatting element affected by the
+ * "Active Formatting Elements" algorithm.
+ */
+ public $formatting;
+
/**
* Low-level factory constructor for creating new standalone element defs
*/
$def->attr = $attr;
return $def;
}
-
+
/**
* Merges the values of another element definition into this one.
* Values from the new element def take precedence if a value is
* not mergeable.
*/
public function mergeIn($def) {
-
+
// later keys takes precedence
foreach($def->attr as $k => $v) {
if ($k === 0) {
$this->_mergeAssocArray($this->attr_transform_pre, $def->attr_transform_pre);
$this->_mergeAssocArray($this->attr_transform_post, $def->attr_transform_post);
$this->_mergeAssocArray($this->excludes, $def->excludes);
-
+
if(!empty($def->content_model)) {
$this->content_model .= ' | ' . $def->content_model;
$this->child = false;
$this->child = false;
}
if(!is_null($def->child)) $this->child = $def->child;
+ if(!is_null($def->formatting)) $this->formatting = $def->formatting;
if($def->descendants_are_inline) $this->descendants_are_inline = $def->descendants_are_inline;
-
+
}
-
+
/**
* Merges one array into another, removes values which equal false
* @param $a1 Array by reference that is merged into
$a1[$k] = $v;
}
}
-
-}
+}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Encoder
{
-
+
/**
* Constructor throws fatal error if you attempt to instantiate class
*/
private function __construct() {
trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR);
}
-
+
/**
* Error-handler that mutes errors, alternative to shut-up operator.
*/
private static function muteErrorHandler() {}
-
+
/**
* Cleans a UTF-8 string for well-formedness and SGML validity
- *
+ *
* It will parse according to UTF-8 and return a valid UTF8 string, with
* non-SGML codepoints excluded.
- *
+ *
* @note Just for reference, the non-SGML code points are 0 to 31 and
* 127 to 159, inclusive. However, we allow code points 9, 10
* and 13, which are the tab, line feed and carriage return
* respectively. 128 and above the code points map to multibyte
* UTF-8 representations.
- *
+ *
* @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and
* hsivonen@iki.fi at <http://iki.fi/hsivonen/php-utf8/> under the
* LGPL license. Notes on what changed are inside, but in general,
* Once again, PHP 6 should solve all our problems.
*/
public static function cleanUTF8($str, $force_php = false) {
-
+
// UTF-8 validity is checked since PHP 4.3.5
// This is an optimization: if the string is already valid UTF-8, no
// need to do PHP stuff. 99% of the time, this will be the case.
if (preg_match('/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du', $str)) {
return $str;
}
-
+
$mState = 0; // cached expected number of octets after the current octet
// until the beginning of the next UTF8 character sequence
$mUcs4 = 0; // cached Unicode character
$mBytes = 1; // cached expected number of octets in the current sequence
-
+
// original code involved an $out that was an array of Unicode
// codepoints. Instead of having to convert back into UTF-8, we've
// decided to directly append valid UTF-8 characters onto a string
// $out once they're done. $char accumulates raw bytes, while $mUcs4
// turns into the Unicode code point, so there's some redundancy.
-
+
$out = '';
$char = '';
-
+
$len = strlen($str);
for($i = 0; $i < $len; $i++) {
$in = ord($str{$i});
$char .= $str[$i]; // append byte to char
if (0 == $mState) {
- // When mState is zero we expect either a US-ASCII character
+ // When mState is zero we expect either a US-ASCII character
// or a multi-octet sequence.
if (0 == (0x80 & ($in))) {
// US-ASCII, pass straight through.
- if (($in <= 31 || $in == 127) &&
+ if (($in <= 31 || $in == 127) &&
!($in == 9 || $in == 13 || $in == 10) // save \r\t\n
) {
// control characters, remove
$mBytes = 4;
} elseif (0xF8 == (0xFC & ($in))) {
// First octet of 5 octet sequence.
- //
- // This is illegal because the encoded codepoint must be
+ //
+ // This is illegal because the encoded codepoint must be
// either:
// (a) not the shortest form or
// (b) outside the Unicode range of 0-0x10FFFF.
- // Rather than trying to resynchronize, we will carry on
+ // Rather than trying to resynchronize, we will carry on
// until the end of the sequence and let the later error
// handling code catch it.
$mUcs4 = ($in);
$mState = 5;
$mBytes = 6;
} else {
- // Current octet is neither in the US-ASCII range nor a
+ // Current octet is neither in the US-ASCII range nor a
// legal first octet of a multi-octet sequence.
$mState = 0;
$mUcs4 = 0;
$tmp = $in;
$tmp = ($tmp & 0x0000003F) << $shift;
$mUcs4 |= $tmp;
-
+
if (0 == --$mState) {
// End of the multi-octet sequence. mUcs4 now contains
// the final Unicode codepoint to be output
-
+
// Check for illegal sequences and codepoints.
-
+
// From Unicode 3.1, non-shortest form is illegal
if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
// Codepoints outside the Unicode range are illegal
($mUcs4 > 0x10FFFF)
) {
-
+
} elseif (0xFEFF != $mUcs4 && // omit BOM
// check for valid Char unicode codepoints
(
}
return $out;
}
-
+
/**
* Translates a Unicode codepoint into its corresponding UTF-8 character.
* @note Based on Feyd's function at
* maintenance/generate-entity-file.php (although this is superior,
* due to its sanity checks).
*/
-
+
// +----------+----------+----------+----------+
// | 33222222 | 22221111 | 111111 | |
// | 10987654 | 32109876 | 54321098 | 76543210 | bit
// +----------+----------+----------+----------+
// | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)
// | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes
- // +----------+----------+----------+----------+
-
+ // +----------+----------+----------+----------+
+
public static function unichr($code) {
if($code > 1114111 or $code < 0 or
($code >= 55296 and $code <= 57343) ) {
// bits are set outside the "valid" range as defined
- // by UNICODE 4.1.0
+ // by UNICODE 4.1.0
return '';
}
-
- $x = $y = $z = $w = 0;
+
+ $x = $y = $z = $w = 0;
if ($code < 128) {
// regular ASCII character
$x = $code;
$z = (($code >> 12) & 63) | 128;
$w = (($code >> 18) & 7) | 240;
}
- }
+ }
}
// set up the actual character
$ret = '';
if($w) $ret .= chr($w);
if($z) $ret .= chr($z);
if($y) $ret .= chr($y);
- $ret .= chr($x);
-
+ $ret .= chr($x);
+
return $ret;
}
-
+
/**
* Converts a string to UTF-8 based on configuration.
*/
}
trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
}
-
+
/**
* Converts a string from UTF-8 based on configuration.
* @note Currently, this is a lossy conversion, with unexpressable
}
trigger_error('Encoding not supported', E_USER_ERROR);
}
-
+
/**
* Lossless (character-wise) conversion of HTML to ASCII
* @param $str UTF-8 string to be converted to ASCII
}
return $result;
}
-
+
/**
* This expensive function tests whether or not a given character
* encoding supports ASCII. 7/8-bit encodings like Shift_JIS will
* fail this test, and require special processing. Variable width
* encodings shouldn't ever fail.
- *
+ *
* @param string $encoding Encoding name to test, as per iconv format
* @param bool $bypass Whether or not to bypass the precompiled arrays.
* @return Array of UTF-8 characters to their corresponding ASCII,
set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
if (iconv('UTF-8', $encoding, 'a') === false) return false;
for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars
- $c = chr($i);
- if (iconv('UTF-8', "$encoding//IGNORE", $c) === '') {
+ $c = chr($i); // UTF-8 char
+ $r = iconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion
+ if (
+ $r === '' ||
+ // This line is needed for iconv implementations that do not
+ // omit characters that do not exist in the target character set
+ ($r === $c && iconv($encoding, 'UTF-8//IGNORE', $r) !== $c)
+ ) {
// Reverse engineer: what's the UTF-8 equiv of this byte
// sequence? This assumes that there's no variable width
// encoding that doesn't support ASCII.
$encodings[$encoding] = $ret;
return $ret;
}
-
-
+
+
}
+// vim: et sw=4 sts=4
* Object that provides entity lookup table from entity name to character
*/
class HTMLPurifier_EntityLookup {
-
+
/**
* Assoc array of entity name to character represented.
*/
public $table;
-
+
/**
* Sets up the entity lookup table from the serialized file contents.
* @note The serialized contents are versioned, but were generated
}
$this->table = unserialize(file_get_contents($file));
}
-
+
/**
* Retrieves sole instance of the object.
* @param Optional prototype of custom lookup table to overload with.
}
return $instance;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_EntityParser
{
-
+
/**
* Reference to entity lookup table.
*/
protected $_entity_lookup;
-
+
/**
* Callback regex string for parsing entities.
- */
+ */
protected $_substituteEntitiesRegex =
'/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\d+)|([A-Za-z_:][A-Za-z0-9.\-_:]*));?/';
// 1. hex 2. dec 3. string (XML style)
-
-
+
+
/**
* Decimal to parsed string conversion table for special entities.
*/
60 => '<',
62 => '>'
);
-
+
/**
* Stripped entity names to decimal conversion table for special entities.
*/
'lt' => 60,
'gt' => 62
);
-
+
/**
* Substitutes non-special entities with their parsed equivalents. Since
* running this whenever you have parsed character is t3h 5uck, we run
* it before everything else.
- *
+ *
* @param $string String to have non-special entities parsed.
* @returns Parsed string.
*/
$string
);
}
-
+
/**
* Callback function for substituteNonSpecialEntities() that does the work.
- *
+ *
* @param $matches PCRE matches array, with 0 the entire match, and
* either index 1, 2 or 3 set with a hex value, dec value,
* or string (respectively).
* @returns Replacement string.
*/
-
+
protected function nonSpecialEntityCallback($matches) {
// replaces all but big five
$entity = $matches[0];
if ($is_num) {
$is_hex = (@$entity[2] === 'x');
$code = $is_hex ? hexdec($matches[1]) : (int) $matches[2];
-
+
// abort for special characters
if (isset($this->_special_dec2str[$code])) return $entity;
-
+
return HTMLPurifier_Encoder::unichr($code);
} else {
if (isset($this->_special_ent2dec[$matches[3]])) return $entity;
}
}
}
-
+
/**
* Substitutes only special entities with their parsed equivalents.
- *
+ *
* @notice We try to avoid calling this function because otherwise, it
* would have to be called a lot (for every parsed section).
- *
+ *
* @param $string String to have non-special entities parsed.
* @returns Parsed string.
*/
array($this, 'specialEntityCallback'),
$string);
}
-
+
/**
* Callback function for substituteSpecialEntities() that does the work.
- *
+ *
* This callback has same syntax as nonSpecialEntityCallback().
- *
+ *
* @param $matches PCRE-style matches array, with 0 the entire match, and
* either index 1, 2 or 3 set with a hex value, dec value,
* or string (respectively).
$entity;
}
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ErrorCollector
{
-
+
/**
* Identifiers for the returned error array. These are purposely numeric
* so list() can be used.
const SEVERITY = 1;
const MESSAGE = 2;
const CHILDREN = 3;
-
+
protected $errors;
protected $_current;
protected $_stacks = array(array());
protected $locale;
protected $generator;
protected $context;
-
+
protected $lines = array();
-
+
public function __construct($context) {
$this->locale =& $context->get('Locale');
$this->context = $context;
$this->_current =& $this->_stacks[0];
$this->errors =& $this->_stacks[0];
}
-
+
/**
* Sends an error message to the collector for later use
* @param $severity int Error severity, PHP error style (don't use E_USER_)
* @param $subst2 string ...
*/
public function send($severity, $msg) {
-
+
$args = array();
if (func_num_args() > 2) {
$args = func_get_args();
array_shift($args);
unset($args[0]);
}
-
+
$token = $this->context->get('CurrentToken', true);
$line = $token ? $token->line : $this->context->get('CurrentLine', true);
$col = $token ? $token->col : $this->context->get('CurrentCol', true);
$attr = $this->context->get('CurrentAttr', true);
-
+
// perform special substitutions, also add custom parameters
$subst = array();
if (!is_null($token)) {
$subst['$CurrentAttr.Name'] = $attr;
if (isset($token->attr[$attr])) $subst['$CurrentAttr.Value'] = $token->attr[$attr];
}
-
+
if (empty($args)) {
$msg = $this->locale->getMessage($msg);
} else {
$msg = $this->locale->formatMessage($msg, $args);
}
-
+
if (!empty($subst)) $msg = strtr($msg, $subst);
-
+
// (numerically indexed)
$error = array(
self::LINENO => $line,
self::CHILDREN => array()
);
$this->_current[] = $error;
-
-
+
+
// NEW CODE BELOW ...
-
+
$struct = null;
// Top-level errors are either:
// TOKEN type, if $value is set appropriately, or
}
}
ksort($this->lines, SORT_NUMERIC);
-
+
// Now, check if we need to operate on a lower structure
if (!empty($attr)) {
$struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr);
$struct->value = array($cssprop, 'PUT VALUE HERE');
}
}
-
+
// Ok, structs are all setup, now time to register the error
$struct->addError($severity, $msg);
}
-
+
/**
* Retrieves raw error data for custom formatter to use
* @param List of arrays in format of array(line of error,
public function getRaw() {
return $this->errors;
}
-
+
/**
* Default HTML formatting implementation for error messages
* @param $config Configuration array, vital for HTML output nature
*/
public function getHTMLFormatted($config, $errors = null) {
$ret = array();
-
+
$this->generator = new HTMLPurifier_Generator($config, $this->context);
if ($errors === null) $errors = $this->errors;
-
+
// 'At line' message needs to be removed
-
+
// generation code for new structure goes here. It needs to be recursive.
foreach ($this->lines as $line => $col_array) {
if ($line == -1) continue;
if (isset($this->lines[-1])) {
$this->_renderStruct($ret, $this->lines[-1]);
}
-
+
if (empty($errors)) {
return '<p>' . $this->locale->getMessage('ErrorCollector: No errors') . '</p>';
} else {
return '<ul><li>' . implode('</li><li>', $ret) . '</li></ul>';
}
-
+
}
-
+
private function _renderStruct(&$ret, $struct, $line = null, $col = null) {
$stack = array($struct);
$context_stack = array(array());
}
}
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_ErrorStruct
{
-
+
/**
* Possible values for $children first-key. Note that top-level structures
* are automatically token-level.
const TOKEN = 0;
const ATTR = 1;
const CSSPROP = 2;
-
+
/**
* Type of this struct.
*/
public $type;
-
+
/**
* Value of the struct we are recording errors for. There are various
* values for this:
* - CSSPROP: array('prop-name', 'value')
*/
public $value;
-
+
/**
* Errors registered for this structure.
*/
public $errors = array();
-
+
/**
* Child ErrorStructs that are from this structure. For example, a TOKEN
* ErrorStruct would contain ATTR ErrorStructs. This is a multi-dimensional
* array in structure: [TYPE]['identifier']
*/
public $children = array();
-
+
public function getChild($type, $id) {
if (!isset($this->children[$type][$id])) {
$this->children[$type][$id] = new HTMLPurifier_ErrorStruct();
}
return $this->children[$type][$id];
}
-
+
public function addError($severity, $message) {
$this->errors[] = array($severity, $message);
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Exception extends Exception
{
-
+
}
+// vim: et sw=4 sts=4
/**
* Represents a pre or post processing filter on HTML Purifier's output
- *
+ *
* Sometimes, a little ad-hoc fixing of HTML has to be done before
* it gets sent through HTML Purifier: you can use filters to acheive
* this effect. For instance, YouTube videos can be preserved using
* this manner. You could have used a decorator for this task, but
* PHP's support for them is not terribly robust, so we're going
* to just loop through the filters.
- *
+ *
* Filters should be exited first in, last out. If there are three filters,
* named 1, 2 and 3, the order of execution should go 1->preFilter,
* 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter,
* 1->postFilter.
- *
+ *
* @note Methods are not declared abstract as it is perfectly legitimate
* for an implementation not to want anything to happen on a step
*/
class HTMLPurifier_Filter
{
-
+
/**
* Name of the filter for identification purposes
*/
public $name;
-
+
/**
- * Pre-processor function, handles HTML before HTML Purifier
+ * Pre-processor function, handles HTML before HTML Purifier
*/
public function preFilter($html, $config, $context) {
return $html;
}
-
+
/**
* Post-processor function, handles HTML after HTML Purifier
*/
public function postFilter($html, $config, $context) {
return $html;
}
-
+
}
+// vim: et sw=4 sts=4
* This filter extracts <style> blocks from input HTML, cleans them up
* using CSSTidy, and then places them in $purifier->context->get('StyleBlocks')
* so they can be used elsewhere in the document.
- *
+ *
* @note
* See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for
* sample usage.
- *
+ *
* @note
* This filter can also be used on stylesheets not included in the
* document--something purists would probably prefer. Just directly
*/
class HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter
{
-
+
public $name = 'ExtractStyleBlocks';
private $_styleMatches = array();
private $_tidy;
-
+
public function __construct() {
$this->_tidy = new csstidy();
}
-
+
/**
* Save the contents of CSS blocks to style matches
* @param $matches preg_replace style $matches array
protected function styleCallback($matches) {
$this->_styleMatches[] = $matches[1];
}
-
+
/**
* Removes inline <style> tags from HTML, saves them for later use
* @todo Extend to indicate non-text/css style blocks
}
return $html;
}
-
+
/**
* Takes CSS (the stuff found in <style>) and cleans it.
* @warning Requires CSSTidy <http://csstidy.sourceforge.net/>
}
return $css;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_Filter_YouTube extends HTMLPurifier_Filter
{
-
+
public $name = 'YouTube';
-
+
public function preFilter($html, $config, $context) {
$pre_regex = '#<object[^>]+>.+?'.
'http://www.youtube.com/v/([A-Za-z0-9\-_]+).+?</object>#s';
$pre_replace = '<span class="youtube-embed">\1</span>';
return preg_replace($pre_regex, $pre_replace, $html);
}
-
+
public function postFilter($html, $config, $context) {
$post_regex = '#<span class="youtube-embed">([A-Za-z0-9\-_]+)</span>#';
- $post_replace = '<object width="425" height="350" '.
- 'data="http://www.youtube.com/v/\1">'.
- '<param name="movie" value="http://www.youtube.com/v/\1"></param>'.
- '<param name="wmode" value="transparent"></param>'.
+ return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);
+ }
+
+ protected function armorUrl($url) {
+ return str_replace('--', '--', $url);
+ }
+
+ protected function postFilterCallback($matches) {
+ $url = $this->armorUrl($matches[1]);
+ return '<object width="425" height="350" type="application/x-shockwave-flash" '.
+ 'data="http://www.youtube.com/v/'.$url.'">'.
+ '<param name="movie" value="http://www.youtube.com/v/'.$url.'"></param>'.
'<!--[if IE]>'.
- '<embed src="http://www.youtube.com/v/\1"'.
+ '<embed src="http://www.youtube.com/v/'.$url.'"'.
'type="application/x-shockwave-flash"'.
'wmode="transparent" width="425" height="350" />'.
'<![endif]-->'.
'</object>';
- return preg_replace($post_regex, $post_replace, $html);
+
}
-
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Generator
{
-
+
/**
* Whether or not generator should produce XML output
*/
private $_xhtml = true;
-
+
/**
* :HACK: Whether or not generator should comment the insides of <script> tags
*/
private $_scriptFix = false;
-
+
/**
* Cache of HTMLDefinition during HTML output to determine whether or
* not attributes should be minimized.
*/
private $_def;
-
+
/**
* Cache of %Output.SortAttr
*/
private $_sortAttr;
-
+
/**
* Configuration for the generator
*/
protected $config;
-
+
/**
* @param $config Instance of HTMLPurifier_Config
* @param $context Instance of HTMLPurifier_Context
$this->_def = $config->getHTMLDefinition();
$this->_xhtml = $this->_def->doctype->xml;
}
-
+
/**
* Generates HTML from an array of tokens.
* @param $tokens Array of HTMLPurifier_Token
*/
public function generateFromTokens($tokens) {
if (!$tokens) return '';
-
+
// Basic algorithm
$html = '';
for ($i = 0, $size = count($tokens); $i < $size; $i++) {
}
$html .= $this->generateFromToken($tokens[$i]);
}
-
+
// Tidy cleanup
if (extension_loaded('tidy') && $this->config->get('Output', 'TidyFormat')) {
$tidy = new Tidy;
$tidy->cleanRepair();
$html = (string) $tidy; // explicit cast necessary
}
-
+
// Normalize newlines to system defined value
$nl = $this->config->get('Output', 'Newline');
if ($nl === null) $nl = PHP_EOL;
if ($nl !== "\n") $html = str_replace("\n", $nl, $html);
return $html;
}
-
+
/**
* Generates HTML from a single token.
* @param $token HTMLPurifier_Token object.
if (!$token instanceof HTMLPurifier_Token) {
trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);
return '';
-
+
} elseif ($token instanceof HTMLPurifier_Token_Start) {
$attr = $this->generateAttributes($token->attr, $token->name);
return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';
-
+
} elseif ($token instanceof HTMLPurifier_Token_End) {
return '</' . $token->name . '>';
-
+
} elseif ($token instanceof HTMLPurifier_Token_Empty) {
$attr = $this->generateAttributes($token->attr, $token->name);
return '<' . $token->name . ($attr ? ' ' : '') . $attr .
( $this->_xhtml ? ' /': '' ) // <br /> v. <br>
. '>';
-
+
} elseif ($token instanceof HTMLPurifier_Token_Text) {
return $this->escape($token->data, ENT_NOQUOTES);
-
+
} elseif ($token instanceof HTMLPurifier_Token_Comment) {
return '<!--' . $token->data . '-->';
} else {
return '';
-
+
}
}
-
+
/**
* Special case processor for the contents of script tags
* @warning This runs into problems if there's already a literal
$data = preg_replace('#//\s*$#', '', $token->data);
return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';
}
-
+
/**
* Generates attribute declarations from attribute array.
* @note This does not include the leading or trailing space.
}
return rtrim($html);
}
-
+
/**
* Escapes raw text data.
* @todo This really ought to be protected, but until we have a facility
public function escape($string, $quote = ENT_COMPAT) {
return htmlspecialchars($string, $quote, 'UTF-8');
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Definition of the purified HTML that describes allowed children,
* attributes, and many other things.
- *
+ *
* Conventions:
- *
+ *
* All member variables that are prefixed with info
* (including the main $info array) are used by HTML Purifier internals
* and should not be directly edited when customizing the HTMLDefinition.
* They can usually be set via configuration directives or custom
* modules.
- *
+ *
* On the other hand, member variables without the info prefix are used
* internally by the HTMLDefinition and MUST NOT be used by other HTML
* Purifier internals. Many of them, however, are public, and may be
* edited by userspace code to tweak the behavior of HTMLDefinition.
- *
+ *
* @note This class is inspected by Printer_HTMLDefinition; please
* update that class if things here change.
*
*/
class HTMLPurifier_HTMLDefinition extends HTMLPurifier_Definition
{
-
+
// FULLY-PUBLIC VARIABLES ---------------------------------------------
-
+
/**
* Associative array of element names to HTMLPurifier_ElementDef
*/
public $info = array();
-
+
/**
* Associative array of global attribute name to attribute definition.
*/
public $info_global_attr = array();
-
+
/**
* String name of parent element HTML will be going into.
*/
public $info_parent = 'div';
-
+
/**
* Definition for parent element, allows parent element to be a
* tag that's not allowed inside the HTML fragment.
*/
public $info_parent_def;
-
+
/**
* String name of element used to wrap inline elements in block context
* @note This is rarely used except for BLOCKQUOTEs in strict mode
*/
public $info_block_wrapper = 'p';
-
+
/**
* Associative array of deprecated tag name to HTMLPurifier_TagTransform
*/
public $info_tag_transform = array();
-
+
/**
* Indexed list of HTMLPurifier_AttrTransform to be performed before validation.
*/
public $info_attr_transform_pre = array();
-
+
/**
* Indexed list of HTMLPurifier_AttrTransform to be performed after validation.
*/
public $info_attr_transform_post = array();
-
+
/**
* Nested lookup array of content set name (Block, Inline) to
* element name to whether or not it belongs in that content set.
*/
public $info_content_sets = array();
-
+
/**
* Indexed list of HTMLPurifier_Injector to be used.
*/
public $info_injector = array();
-
+
/**
* Doctype object
*/
public $doctype;
-
-
-
+
+
+
// RAW CUSTOMIZATION STUFF --------------------------------------------
-
+
/**
* Adds a custom attribute to a pre-existing element
* @note This is strictly convenience, and does not have a corresponding
}
$element->attr[$attr_name] = $def;
}
-
+
/**
* Adds a custom element to your HTML definition
- * @note See HTMLPurifier_HTMLModule::addElement for detailed
+ * @note See HTMLPurifier_HTMLModule::addElement for detailed
* parameter and return value descriptions.
*/
public function addElement($element_name, $type, $contents, $attr_collections, $attributes) {
$element = $module->addElement($element_name, $type, $contents, $attr_collections, $attributes);
return $element;
}
-
+
/**
* Adds a blank element to your HTML definition, for overriding
* existing behavior
$element = $module->addBlankElement($element_name);
return $element;
}
-
+
/**
* Retrieves a reference to the anonymous module, so you can
* bust out advanced features without having to make your own
}
return $this->_anonModule;
}
-
+
private $_anonModule;
-
-
+
+
// PUBLIC BUT INTERNAL VARIABLES --------------------------------------
-
+
public $type = 'HTML';
public $manager; /**< Instance of HTMLPurifier_HTMLModuleManager */
-
+
/**
* Performs low-cost, preliminary initialization.
*/
public function __construct() {
$this->manager = new HTMLPurifier_HTMLModuleManager();
}
-
+
protected function doSetup($config) {
$this->processModules($config);
$this->setupConfigStuff($config);
unset($this->manager);
-
+
// cleanup some of the element definitions
foreach ($this->info as $k => $v) {
unset($this->info[$k]->content_model);
unset($this->info[$k]->content_model_type);
}
}
-
+
/**
* Extract out the information from the manager
*/
protected function processModules($config) {
-
+
if ($this->_anonModule) {
// for user specific changes
// this is late-loaded so we don't have to deal with PHP4
$this->manager->addModule($this->_anonModule);
unset($this->_anonModule);
}
-
+
$this->manager->setup($config);
$this->doctype = $this->manager->doctype;
-
+
foreach ($this->manager->modules as $module) {
foreach($module->info_tag_transform as $k => $v) {
if ($v === false) unset($this->info_tag_transform[$k]);
else $this->info_injector[$k] = $v;
}
}
-
+
$this->info = $this->manager->getElements();
$this->info_content_sets = $this->manager->contentSets->lookup;
-
+
}
-
+
/**
* Sets up stuff based on config. We need a better way of doing this.
*/
protected function setupConfigStuff($config) {
-
+
$block_wrapper = $config->get('HTML', 'BlockWrapper');
if (isset($this->info_content_sets['Block'][$block_wrapper])) {
$this->info_block_wrapper = $block_wrapper;
trigger_error('Cannot use non-block element as block wrapper',
E_USER_ERROR);
}
-
+
$parent = $config->get('HTML', 'Parent');
$def = $this->manager->getElement($parent, true);
if ($def) {
E_USER_ERROR);
$this->info_parent_def = $this->manager->getElement($this->info_parent, true);
}
-
+
// support template text
$support = "(for information on implementing this, see the ".
"support forums) ";
-
+
// setup allowed elements -----------------------------------------
-
+
$allowed_elements = $config->get('HTML', 'AllowedElements');
$allowed_attributes = $config->get('HTML', 'AllowedAttributes'); // retrieve early
-
+
if (!is_array($allowed_elements) && !is_array($allowed_attributes)) {
$allowed = $config->get('HTML', 'Allowed');
if (is_string($allowed)) {
list($allowed_elements, $allowed_attributes) = $this->parseTinyMCEAllowedList($allowed);
}
}
-
+
if (is_array($allowed_elements)) {
foreach ($this->info as $name => $d) {
if(!isset($allowed_elements[$name])) unset($this->info[$name]);
trigger_error("Element '$element' is not supported $support", E_USER_WARNING);
}
}
-
+
// setup allowed attributes ---------------------------------------
-
+
$allowed_attributes_mutable = $allowed_attributes; // by copy!
if (is_array($allowed_attributes)) {
-
+
// This actually doesn't do anything, since we went away from
// global attributes. It's possible that userland code uses
// it, but HTMLModuleManager doesn't!
}
if ($delete) unset($this->info_global_attr[$attr]);
}
-
+
foreach ($this->info as $tag => $info) {
foreach ($info->attr as $attr => $x) {
$keys = array("$tag@$attr", $attr, "*@$attr", "$tag.$attr", "*.$attr");
break;
}
}
-
+
}
-
+
// setup forbidden elements ---------------------------------------
-
+
$forbidden_elements = $config->get('HTML', 'ForbiddenElements');
$forbidden_attributes = $config->get('HTML', 'ForbiddenAttributes');
-
+
foreach ($this->info as $tag => $info) {
if (isset($forbidden_elements[$tag])) {
unset($this->info[$tag]);
trigger_error("Error with $key: *.attr syntax not supported for HTML.ForbiddenAttributes; use attr instead", E_USER_WARNING);
}
}
-
+
// setup injectors -----------------------------------------------------
foreach ($this->info_injector as $i => $injector) {
if ($injector->checkNeeded($config) !== false) {
}
}
}
-
+
/**
* Parses a TinyMCE-flavored Allowed Elements and Attributes list into
* separate lists for processing. Format is element[attr1|attr2],element2...
* @todo Give this its own class, probably static interface
*/
public function parseTinyMCEAllowedList($list) {
-
+
$list = str_replace(array(' ', "\t"), '', $list);
-
+
$elements = array();
$attributes = array();
-
+
$chunks = preg_split('/(,|[\n\r]+)/', $list);
foreach ($chunks as $chunk) {
if (empty($chunk)) continue;
$attributes["$element.$key"] = true;
}
}
-
+
return array($elements, $attributes);
-
+
}
-
-
-}
+}
+
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModule
{
-
+
// -- Overloadable ----------------------------------------------------
-
+
/**
* Short unique string identifier of the module
*/
public $name;
-
+
/**
* Informally, a list of elements this module changes. Not used in
* any significant way.
*/
public $elements = array();
-
+
/**
* Associative array of element names to element definitions.
* Some definitions may be incomplete, to be merged in later
* with the full definition.
*/
public $info = array();
-
+
/**
* Associative array of content set names to content set additions.
* This is commonly used to, say, add an A element to the Inline
* and NOT info_content_sets member variable of HTMLDefinition.
*/
public $content_sets = array();
-
+
/**
* Associative array of attribute collection names to attribute
* collection additions. More rarely used for adding attributes to
* with extra behavior associated with it.
*/
public $attr_collections = array();
-
+
/**
* Associative array of deprecated tag name to HTMLPurifier_TagTransform
*/
public $info_tag_transform = array();
-
+
/**
* List of HTMLPurifier_AttrTransform to be performed before validation.
*/
public $info_attr_transform_pre = array();
-
+
/**
* List of HTMLPurifier_AttrTransform to be performed after validation.
*/
public $info_attr_transform_post = array();
-
+
/**
* List of HTMLPurifier_Injector to be performed during well-formedness fixing.
* An injector will only be invoked if all of it's pre-requisites are met;
* silently disabled.
*/
public $info_injector = array();
-
+
/**
* Boolean flag that indicates whether or not getChildDef is implemented.
* For optimization reasons: may save a call to a function. Be sure
* no effect!
*/
public $defines_child_def = false;
-
+
/**
* Boolean flag whether or not this module is safe. If it is not safe, all
* of its members are unsafe. Modules are safe by default (this might be
* slightly dangerous, but it doesn't make much sense to force HTML Purifier,
* which is based off of safe HTML, to explicitly say, "This is safe," even
* though there are modules which are "unsafe")
- *
+ *
* @note Previously, safety could be applied at an element level granularity.
* We've removed this ability, so in order to add "unsafe" elements
* or attributes, a dedicated module with this property set to false
* must be used.
*/
public $safe = true;
-
+
/**
- * Retrieves a proper HTMLPurifier_ChildDef subclass based on
+ * Retrieves a proper HTMLPurifier_ChildDef subclass based on
* content_model and content_model_type member variables of
* the HTMLPurifier_ElementDef class. There is a similar function
* in HTMLPurifier_HTMLDefinition.
* @return HTMLPurifier_ChildDef subclass
*/
public function getChildDef($def) {return false;}
-
+
// -- Convenience -----------------------------------------------------
-
+
/**
* Convenience function that sets up a new element
* @param $element Name of element to add
* element?
* @param $attr What unique attributes does the element define?
* @note See ElementDef for in-depth descriptions of these parameters.
- * @return Created element definition object, so you
+ * @return Created element definition object, so you
* can set advanced parameters
*/
public function addElement($element, $type, $contents, $attr_includes = array(), $attr = array()) {
if (!is_string($contents)) $this->info[$element]->child = $contents;
return $this->info[$element];
}
-
+
/**
* Convenience function that creates a totally blank, non-standalone
* element.
}
return $this->info[$element];
}
-
+
/**
* Convenience function that registers an element to a content set
* @param Element to register
else $this->content_sets[$type] .= ' | ';
$this->content_sets[$type] .= $element;
}
-
+
/**
* Convenience function that transforms single-string contents
* into separate content model and content model type
$content_model = trim($content_model);
return array($content_model_type, $content_model);
}
-
+
/**
* Convenience function that merges a list of attribute includes into
* an attribute array.
}
$attr[0] = $attr_includes;
}
-
+
/**
* Convenience function that generates a lookup table with boolean
* true as value.
}
return $ret;
}
-
+
/**
* Lazy load construction of the module after determining whether
* or not it's needed, and also when a finalized configuration object
* @param $config Instance of HTMLPurifier_Config
*/
public function setup($config) {}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Bdo extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Bdo';
public $attr_collections = array(
'I18N' => array('dir' => false)
);
-
+
public function setup($config) {
$bdo = $this->addElement(
'bdo', 'Inline', 'Inline', array('Core', 'Lang'),
)
);
$bdo->attr_transform_post['required-dir'] = new HTMLPurifier_AttrTransform_BdoDir();
-
+
$this->attr_collections['I18N']['dir'] = 'Enum#ltr,rtl';
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModule_CommonAttributes extends HTMLPurifier_HTMLModule
{
public $name = 'CommonAttributes';
-
+
public $attr_collections = array(
'Core' => array(
0 => array('Style'),
);
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Edit extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Edit';
-
+
public function setup($config) {
$contents = 'Chameleon: #PCDATA | Inline ! #PCDATA | Flow';
$attr = array(
$this->addElement('del', 'Inline', $contents, 'Common', $attr);
$this->addElement('ins', 'Inline', $contents, 'Common', $attr);
}
-
+
// HTML 4.01 specifies that ins/del must not contain block
// elements when used in an inline context, chameleon is
// a complicated workaround to acheive this effect
-
+
// Inline context ! Block context (exclamation mark is
// separator, see getChildDef for parsing)
-
+
public $defines_child_def = true;
public function getChildDef($def) {
if ($def->content_model_type != 'chameleon') return false;
$value = explode('!', $def->content_model);
return new HTMLPurifier_ChildDef_Chameleon($value[0], $value[1]);
}
-
+
}
+// vim: et sw=4 sts=4
{
public $name = 'Forms';
public $safe = false;
-
+
public $content_sets = array(
'Block' => 'Form',
'Inline' => 'Formctrl',
);
-
+
public function setup($config) {
$form = $this->addElement('form', 'Form',
'Required: Heading | List | Block | fieldset', 'Common', array(
'enctype' => 'Enum#application/x-www-form-urlencoded,multipart/form-data',
));
$form->excludes = array('form' => true);
-
+
$input = $this->addElement('input', 'Formctrl', 'Empty', 'Common', array(
'accept' => 'ContentTypes',
'accesskey' => 'Character',
'value' => 'CDATA',
));
$input->attr_transform_post[] = new HTMLPurifier_AttrTransform_Input();
-
+
$this->addElement('select', 'Formctrl', 'Required: optgroup | option', 'Common', array(
'disabled' => 'Bool#disabled',
'multiple' => 'Bool#multiple',
'size' => 'Number',
'tabindex' => 'Number',
));
-
+
$this->addElement('option', false, 'Optional: #PCDATA', 'Common', array(
'disabled' => 'Bool#disabled',
'label' => 'Text',
// It's illegal for there to be more than one selected, but not
// be multiple. Also, no selected means undefined behavior. This might
// be difficult to implement; perhaps an injector, or a context variable.
-
+
$textarea = $this->addElement('textarea', 'Formctrl', 'Optional: #PCDATA', 'Common', array(
'accesskey' => 'Character',
'cols*' => 'Number',
'tabindex' => 'Number',
));
$textarea->attr_transform_pre[] = new HTMLPurifier_AttrTransform_Textarea();
-
+
$button = $this->addElement('button', 'Formctrl', 'Optional: #PCDATA | Heading | List | Block | Inline', 'Common', array(
'accesskey' => 'Character',
'disabled' => 'Bool#disabled',
'type' => 'Enum#button,submit,reset',
'value' => 'CDATA',
));
-
+
// For exclusions, ideally we'd specify content sets, not literal elements
$button->excludes = $this->makeLookup(
'form', 'fieldset', // Form
'input', 'select', 'textarea', 'label', 'button', // Formctrl
'a' // as per HTML 4.01 spec, this is omitted by modularization
);
-
+
// Extra exclusion: img usemap="" is not permitted within this element.
// We'll omit this for now, since we don't have any good way of
// indicating it yet.
-
+
// This is HIGHLY user-unfriendly; we need a custom child-def for this
$this->addElement('fieldset', 'Form', 'Custom: (#WS?,legend,(Flow|#PCDATA)*)', 'Common');
-
+
$label = $this->addElement('label', 'Formctrl', 'Optional: #PCDATA | Inline', 'Common', array(
'accesskey' => 'Character',
// 'for' => 'IDREF', // IDREF not implemented, cannot allow
));
$label->excludes = array('label' => true);
-
+
$this->addElement('legend', false, 'Optional: #PCDATA | Inline', 'Common', array(
'accesskey' => 'Character',
));
-
+
$this->addElement('optgroup', false, 'Required: option', 'Common', array(
'disabled' => 'Bool#disabled',
'label*' => 'Text',
));
-
+
// Don't forget an injector for <isindex>. This one's a little complex
// because it maps to multiple elements.
-
+
}
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Hypertext extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Hypertext';
-
+
public function setup($config) {
$a = $this->addElement(
'a', 'Inline', 'Inline', 'Common',
// 'type' => 'ContentType',
)
);
+ $a->formatting = true;
$a->excludes = array('a' => true);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Image extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Image';
-
+
public function setup($config) {
$max = $config->get('HTML', 'MaxImgLength');
$img = $this->addElement(
// be abused, so we allow only Pixels.
'height' => 'Pixels#' . $max,
'width' => 'Pixels#' . $max,
- 'longdesc' => 'URI',
+ 'longdesc' => 'URI',
'src*' => new HTMLPurifier_AttrDef_URI(true), // embedded
)
);
$img->attr['height'] =
$img->attr['width'] = 'Length';
}
-
+
// kind of strange, but splitting things up would be inefficient
$img->attr_transform_pre[] =
$img->attr_transform_post[] =
new HTMLPurifier_AttrTransform_ImgRequired();
}
-
+
}
+// vim: et sw=4 sts=4
<?php
/**
- * XHTML 1.1 Legacy module defines elements that were previously
+ * XHTML 1.1 Legacy module defines elements that were previously
* deprecated.
- *
+ *
* @note Not all legacy elements have been implemented yet, which
* is a bit of a reverse problem as compared to browsers! In
* addition, this legacy module may implement a bit more than
* mandated by XHTML 1.1.
- *
+ *
* This module can be used in combination with TransformToStrict in order
* to transform as many deprecated elements as possible, but retain
* questionably deprecated elements that do not have good alternatives
class HTMLPurifier_HTMLModule_Legacy extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Legacy';
-
+
public function setup($config) {
-
+
$this->addElement('basefont', 'Inline', 'Empty', false, array(
'color' => 'Color',
'face' => 'Text', // extremely broad, we should
$this->addElement('menu', 'Block', 'Required: li', 'Common', array(
'compact' => 'Bool#compact'
));
- $this->addElement('s', 'Inline', 'Inline', 'Common');
- $this->addElement('strike', 'Inline', 'Inline', 'Common');
- $this->addElement('u', 'Inline', 'Inline', 'Common');
-
+
+ $s = $this->addElement('s', 'Inline', 'Inline', 'Common');
+ $s->formatting = true;
+
+ $strike = $this->addElement('strike', 'Inline', 'Inline', 'Common');
+ $strike->formatting = true;
+
+ $u = $this->addElement('u', 'Inline', 'Inline', 'Common');
+ $u->formatting = true;
+
// setup modifications to old elements
-
+
$align = 'Enum#left,right,center,justify';
-
+
$address = $this->addBlankElement('address');
$address->content_model = 'Inline | #PCDATA | p';
$address->content_model_type = 'optional';
$address->child = false;
-
+
$blockquote = $this->addBlankElement('blockquote');
$blockquote->content_model = 'Flow | #PCDATA';
$blockquote->content_model_type = 'optional';
$blockquote->child = false;
-
+
$br = $this->addBlankElement('br');
$br->attr['clear'] = 'Enum#left,all,right,none';
-
+
$caption = $this->addBlankElement('caption');
$caption->attr['align'] = 'Enum#top,bottom,left,right';
-
+
$div = $this->addBlankElement('div');
$div->attr['align'] = $align;
-
+
$dl = $this->addBlankElement('dl');
$dl->attr['compact'] = 'Bool#compact';
-
+
for ($i = 1; $i <= 6; $i++) {
$h = $this->addBlankElement("h$i");
$h->attr['align'] = $align;
}
-
+
$hr = $this->addBlankElement('hr');
$hr->attr['align'] = $align;
$hr->attr['noshade'] = 'Bool#noshade';
$hr->attr['size'] = 'Pixels';
$hr->attr['width'] = 'Length';
-
+
$img = $this->addBlankElement('img');
$img->attr['align'] = 'Enum#top,middle,bottom,left,right';
$img->attr['border'] = 'Pixels';
$img->attr['hspace'] = 'Pixels';
$img->attr['vspace'] = 'Pixels';
-
+
// figure out this integer business
-
+
$li = $this->addBlankElement('li');
$li->attr['value'] = new HTMLPurifier_AttrDef_Integer();
$li->attr['type'] = 'Enum#s:1,i,I,a,A,disc,square,circle';
-
+
$ol = $this->addBlankElement('ol');
$ol->attr['compact'] = 'Bool#compact';
$ol->attr['start'] = new HTMLPurifier_AttrDef_Integer();
$ol->attr['type'] = 'Enum#s:1,i,I,a,A';
-
+
$p = $this->addBlankElement('p');
$p->attr['align'] = $align;
-
+
$pre = $this->addBlankElement('pre');
$pre->attr['width'] = 'Number';
-
+
// script omitted
-
+
$table = $this->addBlankElement('table');
$table->attr['align'] = 'Enum#left,center,right';
$table->attr['bgcolor'] = 'Color';
-
+
$tr = $this->addBlankElement('tr');
$tr->attr['bgcolor'] = 'Color';
-
+
$th = $this->addBlankElement('th');
$th->attr['bgcolor'] = 'Color';
$th->attr['height'] = 'Length';
$th->attr['nowrap'] = 'Bool#nowrap';
$th->attr['width'] = 'Length';
-
+
$td = $this->addBlankElement('td');
$td->attr['bgcolor'] = 'Color';
$td->attr['height'] = 'Length';
$td->attr['nowrap'] = 'Bool#nowrap';
$td->attr['width'] = 'Length';
-
+
$ul = $this->addBlankElement('ul');
$ul->attr['compact'] = 'Bool#compact';
$ul->attr['type'] = 'Enum#square,disc,circle';
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_List extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'List';
-
+
// According to the abstract schema, the List content set is a fully formed
// one or more expr, but it invariably occurs in an optional declaration
// so we're not going to do that subtlety. It might cause trouble
// Furthermore, the actual XML Schema may disagree. Regardless,
// we don't have support for such nested expressions without using
// the incredibly inefficient and draconic Custom ChildDef.
-
+
public $content_sets = array('Flow' => 'List');
-
+
public function setup($config) {
$this->addElement('ol', 'List', 'Required: li', 'Common');
$this->addElement('ul', 'List', 'Required: li', 'Common');
$this->addElement('dl', 'List', 'Required: dt | dd', 'Common');
-
+
$this->addElement('li', false, 'Flow', 'Common');
-
+
$this->addElement('dd', false, 'Flow', 'Common');
$this->addElement('dt', false, 'Inline', 'Common');
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModule_Name extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Name';
-
+
public function setup($config) {
$elements = array('a', 'applet', 'form', 'frame', 'iframe', 'img', 'map');
foreach ($elements as $name) {
$element->attr['name'] = 'ID';
}
}
-
+
}
+
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModule_NonXMLCommonAttributes extends HTMLPurifier_HTMLModule
{
public $name = 'NonXMLCommonAttributes';
-
+
public $attr_collections = array(
'Lang' => array(
'lang' => 'LanguageCode',
);
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Object extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Object';
public $safe = false;
-
+
public function setup($config) {
-
- $this->addElement('object', 'Inline', 'Optional: #PCDATA | Flow | param', 'Common',
+
+ $this->addElement('object', 'Inline', 'Optional: #PCDATA | Flow | param', 'Common',
array(
'archive' => 'URI',
'classid' => 'URI',
'valuetype' => 'Enum#data,ref,object'
)
);
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Presentation extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Presentation';
-
+
public function setup($config) {
- $this->addElement('b', 'Inline', 'Inline', 'Common');
- $this->addElement('big', 'Inline', 'Inline', 'Common');
$this->addElement('hr', 'Block', 'Empty', 'Common');
- $this->addElement('i', 'Inline', 'Inline', 'Common');
- $this->addElement('small', 'Inline', 'Inline', 'Common');
$this->addElement('sub', 'Inline', 'Inline', 'Common');
$this->addElement('sup', 'Inline', 'Inline', 'Common');
- $this->addElement('tt', 'Inline', 'Inline', 'Common');
+ $b = $this->addElement('b', 'Inline', 'Inline', 'Common');
+ $b->formatting = true;
+ $big = $this->addElement('big', 'Inline', 'Inline', 'Common');
+ $big->formatting = true;
+ $i = $this->addElement('i', 'Inline', 'Inline', 'Common');
+ $i->formatting = true;
+ $small = $this->addElement('small', 'Inline', 'Inline', 'Common');
+ $small->formatting = true;
+ $tt = $this->addElement('tt', 'Inline', 'Inline', 'Common');
+ $tt->formatting = true;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Proprietary extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Proprietary';
-
+
public function setup($config) {
-
- $this->addElement('marquee', 'Inline', 'Flow', 'Common',
+
+ $this->addElement('marquee', 'Inline', 'Flow', 'Common',
array(
'direction' => 'Enum#left,right,up,down',
'behavior' => 'Enum#alternate',
'vspace' => 'Pixels',
)
);
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Ruby extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Ruby';
-
+
public function setup($config) {
$this->addElement('ruby', 'Inline',
'Custom: ((rb, (rt | (rp, rt, rp))) | (rbc, rtc, rtc?))',
$rt->excludes = array('ruby' => true);
$this->addElement('rp', false, 'Optional: #PCDATA', 'Common');
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_SafeEmbed extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'SafeEmbed';
-
+
public function setup($config) {
-
+
$max = $config->get('HTML', 'MaxImgLength');
$embed = $this->addElement(
'embed', 'Inline', 'Empty', 'Common',
)
);
$embed->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeEmbed();
-
+
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_SafeObject extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'SafeObject';
-
+
public function setup($config) {
-
+
// These definitions are not intrinsically safe: the attribute transforms
// are a vital part of ensuring safety.
-
+
$max = $config->get('HTML', 'MaxImgLength');
$object = $this->addElement(
'object',
$param = $this->addElement('param', false, 'Empty', false,
array(
'id' => 'ID',
- 'name*' => 'Text',
+ 'name*' => 'Text',
'value' => 'Text'
)
);
$param->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeParam();
$this->info_injector[] = 'SafeObject';
-
+
}
-
+
}
+
+// vim: et sw=4 sts=4
public $elements = array('script', 'noscript');
public $content_sets = array('Block' => 'script | noscript', 'Inline' => 'script | noscript');
public $safe = false;
-
+
public function setup($config) {
// TODO: create custom child-definition for noscript that
- // auto-wraps stray #PCDATA in a similar manner to
+ // auto-wraps stray #PCDATA in a similar manner to
// blockquote's custom definition (we would use it but
// blockquote's contents are optional while noscript's contents
// are required)
-
+
// TODO: convert this to new syntax, main problem is getting
// both content sets working
-
+
// In theory, this could be safe, but I don't see any reason to
// allow it.
$this->info['noscript'] = new HTMLPurifier_ElementDef();
$this->info['noscript']->attr = array( 0 => array('Common') );
$this->info['noscript']->content_model = 'Heading | List | Block';
$this->info['noscript']->content_model_type = 'required';
-
+
$this->info['script'] = new HTMLPurifier_ElementDef();
$this->info['script']->attr = array(
'defer' => new HTMLPurifier_AttrDef_Enum(array('defer')),
}
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_StyleAttribute extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'StyleAttribute';
public $attr_collections = array(
// The inclusion routine differs from the Abstract Modules but
'Style' => array('style' => false), // see constructor
'Core' => array(0 => array('Style'))
);
-
+
public function setup($config) {
$this->attr_collections['Style']['style'] = new HTMLPurifier_AttrDef_CSS();
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Tables extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Tables';
-
+
public function setup($config) {
-
+
$this->addElement('caption', false, 'Inline', 'Common');
-
- $this->addElement('table', 'Block',
- new HTMLPurifier_ChildDef_Table(), 'Common',
+
+ $this->addElement('table', 'Block',
+ new HTMLPurifier_ChildDef_Table(), 'Common',
array(
'border' => 'Pixels',
'cellpadding' => 'Length',
'width' => 'Length'
)
);
-
+
// common attributes
$cell_align = array(
'align' => 'Enum#left,center,right,justify,char',
'charoff' => 'Length',
'valign' => 'Enum#top,middle,bottom,baseline',
);
-
+
$cell_t = array_merge(
array(
'abbr' => 'Text',
);
$this->addElement('td', false, 'Flow', 'Common', $cell_t);
$this->addElement('th', false, 'Flow', 'Common', $cell_t);
-
+
$this->addElement('tr', false, 'Required: td | th', 'Common', $cell_align);
-
+
$cell_col = array_merge(
array(
'span' => 'Number',
);
$this->addElement('col', false, 'Empty', 'Common', $cell_col);
$this->addElement('colgroup', false, 'Optional: col', 'Common', $cell_col);
-
+
$this->addElement('tbody', false, 'Required: tr', 'Common', $cell_align);
$this->addElement('thead', false, 'Required: tr', 'Common', $cell_align);
$this->addElement('tfoot', false, 'Required: tr', 'Common', $cell_align);
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Target extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Target';
-
+
public function setup($config) {
$elements = array('a');
foreach ($elements as $name) {
);
}
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Text extends HTMLPurifier_HTMLModule
{
-
+
public $name = 'Text';
public $content_sets = array(
'Flow' => 'Heading | Block | Inline'
);
-
+
public function setup($config) {
-
+
// Inline Phrasal -------------------------------------------------
$this->addElement('abbr', 'Inline', 'Inline', 'Common');
$this->addElement('acronym', 'Inline', 'Inline', 'Common');
$this->addElement('cite', 'Inline', 'Inline', 'Common');
- $this->addElement('code', 'Inline', 'Inline', 'Common');
$this->addElement('dfn', 'Inline', 'Inline', 'Common');
- $this->addElement('em', 'Inline', 'Inline', 'Common');
$this->addElement('kbd', 'Inline', 'Inline', 'Common');
$this->addElement('q', 'Inline', 'Inline', 'Common', array('cite' => 'URI'));
$this->addElement('samp', 'Inline', 'Inline', 'Common');
- $this->addElement('strong', 'Inline', 'Inline', 'Common');
$this->addElement('var', 'Inline', 'Inline', 'Common');
-
+
+ $em = $this->addElement('em', 'Inline', 'Inline', 'Common');
+ $em->formatting = true;
+
+ $strong = $this->addElement('strong', 'Inline', 'Inline', 'Common');
+ $strong->formatting = true;
+
+ $code = $this->addElement('code', 'Inline', 'Inline', 'Common');
+ $code->formatting = true;
+
// Inline Structural ----------------------------------------------
$this->addElement('span', 'Inline', 'Inline', 'Common');
$this->addElement('br', 'Inline', 'Empty', 'Core');
$this->addElement('h4', 'Heading', 'Inline', 'Common');
$this->addElement('h5', 'Heading', 'Inline', 'Common');
$this->addElement('h6', 'Heading', 'Inline', 'Common');
-
+
// Block Structural -----------------------------------------------
- $this->addElement('p', 'Block', 'Inline', 'Common');
+ $p = $this->addElement('p', 'Block', 'Inline', 'Common');
+ $p->autoclose = array_flip(array("address", "blockquote", "center", "dir", "div", "dl", "fieldset", "ol", "p", "ul"));
+
$this->addElement('div', 'Block', 'Flow', 'Common');
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_HTMLModule_Tidy extends HTMLPurifier_HTMLModule
{
-
+
/**
* List of supported levels. Index zero is a special case "no fixes"
* level.
*/
public $levels = array(0 => 'none', 'light', 'medium', 'heavy');
-
+
/**
* Default level to place all fixes in. Disabled by default
*/
public $defaultLevel = null;
-
+
/**
* Lists of fixes used by getFixesForLevel(). Format is:
* HTMLModule_Tidy->fixesForLevel[$level] = array('fix-1', 'fix-2');
'medium' => array(),
'heavy' => array()
);
-
+
/**
* Lazy load constructs the module by determining the necessary
* fixes to create and then delegating to the populate() function.
* subtracted fix has no effect.
*/
public function setup($config) {
-
+
// create fixes, initialize fixesForLevel
$fixes = $this->makeFixes();
$this->makeFixesForLevel($fixes);
-
+
// figure out which fixes to use
$level = $config->get('HTML', 'TidyLevel');
$fixes_lookup = $this->getFixesForLevel($level);
-
+
// get custom fix declarations: these need namespace processing
$add_fixes = $config->get('HTML', 'TidyAdd');
$remove_fixes = $config->get('HTML', 'TidyRemove');
-
+
foreach ($fixes as $name => $fix) {
// needs to be refactored a little to implement globbing
if (
unset($fixes[$name]);
}
}
-
+
// populate this module with necessary fixes
$this->populate($fixes);
-
+
}
-
+
/**
* Retrieves all fixes per a level, returning fixes for that specific
* level as well as all levels below it.
}
return $ret;
}
-
+
/**
* Dynamically populates the $fixesForLevel member variable using
* the fixes array. It may be custom overloaded, used in conjunction
}
$this->fixesForLevel[$this->defaultLevel] = array_keys($fixes);
}
-
+
/**
* Populates the module with transforms and other special-case code
* based on a list of fixes passed to it
}
}
}
-
+
/**
* Parses a fix name and determines what kind of fix it is, as well
* as other information defined by the fix
$property = $attr = null;
if (strpos($name, '#') !== false) list($name, $property) = explode('#', $name);
if (strpos($name, '@') !== false) list($name, $attr) = explode('@', $name);
-
+
// figure out the parameters
$params = array();
if ($name !== '') $params['element'] = $name;
if (!is_null($attr)) $params['attr'] = $attr;
-
+
// special case: attribute transform
if (!is_null($attr)) {
if (is_null($property)) $property = 'pre';
$type = 'attr_transform_' . $property;
return array($type, $params);
}
-
+
// special case: tag transform
if (is_null($property)) {
return array('tag_transform', $params);
}
-
+
return array($property, $params);
-
+
}
-
+
/**
* Defines all fixes the module will perform in a compact
* associative array of fix name to fix implementation.
*/
public function makeFixes() {}
-
-}
+}
+// vim: et sw=4 sts=4
public $name = 'Tidy_Name';
public $defaultLevel = 'heavy';
public function makeFixes() {
-
+
$r = array();
-
+
// @name for img, a -----------------------------------------------
// Technically, it's allowed even on strict, so we allow authors to use
// it. However, it's deprecated in future versions of XHTML.
- $r['img@name'] =
+ $r['img@name'] =
$r['a@name'] = new HTMLPurifier_AttrTransform_Name();
-
+
return $r;
}
}
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModule_Tidy_Proprietary extends HTMLPurifier_HTMLModule_Tidy
{
-
+
public $name = 'Tidy_Proprietary';
public $defaultLevel = 'light';
-
+
public function makeFixes() {
$r = array();
$r['table@background'] = new HTMLPurifier_AttrTransform_Background();
$r['tbody@background'] = new HTMLPurifier_AttrTransform_Background();
return $r;
}
-
+
}
+// vim: et sw=4 sts=4
{
public $name = 'Tidy_Strict';
public $defaultLevel = 'light';
-
+
public function makeFixes() {
$r = parent::makeFixes();
$r['blockquote#content_model_type'] = 'strictblockquote';
return $r;
}
-
+
public $defines_child_def = true;
public function getChildDef($def) {
if ($def->content_model_type != 'strictblockquote') return parent::getChildDef($def);
return new HTMLPurifier_ChildDef_StrictBlockquote($def->content_model);
}
}
+
+// vim: et sw=4 sts=4
public $defaultLevel = 'heavy';
}
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModule_Tidy_XHTML extends HTMLPurifier_HTMLModule_Tidy
{
-
+
public $name = 'Tidy_XHTML';
public $defaultLevel = 'medium';
-
+
public function makeFixes() {
$r = array();
$r['@lang'] = new HTMLPurifier_AttrTransform_Lang();
return $r;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 extends HTMLPurifier_HTMLModule_Tidy
{
-
+
public function makeFixes() {
-
+
$r = array();
-
+
// == deprecated tag transforms ===================================
-
+
$r['font'] = new HTMLPurifier_TagTransform_Font();
$r['menu'] = new HTMLPurifier_TagTransform_Simple('ul');
$r['dir'] = new HTMLPurifier_TagTransform_Simple('ul');
$r['u'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:underline;');
$r['s'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');
$r['strike'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');
-
+
// == deprecated attribute transforms =============================
-
- $r['caption@align'] =
+
+ $r['caption@align'] =
new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
// we're following IE's behavior, not Firefox's, due
// to the fact that no one supports caption-side:right,
'top' => 'caption-side:top;',
'bottom' => 'caption-side:bottom;' // not supported by IE
));
-
+
// @align for img -------------------------------------------------
$r['img@align'] =
new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
'middle' => 'vertical-align:middle;',
'bottom' => 'vertical-align:baseline;',
));
-
+
// @align for table -----------------------------------------------
$r['table@align'] =
new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
'center' => 'margin-left:auto;margin-right:auto;',
'right' => 'float:right;'
));
-
+
// @align for hr -----------------------------------------------
$r['hr@align'] =
new HTMLPurifier_AttrTransform_EnumToCSS('align', array(
'center' => 'margin-left:auto;margin-right:auto;text-align:center;',
'right' => 'margin-left:auto;margin-right:0;text-align:right;'
));
-
+
// @align for h1, h2, h3, h4, h5, h6, p, div ----------------------
// {{{
$align_lookup = array();
$r['h5@align'] =
$r['h6@align'] =
$r['p@align'] =
- $r['div@align'] =
+ $r['div@align'] =
new HTMLPurifier_AttrTransform_EnumToCSS('align', $align_lookup);
-
+
// @bgcolor for table, tr, td, th ---------------------------------
$r['table@bgcolor'] =
$r['td@bgcolor'] =
$r['th@bgcolor'] =
new HTMLPurifier_AttrTransform_BgColor();
-
+
// @border for img ------------------------------------------------
$r['img@border'] = new HTMLPurifier_AttrTransform_Border();
-
+
// @clear for br --------------------------------------------------
$r['br@clear'] =
new HTMLPurifier_AttrTransform_EnumToCSS('clear', array(
'all' => 'clear:both;',
'none' => 'clear:none;',
));
-
+
// @height for td, th ---------------------------------------------
- $r['td@height'] =
+ $r['td@height'] =
$r['th@height'] =
new HTMLPurifier_AttrTransform_Length('height');
-
+
// @hspace for img ------------------------------------------------
$r['img@hspace'] = new HTMLPurifier_AttrTransform_ImgSpace('hspace');
-
+
// @noshade for hr ------------------------------------------------
// this transformation is not precise but often good enough.
// different browsers use different styles to designate noshade
'noshade',
'color:#808080;background-color:#808080;border:0;'
);
-
+
// @nowrap for td, th ---------------------------------------------
- $r['td@nowrap'] =
+ $r['td@nowrap'] =
$r['th@nowrap'] =
new HTMLPurifier_AttrTransform_BoolToCSS(
'nowrap',
'white-space:nowrap;'
);
-
+
// @size for hr --------------------------------------------------
$r['hr@size'] = new HTMLPurifier_AttrTransform_Length('size', 'height');
-
+
// @type for li, ol, ul -------------------------------------------
// {{{
$ul_types = array(
);
$li_types = $ul_types + $ol_types;
// }}}
-
+
$r['ul@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ul_types);
$r['ol@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ol_types, true);
$r['li@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $li_types, true);
-
+
// @vspace for img ------------------------------------------------
$r['img@vspace'] = new HTMLPurifier_AttrTransform_ImgSpace('vspace');
-
+
// @width for hr, td, th ------------------------------------------
$r['td@width'] =
- $r['th@width'] =
+ $r['th@width'] =
$r['hr@width'] = new HTMLPurifier_AttrTransform_Length('width');
-
+
return $r;
-
+
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModule_XMLCommonAttributes extends HTMLPurifier_HTMLModule
{
public $name = 'XMLCommonAttributes';
-
+
public $attr_collections = array(
/* moodle comment - xml:lang breaks our multilang
'Lang' => array(
);
}
+// vim: et sw=4 sts=4
class HTMLPurifier_HTMLModuleManager
{
-
+
/**
* Instance of HTMLPurifier_DoctypeRegistry
*/
public $doctypes;
-
+
/**
* Instance of current doctype
*/
public $doctype;
-
+
/**
* Instance of HTMLPurifier_AttrTypes
*/
public $attrTypes;
-
+
/**
* Active instances of modules for the specified doctype are
* indexed, by name, in this array.
*/
public $modules = array();
-
+
/**
- * Array of recognized HTMLPurifier_Module instances, indexed by
+ * Array of recognized HTMLPurifier_Module instances, indexed by
* module's class name. This array is usually lazy loaded, but a
* user can overload a module by pre-emptively registering it.
*/
public $registeredModules = array();
-
+
/**
* List of extra modules that were added by the user using addModule().
* These get unconditionally merged into the current doctype, whatever
* it may be.
*/
public $userModules = array();
-
+
/**
* Associative array of element name to list of modules that have
* definitions for the element; this array is dynamically filled.
*/
public $elementLookup = array();
-
+
/** List of prefixes we should use for registering small names */
public $prefixes = array('HTMLPurifier_HTMLModule_');
-
+
public $contentSets; /**< Instance of HTMLPurifier_ContentSets */
public $attrCollections; /**< Instance of HTMLPurifier_AttrCollections */
-
+
/** If set to true, unsafe elements and attributes will be allowed */
public $trusted = false;
-
+
public function __construct() {
-
+
// editable internal objects
$this->attrTypes = new HTMLPurifier_AttrTypes();
$this->doctypes = new HTMLPurifier_DoctypeRegistry();
-
+
// setup basic modules
$common = array(
'CommonAttributes', 'Text', 'Hypertext', 'List',
// Unsafe:
'Scripting', 'Object', 'Forms',
// Sorta legacy, but present in strict:
- 'Name',
+ 'Name',
);
$transitional = array('Legacy', 'Target');
$xml = array('XMLCommonAttributes');
$non_xml = array('NonXMLCommonAttributes');
-
+
// setup basic doctypes
$this->doctypes->register(
'HTML 4.01 Transitional', false,
'-//W3C//DTD HTML 4.01 Transitional//EN',
'http://www.w3.org/TR/html4/loose.dtd'
);
-
+
$this->doctypes->register(
'HTML 4.01 Strict', false,
array_merge($common, $non_xml),
'-//W3C//DTD HTML 4.01//EN',
'http://www.w3.org/TR/html4/strict.dtd'
);
-
+
$this->doctypes->register(
'XHTML 1.0 Transitional', true,
array_merge($common, $transitional, $xml, $non_xml),
'-//W3C//DTD XHTML 1.0 Transitional//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
);
-
+
$this->doctypes->register(
'XHTML 1.0 Strict', true,
array_merge($common, $xml, $non_xml),
'-//W3C//DTD XHTML 1.0 Strict//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
);
-
+
$this->doctypes->register(
'XHTML 1.1', true,
array_merge($common, $xml, array('Ruby')),
'-//W3C//DTD XHTML 1.1//EN',
'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'
);
-
+
}
-
+
/**
* Registers a module to the recognized module list, useful for
* overloading pre-existing modules.
}
$this->registeredModules[$module->name] = $module;
}
-
+
/**
* Adds a module to the current doctype by first registering it,
* and then tacking it on to the active doctype
if (is_object($module)) $module = $module->name;
$this->userModules[] = $module;
}
-
+
/**
* Adds a class prefix that registerModule() will use to resolve a
* string name to a concrete class
public function addPrefix($prefix) {
$this->prefixes[] = $prefix;
}
-
+
/**
* Performs processing on modules, after being called you may
* use getElement() and getElements()
* @param $config Instance of HTMLPurifier_Config
*/
public function setup($config) {
-
+
$this->trusted = $config->get('HTML', 'Trusted');
-
+
// generate
$this->doctype = $this->doctypes->make($config);
$modules = $this->doctype->modules;
-
+
// take out the default modules that aren't allowed
$lookup = $config->get('HTML', 'AllowedModules');
$special_cases = $config->get('HTML', 'CoreModules');
-
+
if (is_array($lookup)) {
foreach ($modules as $k => $m) {
if (isset($special_cases[$m])) continue;
if (!isset($lookup[$m])) unset($modules[$k]);
}
}
-
+
// add proprietary module (this gets special treatment because
// it is completely removed from doctypes, etc.)
if ($config->get('HTML', 'Proprietary')) {
$modules[] = 'Proprietary';
}
-
+
// add SafeObject/Safeembed modules
if ($config->get('HTML', 'SafeObject')) {
$modules[] = 'SafeObject';
if ($config->get('HTML', 'SafeEmbed')) {
$modules[] = 'SafeEmbed';
}
-
+
// merge in custom modules
$modules = array_merge($modules, $this->userModules);
-
+
foreach ($modules as $module) {
$this->processModule($module);
$this->modules[$module]->setup($config);
}
-
+
foreach ($this->doctype->tidyModules as $module) {
$this->processModule($module);
$this->modules[$module]->setup($config);
}
-
+
// prepare any injectors
foreach ($this->modules as $module) {
$n = array();
}
$module->info_injector = $n;
}
-
+
// setup lookup table based on all valid modules
foreach ($this->modules as $module) {
foreach ($module->info as $name => $def) {
$this->elementLookup[$name][] = $module->name;
}
}
-
+
// note the different choice
$this->contentSets = new HTMLPurifier_ContentSets(
// content set assembly deals with all possible modules,
$this->modules
);
}
-
+
/**
* Takes a module and adds it to the active module collection,
* registering it if necessary.
}
$this->modules[$module] = $this->registeredModules[$module];
}
-
+
/**
* Retrieves merged element definitions.
* @return Array of HTMLPurifier_ElementDef
*/
public function getElements() {
-
+
$elements = array();
foreach ($this->modules as $module) {
if (!$this->trusted && !$module->safe) continue;
$elements[$name] = $this->getElement($name);
}
}
-
+
// remove dud elements, this happens when an element that
// appeared to be safe actually wasn't
foreach ($elements as $n => $v) {
if ($v === false) unset($elements[$n]);
}
-
+
return $elements;
-
+
}
-
+
/**
* Retrieves a single merged element definition
* @param $name Name of element
* @return Merged HTMLPurifier_ElementDef
* @note You may notice that modules are getting iterated over twice (once
* in getElements() and once here). This
- * is because
+ * is because
*/
public function getElement($name, $trusted = null) {
-
+
if (!isset($this->elementLookup[$name])) {
return false;
}
-
+
// setup global state variables
$def = false;
if ($trusted === null) $trusted = $this->trusted;
-
+
// iterate through each module that has registered itself to this
// element
foreach($this->elementLookup[$name] as $module_name) {
-
+
$module = $this->modules[$module_name];
-
+
// refuse to create/merge from a module that is deemed unsafe--
// pretend the module doesn't exist--when trusted mode is not on.
if (!$trusted && !$module->safe) {
continue;
}
-
+
// clone is used because, ideally speaking, the original
// definition should not be modified. Usually, this will
// make no difference, but for consistency's sake
$new_def = clone $module->info[$name];
-
+
if (!$def && $new_def->standalone) {
$def = $new_def;
} elseif ($def) {
// to merge into could be deferred to the end
continue;
}
-
+
// attribute value expansions
$this->attrCollections->performInclusions($def->attr);
$this->attrCollections->expandIdentifiers($def->attr, $this->attrTypes);
-
+
// descendants_are_inline, for ChildDef_Chameleon
if (is_string($def->content_model) &&
strpos($def->content_model, 'Inline') !== false) {
$def->descendants_are_inline = true;
}
}
-
+
$this->contentSets->generateChildDef($def, $module);
}
-
+
// This can occur if there is a blank definition, but no base to
// mix it in with
if (!$def) return false;
-
+
// add information on required attributes
foreach ($def->attr as $attr_name => $attr_def) {
if ($attr_def->required) {
$def->required_attr[] = $attr_name;
}
}
-
+
return $def;
-
+
}
-
-}
+}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_IDAccumulator
{
-
+
/**
* Lookup table of IDs we've accumulated.
* @public
*/
public $ids = array();
-
+
/**
* Builds an IDAccumulator, also initializing the default blacklist
* @param $config Instance of HTMLPurifier_Config
$id_accumulator->load($config->get('Attr', 'IDBlacklist'));
return $id_accumulator;
}
-
+
/**
* Add an ID to the lookup table.
* @param $id ID to be added.
if (isset($this->ids[$id])) return false;
return $this->ids[$id] = true;
}
-
+
/**
* Load a list of IDs into the lookup table
* @param $array_of_ids Array of IDs to load
$this->ids[$id] = true;
}
}
-
+
}
+// vim: et sw=4 sts=4
* Injects tokens into the document while parsing for well-formedness.
* This enables "formatter-like" functionality such as auto-paragraphing,
* smiley-ification and linkification to take place.
- *
+ *
* A note on how handlers create changes; this is done by assigning a new
* value to the $token reference. These values can take a variety of forms and
* are best described HTMLPurifier_Strategy_MakeWellFormed->processToken()
* documentation.
- *
- * @todo Allow injectors to request a re-run on their output. This
+ *
+ * @todo Allow injectors to request a re-run on their output. This
* would help if an operation is recursive.
*/
abstract class HTMLPurifier_Injector
{
-
+
/**
* Advisory name of injector, this is for friendly error messages
*/
public $name;
-
+
/**
* Instance of HTMLPurifier_HTMLDefinition
*/
protected $htmlDefinition;
-
+
/**
* Reference to CurrentNesting variable in Context. This is an array
* list of tokens that we are currently "inside"
*/
protected $currentNesting;
-
+
/**
* Reference to InputTokens variable in Context. This is an array
* list of the input tokens that are being processed.
*/
protected $inputTokens;
-
+
/**
* Reference to InputIndex variable in Context. This is an integer
* array index for $this->inputTokens that indicates what token
* is currently being processed.
*/
protected $inputIndex;
-
+
/**
* Array of elements and attributes this injector creates and therefore
* need to be allowed by the definition. Takes form of
* array('element' => array('attr', 'attr2'), 'element2')
*/
public $needed = array();
-
+
/**
* Index of inputTokens to rewind to.
*/
protected $rewind = false;
-
+
/**
* Rewind to a spot to re-perform processing. This is useful if you
* deleted a node, and now need to see if this change affected any
public function rewind($index) {
$this->rewind = $index;
}
-
+
/**
* Retrieves rewind, and then unsets it.
*/
$this->rewind = false;
return $r;
}
-
+
/**
* Prepares the injector by giving it the config and context objects:
* this allows references to important variables to be made within
$this->inputIndex =& $context->get('InputIndex');
return false;
}
-
+
/**
* This function checks if the HTML environment
* will work with the Injector: if p tags are not allowed, the
}
return false;
}
-
+
/**
* Tests if the context node allows a certain element
* @param $name Name of element to test for
}
return true;
}
-
+
/**
* Iterator function, which starts with the next token and continues until
* you reach the end of the input tokens.
$current = $this->inputTokens[$i];
return true;
}
-
+
/**
* Similar to _forward, but accepts a third parameter $nesting (which
* should be initialized at 0) and stops when we hit the end tag
}
return true;
}
-
+
/**
* Iterator function, starts with the previous token and continues until
* you reach the beginning of input tokens.
$current = $this->inputTokens[$i];
return true;
}
-
+
/**
* Initializes the iterator at the current position. Use in a do {} while;
* loop to force the _forward and _backward functions to start at the
if ($i === null) $i = $this->inputIndex;
$current = $this->inputTokens[$i];
}
-
+
/**
* Handler that is called when a text token is processed
*/
public function handleText(&$token) {}
-
+
/**
* Handler that is called when a start or empty token is processed
*/
public function handleElement(&$token) {}
-
+
/**
* Handler that is called when an end token is processed
*/
public function handleEnd(&$token) {
$this->notifyEnd($token);
}
-
+
/**
* Notifier that is called when an end token is processed
* @note This differs from handlers in that the token is read-only
* @deprecated
*/
public function notifyEnd($token) {}
-
-
+
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector
{
-
+
public $name = 'AutoParagraph';
public $needed = array('p');
-
+
private function _pStart() {
$par = new HTMLPurifier_Token_Start('p');
$par->armor['MakeWellFormed_TagClosedError'] = true;
return $par;
}
-
+
public function handleText(&$token) {
$text = $token->data;
// Does the current parent allow <p> tags?
// in the anonymous root node, or a node inside the document.
// If the text as a double-newline, the treatment is the same;
// if it doesn't, see the next if-block if you're in the document.
-
+
$i = $nesting = null;
if (!$this->forwardUntilEndToken($i, $current, $nesting) && $token->is_whitespace) {
// State 1.1: ... ^ (whitespace, then document end)
} else {
// State 1.2: PAR1
// ----
-
+
// State 1.3: PAR1\n\nPAR2
// ------------
-
+
// State 1.4: <div>PAR1\n\nPAR2 (see State 2)
// ------------
$token = array($this->_pStart());
} else {
// State 2: <div>PAR1... (similar to 1.4)
// ----
-
+
// We're in an element that allows paragraph tags, but we're not
// sure if we're going to need them.
if ($this->_pLookAhead()) {
} else {
// State 2.2.1: <div>PAR1<div>
// ----
-
+
// State 2.2.2: <div>PAR1<b>PAR1</b></div>
// ----
}
) {
// State 3.1: ...<p>PAR1
// ----
-
+
// State 3.2: ...<p>PAR1\n\nPAR2
// ------------
$token = array();
} else {
// State 4.1: ...<b>PAR1
// ----
-
+
// State 4.2: ...<b>PAR1\n\nPAR2
// ------------
}
}
-
+
public function handleElement(&$token) {
// We don't have to check if we're already in a <p> tag for block
// tokens, because the tag would have been autoclosed by MakeWellFormed.
if ($this->_isInline($token)) {
// State 1: <div>...<b>
// ---
-
+
// Check if this token is adjacent to the parent token
// (seek backwards until token isn't whitespace)
$i = null;
$this->backward($i, $prev);
-
+
if (!$prev instanceof HTMLPurifier_Token_Start) {
// Token wasn't adjacent
-
+
if (
$prev instanceof HTMLPurifier_Token_Text &&
substr($prev->data, -2) === "\n\n"
) {
// State 1.1.4: <div><p>PAR1</p>\n\n<b>
// ---
-
+
// Quite frankly, this should be handled by splitText
$token = array($this->_pStart(), $token);
} else {
// State 1.1.1: <div><p>PAR1</p><b>
// ---
-
+
// State 1.1.2: <div><br /><b>
// ---
-
+
// State 1.1.3: <div>PAR<b>
// ---
}
-
+
} else {
// State 1.2.1: <div><b>
// ---
-
+
// Lookahead to see if <p> is needed.
if ($this->_pLookAhead()) {
// State 1.3.1: <div><b>PAR1\n\nPAR2
} else {
// State 1.3.2: <div><b>PAR1</b></div>
// ---
-
+
// State 1.3.3: <div><b>PAR1</b><div></div>\n\n</div>
// ---
}
// State 3.2: <div>
// -----
}
-
+
$i = null;
if ($this->backward($i, $prev)) {
if (
) {
// State 3.1.1: ...</p>{p}<b>
// ---
-
+
// State 3.2.1: ...</p><div>
// -----
-
+
if (!is_array($token)) $token = array($token);
array_unshift($token, new HTMLPurifier_Token_Text("\n\n"));
} else {
// State 3.1.2: ...</p>\n\n{p}<b>
// ---
-
+
// State 3.2.2: ...</p>\n\n<div>
// -----
-
+
// Note: PAR<ELEM> cannot occur because PAR would have been
// wrapped in <p> tags.
}
} else {
// State 2.2: <ul><li>
// ----
-
+
// State 2.4: <p><b>
// ---
}
}
-
+
/**
* Splits up a text in paragraph tokens and appends them
* to the result stream that will replace the original
$paragraphs = array(); // without empty paragraphs
$needs_start = false;
$needs_end = false;
-
+
$c = count($raw_paragraphs);
if ($c == 1) {
// There were no double-newlines, abort quickly. In theory this
// a while, and the newline means we should start a new one.
$result[] = new HTMLPurifier_Token_End('p');
$result[] = new HTMLPurifier_Token_Text("\n\n");
- // However, the start token should only be added if
+ // However, the start token should only be added if
// there is more processing to be done (i.e. there are
// real paragraphs in here). If there are none, the
// next start paragraph tag will be handled by the
}
}
}
-
+
// Check if this was just a giant blob of whitespace. Move this earlier,
// perhaps?
if (empty($paragraphs)) {
return;
}
-
+
// Add the start tag indicated by \n\n at the beginning of $data
if ($needs_start) {
$result[] = $this->_pStart();
}
-
+
// Append the paragraphs onto the result
foreach ($paragraphs as $par) {
$result[] = new HTMLPurifier_Token_Text($par);
$result[] = new HTMLPurifier_Token_Text("\n\n");
$result[] = $this->_pStart();
}
-
+
// Remove trailing start token; Injector will handle this later if
// it was indeed needed. This prevents from needing to do a lookahead,
// at the cost of a lookbehind later.
array_pop($result);
-
- // If there is no need for an end tag, remove all of it and let
+
+ // If there is no need for an end tag, remove all of it and let
// MakeWellFormed close it later.
if (!$needs_end) {
array_pop($result); // removes \n\n
array_pop($result); // removes </p>
}
-
+
}
-
+
/**
* Returns true if passed token is inline (and, ergo, allowed in
* paragraph tags)
private function _isInline($token) {
return isset($this->htmlDefinition->info['p']->child->elements[$token->name]);
}
-
+
/**
* Looks ahead in the token list and determines whether or not we need
* to insert a <p> tag.
}
return $ok;
}
-
+
/**
* Determines if a particular token requires an earlier inline token
* to get a paragraph. This should be used with _forwardUntilEndToken
}
return null;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Injector_DisplayLinkURI extends HTMLPurifier_Injector
{
-
+
public $name = 'DisplayLinkURI';
public $needed = array('a');
-
+
public function handleElement(&$token) {
}
-
+
public function handleEnd(&$token) {
if (isset($token->start->attr['href'])){
$url = $token->start->attr['href'];
// nothing to display
}
}
-}
\ No newline at end of file
+}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Injector_Linkify extends HTMLPurifier_Injector
{
-
+
public $name = 'Linkify';
public $needed = array('a' => array('href'));
-
+
public function handleText(&$token) {
if (!$this->allowsElement('a')) return;
-
+
if (strpos($token->data, '://') === false) {
// our really quick heuristic failed, abort
// this may not work so well if we want to match things like
// "google.com", but then again, most people don't
return;
}
-
+
// there is/are URL(s). Let's split the string:
// Note: this regex is extremely permissive
$bits = preg_split('#((?:https?|ftp)://[^\s\'"<>()]+)#S', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
-
+
$token = array();
-
+
// $i = index
// $c = count
// $l = is link
$token[] = new HTMLPurifier_Token_End('a');
}
}
-
+
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Injector_PurifierLinkify extends HTMLPurifier_Injector
{
-
+
public $name = 'PurifierLinkify';
public $docURL;
public $needed = array('a' => array('href'));
-
+
public function prepare($config, $context) {
$this->docURL = $config->get('AutoFormatParam', 'PurifierLinkifyDocURL');
return parent::prepare($config, $context);
}
-
+
public function handleText(&$token) {
if (!$this->allowsElement('a')) return;
if (strpos($token->data, '%') === false) return;
-
+
$bits = preg_split('#%([a-z0-9]+\.[a-z0-9]+)#Si', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
$token = array();
-
+
// $i = index
// $c = count
// $l = is link
$token[] = new HTMLPurifier_Token_End('a');
}
}
-
+
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_Injector_RemoveEmpty extends HTMLPurifier_Injector
{
-
+
private $context, $config;
-
+
public function prepare($config, $context) {
parent::prepare($config, $context);
$this->config = $config;
$this->context = $context;
$this->attrValidator = new HTMLPurifier_AttrValidator();
}
-
+
public function handleElement(&$token) {
if (!$token instanceof HTMLPurifier_Token_Start) return;
$next = false;
return;
}
}
-
+
}
+
+// vim: et sw=4 sts=4
{
public $name = 'SafeObject';
public $needed = array('object', 'param');
-
+
protected $objectStack = array();
protected $paramStack = array();
-
+
// Keep this synchronized with AttrTransform/SafeParam.php
protected $addParam = array(
'allowScriptAccess' => 'never',
'wmode' => true,
'movie' => true,
);
-
+
public function prepare($config, $context) {
parent::prepare($config, $context);
}
-
+
public function handleElement(&$token) {
if ($token->name == 'object') {
$this->objectStack[] = $token;
}
}
}
-
+
public function handleEnd(&$token) {
// This is the WRONG way of handling the object and param stacks;
// we should be inserting them directly on the relevant object tokens
array_pop($this->paramStack);
}
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Language
{
-
+
/**
* ISO 639 language code of language. Prefers shortest possible version
*/
public $code = 'en';
-
+
/**
* Fallback language code
*/
public $fallback = false;
-
+
/**
* Array of localizable messages
*/
public $messages = array();
-
+
/**
* Array of localizable error codes
*/
public $errorNames = array();
-
+
/**
* True if no message file was found for this language, so English
* is being used instead. Check this if you'd like to notify the
* user that they've used a non-supported language.
*/
public $error = false;
-
+
/**
* Has the language object been loaded yet?
* @todo Make it private, fix usage in HTMLPurifier_LanguageTest
*/
public $_loaded = false;
-
+
/**
* Instances of HTMLPurifier_Config and HTMLPurifier_Context
*/
protected $config, $context;
-
+
public function __construct($config, $context) {
$this->config = $config;
$this->context = $context;
}
-
+
/**
* Loads language object with necessary info from factory cache
* @note This is a lazy loader
}
$this->_loaded = true;
}
-
+
/**
* Retrieves a localised message.
* @param $key string identifier of message
if (!isset($this->messages[$key])) return "[$key]";
return $this->messages[$key];
}
-
+
/**
* Retrieves a localised error name.
* @param $int integer error number, corresponding to PHP's error
if (!isset($this->errorNames[$int])) return "[Error: $int]";
return $this->errorNames[$int];
}
-
+
/**
* Converts an array list into a string readable representation
*/
}
return $ret;
}
-
+
/**
* Formats a localised message with passed parameters
* @param $key string identifier of message
if (!$generator) $generator = $this->context->get('Generator');
if (isset($value->name)) $subst['$'.$i.'.Name'] = $value->name;
if (isset($value->data)) $subst['$'.$i.'.Data'] = $value->data;
- $subst['$'.$i.'.Compact'] =
+ $subst['$'.$i.'.Compact'] =
$subst['$'.$i.'.Serialized'] = $generator->generateFromToken($value);
// a more complex algorithm for compact representation
// could be introduced for all types of tokens. This
}
return strtr($raw, $subst);
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_Language_en_x_test extends HTMLPurifier_Language
{
-
-
-
+
+
+
}
+// vim: et sw=4 sts=4
'HTMLPurifier' => 'HTML Purifier X'
);
+// vim: et sw=4 sts=4
'HTMLPurifier' => 'HTML Purifier XNone'
);
+// vim: et sw=4 sts=4
'Strategy_MakeWellFormed: Unnecessary end tag removed' => 'Unnecessary $CurrentToken.Serialized tag removed',
'Strategy_MakeWellFormed: Unnecessary end tag to text' => 'Unnecessary $CurrentToken.Serialized tag converted to text',
'Strategy_MakeWellFormed: Tag auto closed' => '$1.Compact started on line $1.Line auto-closed by $CurrentToken.Compact',
+'Strategy_MakeWellFormed: Tag carryover' => '$1.Compact started on line $1.Line auto-continued into $CurrentToken.Compact',
'Strategy_MakeWellFormed: Stray end tag removed' => 'Stray $CurrentToken.Serialized tag removed',
'Strategy_MakeWellFormed: Stray end tag to text' => 'Stray $CurrentToken.Serialized tag converted to text',
'Strategy_MakeWellFormed: Tag closed by element end' => '$1.Compact tag started on line $1.Line closed by end of $CurrentToken.Serialized',
E_NOTICE => 'Notice'
);
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_LanguageFactory
{
-
+
/**
* Cache of language code information used to load HTMLPurifier_Language objects
* Structure is: $factory->cache[$language_code][$key] = $value
* @value array map
*/
public $cache;
-
+
/**
* Valid keys in the HTMLPurifier_Language object. Designates which
* variables to slurp out of a message file.
* @value array list
*/
public $keys = array('fallback', 'messages', 'errorNames');
-
+
/**
* Instance of HTMLPurifier_AttrDef_Lang to validate language codes
* @value object HTMLPurifier_AttrDef_Lang
*/
protected $validator;
-
+
/**
* Cached copy of dirname(__FILE__), directory of current file without
* trailing slash
* @value string filename
*/
protected $dir;
-
+
/**
* Keys whose contents are a hash map and can be merged
* @value array lookup
*/
protected $mergeable_keys_map = array('messages' => true, 'errorNames' => true);
-
+
/**
* Keys whose contents are a list and can be merged
* @value array lookup
*/
protected $mergeable_keys_list = array();
-
+
/**
* Retrieve sole instance of the factory.
* @param $prototype Optional prototype to overload sole instance with,
}
return $instance;
}
-
+
/**
* Sets up the singleton, much like a constructor
* @note Prevents people from getting this outside of the singleton
$this->validator = new HTMLPurifier_AttrDef_Lang();
$this->dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier';
}
-
+
/**
* Creates a language object, handles class fallbacks
* @param $config Instance of HTMLPurifier_Config
* @param $code Code to override configuration with. Private parameter.
*/
public function create($config, $context, $code = false) {
-
+
// validate language code
if ($code === false) {
$code = $this->validator->validate(
$code = $this->validator->validate($code, $config, $context);
}
if ($code === false) $code = 'en'; // malformed code becomes English
-
+
$pcode = str_replace('-', '_', $code); // make valid PHP classname
static $depth = 0; // recursion protection
-
+
if ($code == 'en') {
$lang = new HTMLPurifier_Language($config, $context);
} else {
$depth--;
}
}
-
+
$lang->code = $code;
-
+
return $lang;
-
+
}
-
+
/**
* Returns the fallback language for language
* @note Loads the original language into cache
$this->loadLanguage($code);
return $this->cache[$code]['fallback'];
}
-
+
/**
* Loads language into the cache, handles message file and fallbacks
* @param $code string language code
*/
public function loadLanguage($code) {
static $languages_seen = array(); // recursion guard
-
+
// abort if we've already loaded it
if (isset($this->cache[$code])) return;
-
+
// generate filename
$filename = $this->dir . '/Language/messages/' . $code . '.php';
-
+
// default fallback : may be overwritten by the ensuing include
$fallback = ($code != 'en') ? 'en' : false;
-
+
// load primary localisation
if (!file_exists($filename)) {
// skip the include: will rely solely on fallback
include $filename;
$cache = compact($this->keys);
}
-
+
// load fallback localisation
if (!empty($fallback)) {
-
+
// infinite recursion guard
if (isset($languages_seen[$code])) {
trigger_error('Circular fallback reference in language ' .
$fallback = 'en';
}
$language_seen[$code] = true;
-
+
// load the fallback recursively
$this->loadLanguage($fallback);
$fallback_cache = $this->cache[$fallback];
-
+
// merge fallback with current language
foreach ( $this->keys as $key ) {
if (isset($cache[$key]) && isset($fallback_cache[$key])) {
$cache[$key] = $fallback_cache[$key];
}
}
-
+
}
-
+
// save to cache for later retrieval
$this->cache[$code] = $cache;
-
+
return;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Length
{
-
+
/**
* String numeric magnitude.
*/
protected $n;
-
+
/**
* String unit. False is permitted if $n = 0.
*/
protected $unit;
-
+
/**
* Whether or not this length is valid. Null if not calculated yet.
*/
protected $isValid;
-
+
/**
* Lookup array of units recognized by CSS 2.1
*/
'em' => true, 'ex' => true, 'px' => true, 'in' => true,
'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true
);
-
+
/**
* @param number $n Magnitude
* @param string $u Unit
$this->n = (string) $n;
$this->unit = $u !== false ? (string) $u : false;
}
-
+
/**
* @param string $s Unit string, like '2em' or '3.4in'
* @warning Does not perform validation.
if ($unit === '') $unit = false;
return new HTMLPurifier_Length($n, $unit);
}
-
+
/**
* Validates the number and unit.
*/
$this->n = $result;
return true;
}
-
+
/**
* Returns string representation of number.
*/
if (!$this->isValid()) return false;
return $this->n . $this->unit;
}
-
+
/**
* Retrieves string numeric magnitude.
*/
public function getN() {return $this->n;}
-
+
/**
* Retrieves string unit.
*/
public function getUnit() {return $this->unit;}
-
+
/**
* Returns true if this length unit is valid.
*/
if ($this->isValid === null) $this->isValid = $this->validate();
return $this->isValid;
}
-
+
/**
* Compares two lengths, and returns 1 if greater, -1 if less and 0 if equal.
* @warning If both values are too large or small, this calculation will
}
return $this->n - $l->n;
}
-
+
}
+
+// vim: et sw=4 sts=4
/**
* Forgivingly lexes HTML (SGML-style) markup into tokens.
- *
+ *
* A lexer parses a string of SGML-style markup and converts them into
* corresponding tokens. It doesn't check for well-formedness, although its
* internal mechanism may make this automatic (such as the case of
* HTMLPurifier_Lexer_DOMLex). There are several implementations to choose
* from.
- *
+ *
* A lexer is HTML-oriented: it might work with XML, but it's not
* recommended, as we adhere to a subset of the specification for optimization
* reasons. This might change in the future. Also, most tokenizers are not
* expected to handle DTDs or PIs.
- *
+ *
* This class should not be directly instantiated, but you may use create() to
* retrieve a default copy of the lexer. Being a supertype, this class
* does not actually define any implementation, but offers commonly used
* convenience functions for subclasses.
- *
+ *
* @note The unit tests will instantiate this class for testing purposes, as
* many of the utility functions require a class to be instantiated.
* This means that, even though this class is not runnable, it will
* not be declared abstract.
- *
+ *
* @par
- *
+ *
* @note
* We use tokens rather than create a DOM representation because DOM would:
- *
+ *
* @par
* -# Require more processing and memory to create,
* -# Is not streamable, and
* -# Has the entire document structure (html and body not needed).
- *
+ *
* @par
* However, DOM is helpful in that it makes it easy to move around nodes
* without a lot of lookaheads to see when a tag is closed. This is a
*/
class HTMLPurifier_Lexer
{
-
+
/**
* Whether or not this lexer implements line-number/column-number tracking.
* If it does, set to true.
*/
public $tracksLineNumbers = false;
-
+
// -- STATIC ----------------------------------------------------------
-
+
/**
* Retrieves or sets the default Lexer as a Prototype Factory.
- *
+ *
* By default HTMLPurifier_Lexer_DOMLex will be returned. There are
* a few exceptions involving special features that only DirectLex
* implements.
- *
+ *
* @note The behavior of this class has changed, rather than accepting
* a prototype object, it now accepts a configuration object.
* To specify your own prototype, set %Core.LexerImpl to it.
* This change in behavior de-singletonizes the lexer object.
- *
+ *
* @param $config Instance of HTMLPurifier_Config
* @return Concrete lexer.
*/
public static function create($config) {
-
+
if (!($config instanceof HTMLPurifier_Config)) {
$lexer = $config;
- trigger_error("Passing a prototype to
+ trigger_error("Passing a prototype to
HTMLPurifier_Lexer::create() is deprecated, please instead
use %Core.LexerImpl", E_USER_WARNING);
} else {
$lexer = $config->get('Core', 'LexerImpl');
}
-
+
$needs_tracking =
$config->get('Core', 'MaintainLineNumbers') ||
$config->get('Core', 'CollectErrors');
-
+
$inst = null;
if (is_object($lexer)) {
$inst = $lexer;
} else {
-
+
if (is_null($lexer)) { do {
// auto-detection algorithm
-
+
if ($needs_tracking) {
$lexer = 'DirectLex';
break;
}
-
+
if (
class_exists('DOMDocument') &&
method_exists('DOMDocument', 'loadHTML') &&
} else {
$lexer = 'DirectLex';
}
-
+
} while(0); } // do..while so we can break
-
+
// instantiate recognized string names
switch ($lexer) {
case 'DOMLex':
throw new HTMLPurifier_Exception("Cannot instantiate unrecognized Lexer type " . htmlspecialchars($lexer));
}
}
-
+
if (!$inst) throw new HTMLPurifier_Exception('No lexer was instantiated');
-
+
// once PHP DOM implements native line numbers, or we
// hack out something using XSLT, remove this stipulation
if ($needs_tracking && !$inst->tracksLineNumbers) {
throw new HTMLPurifier_Exception('Cannot use lexer that does not support line numbers with Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)');
}
-
+
return $inst;
-
+
}
-
+
// -- CONVENIENCE MEMBERS ---------------------------------------------
-
+
public function __construct() {
$this->_entity_parser = new HTMLPurifier_EntityParser();
}
-
+
/**
* Most common entity to raw value conversion table for special entities.
*/
''' => "'",
''' => "'"
);
-
+
/**
* Parses special entities into the proper characters.
- *
+ *
* This string will translate escaped versions of the special characters
* into the correct ones.
- *
+ *
* @warning
* You should be able to treat the output of this function as
* completely parsed, but that's only because all other entities should
* have been handled previously in substituteNonSpecialEntities()
- *
+ *
* @param $string String character data to be parsed.
* @returns Parsed character data.
*/
public function parseData($string) {
-
+
// following functions require at least one character
if ($string === '') return '';
-
+
// subtracts amps that cannot possibly be escaped
$num_amp = substr_count($string, '&') - substr_count($string, '& ') -
($string[strlen($string)-1] === '&' ? 1 : 0);
-
+
if (!$num_amp) return $string; // abort if no entities
$num_esc_amp = substr_count($string, '&');
$string = strtr($string, $this->_special_entity2str);
-
+
// code duplication for sake of optimization, see above
$num_amp_2 = substr_count($string, '&') - substr_count($string, '& ') -
($string[strlen($string)-1] === '&' ? 1 : 0);
-
+
if ($num_amp_2 <= $num_esc_amp) return $string;
-
+
// hmm... now we have some uncommon entities. Use the callback.
$string = $this->_entity_parser->substituteSpecialEntities($string);
return $string;
}
-
+
/**
* Lexes an HTML string into tokens.
- *
+ *
* @param $string String HTML.
* @return HTMLPurifier_Token array representation of HTML.
*/
public function tokenizeHTML($string, $config, $context) {
trigger_error('Call to abstract class', E_USER_ERROR);
}
-
+
/**
* Translates CDATA sections into regular sections (through escaping).
- *
+ *
* @param $string HTML string to process.
* @returns HTML with CDATA sections escaped.
*/
$string
);
}
-
+
/**
* Special CDATA case that is especially convoluted for <script>
*/
$string
);
}
-
+
/**
* Callback function for escapeCDATA() that does the work.
- *
+ *
* @warning Though this is public in order to let the callback happen,
* calling it directly is not recommended.
* @params $matches PCRE matches array, with index 0 the entire match
// not exactly sure why the character set is needed, but whatever
return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');
}
-
+
/**
* Takes a piece of HTML and normalizes it by converting entities, fixing
* encoding, extracting bits, and other good stuff.
* @todo Consider making protected
*/
public function normalize($html, $config, $context) {
-
+
// normalize newlines to \n
$html = str_replace("\r\n", "\n", $html);
$html = str_replace("\r", "\n", $html);
-
+
if ($config->get('HTML', 'Trusted')) {
// escape convoluted CDATA
$html = $this->escapeCommentedCDATA($html);
}
-
+
// escape CDATA
$html = $this->escapeCDATA($html);
-
+
// extract body from document if applicable
if ($config->get('Core', 'ConvertDocumentToFragment')) {
$html = $this->extractBody($html);
}
-
+
// expand entities that aren't the big five
$html = $this->_entity_parser->substituteNonSpecialEntities($html);
-
+
// clean into wellformed UTF-8 string for an SGML context: this has
// to be done after entity expansion because the entities sometimes
// represent non-SGML characters (horror, horror!)
$html = HTMLPurifier_Encoder::cleanUTF8($html);
-
+
return $html;
}
-
+
/**
* Takes a string of HTML (fragment or document) and returns the content
* @todo Consider making protected
return $html;
}
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Parser that uses PHP 5's DOM extension (part of the core).
- *
+ *
* In PHP 5, the DOM XML extension was revamped into DOM and added to the core.
* It gives us a forgiving HTML parser, which we use to transform the HTML
* into a DOM, and then into the tokens. It is blazingly fast (for large
* documents, it performs twenty times faster than
- * HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.
- *
+ * HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.
+ *
* @note Any empty elements will have empty tokens associated with them, even if
* this is prohibited by the spec. This is cannot be fixed until the spec
* comes into play.
- *
+ *
* @note PHP's DOM extension does not actually parse any entities, we use
* our own function to do that.
- *
+ *
* @warning DOM tends to drop whitespace, which may wreak havoc on indenting.
* If this is a huge problem, due to the fact that HTML is hand
* edited and you are unable to get a parser cache that caches the
class HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer
{
-
+
private $factory;
-
+
public function __construct() {
// setup the factory
parent::__construct();
$this->factory = new HTMLPurifier_TokenFactory();
}
-
+
public function tokenizeHTML($html, $config, $context) {
-
+
$html = $this->normalize($html, $config, $context);
-
+
// attempt to armor stray angled brackets that cannot possibly
// form tags and thus are probably being used as emoticons
if ($config->get('Core', 'AggressivelyFixLt')) {
} while ($html !== $old);
$html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments
}
-
+
// preprocess html, essential for UTF-8
$html = $this->wrapHTML($html, $config, $context);
-
+
$doc = new DOMDocument();
$doc->encoding = 'UTF-8'; // theoretically, the above has this covered
-
+
set_error_handler(array($this, 'muteErrorHandler'));
$doc->loadHTML($html);
restore_error_handler();
-
+
$tokens = array();
$this->tokenizeDOM(
$doc->getElementsByTagName('html')->item(0)-> // <html>
, $tokens);
return $tokens;
}
-
+
/**
* Recursive function that tokenizes a node, putting it into an accumulator.
- *
+ *
* @param $node DOMNode to be tokenized.
* @param $tokens Array-list of already tokenized tokens.
* @param $collect Says whether or start and close are collected, set to
* @returns Tokens of node appended to previously passed tokens.
*/
protected function tokenizeDOM($node, &$tokens, $collect = false) {
-
+
// intercept non element nodes. WE MUST catch all of them,
// but we're not getting the character reference nodes because
// those should have been preprocessed
) {
return;
}
-
+
$attr = $node->hasAttributes() ?
$this->transformAttrToAssoc($node->attributes) :
array();
-
+
// We still have to make sure that the element actually IS empty
if (!$node->childNodes->length) {
if ($collect) {
$tokens[] = $this->factory->createEnd($tag_name);
}
}
-
+
}
-
+
/**
* Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
- *
+ *
* @param $attribute_list DOMNamedNodeMap of DOMAttr objects.
* @returns Associative array of attributes.
*/
}
return $array;
}
-
+
/**
* An error handler that mutes all errors
*/
public function muteErrorHandler($errno, $errstr) {}
-
+
/**
* Callback function for undoing escaping of stray angled brackets
* in comments
public function callbackUndoCommentSubst($matches) {
return '<!--' . strtr($matches[1], array('&'=>'&','<'=>'<')) . $matches[2];
}
-
+
/**
* Callback function that entity-izes ampersands in comments so that
* callbackUndoCommentSubst doesn't clobber them
public function callbackArmorCommentEntities($matches) {
return '<!--' . str_replace('&', '&', $matches[1]) . $matches[2];
}
-
+
/**
* Wraps an HTML fragment in the necessary HTML
*/
protected function wrapHTML($html, $config, $context) {
$def = $config->getDefinition('HTML');
$ret = '';
-
+
if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
$ret .= '<!DOCTYPE html ';
if (!empty($def->doctype->dtdPublic)) $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
if (!empty($def->doctype->dtdSystem)) $ret .= '"' . $def->doctype->dtdSystem . '" ';
$ret .= '>';
}
-
+
$ret .= '<html><head>';
$ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
// No protection if $html contains a stray </div>!
$ret .= '</head><body><div>'.$html.'</div></body></html>';
return $ret;
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Our in-house implementation of a parser.
- *
+ *
* A pure PHP parser, DirectLex has absolutely no dependencies, making
* it a reasonably good default for PHP4. Written with efficiency in mind,
* it can be four times faster than HTMLPurifier_Lexer_PEARSax3, although it
* pales in comparison to HTMLPurifier_Lexer_DOMLex.
- *
+ *
* @todo Reread XML spec and document differences.
*/
class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
{
-
+
public $tracksLineNumbers = true;
-
+
/**
* Whitespace characters for str(c)spn.
*/
protected $_whitespace = "\x20\x09\x0D\x0A";
-
+
/**
* Callback function for script CDATA fudge
* @param $matches, in form of array(opening tag, contents, closing tag)
protected function scriptCallback($matches) {
return $matches[1] . htmlspecialchars($matches[2], ENT_COMPAT, 'UTF-8') . $matches[3];
}
-
+
public function tokenizeHTML($html, $config, $context) {
-
+
// special normalization for script tags without any armor
// our "armor" heurstic is a < sign any number of whitespaces after
// the first script tag
$html = preg_replace_callback('#(<script[^>]*>)(\s*[^<].+?)(</script>)#si',
array($this, 'scriptCallback'), $html);
}
-
+
$html = $this->normalize($html, $config, $context);
-
+
$cursor = 0; // our location in the text
$inside_tag = false; // whether or not we're parsing the inside of a tag
$array = array(); // result array
-
+
// This is also treated to mean maintain *column* numbers too
$maintain_line_numbers = $config->get('Core', 'MaintainLineNumbers');
-
+
if ($maintain_line_numbers === null) {
// automatically determine line numbering by checking
// if error collection is on
$maintain_line_numbers = $config->get('Core', 'CollectErrors');
}
-
+
if ($maintain_line_numbers) {
$current_line = 1;
- $current_col = 0;
+ $current_col = 0;
$length = strlen($html);
} else {
$current_line = false;
$nl = "\n";
// how often to manually recalculate. This will ALWAYS be right,
// but it's pretty wasteful. Set to 0 to turn off
- $synchronize_interval = $config->get('Core', 'DirectLexLineNumberSyncInterval');
-
+ $synchronize_interval = $config->get('Core', 'DirectLexLineNumberSyncInterval');
+
$e = false;
if ($config->get('Core', 'CollectErrors')) {
$e =& $context->get('ErrorCollector');
}
-
+
// for testing synchronization
$loops = 0;
-
+
while(++$loops) {
-
+
// $cursor is either at the start of a token, or inside of
// a tag (i.e. there was a < immediately before it), as indicated
// by $inside_tag
-
+
if ($maintain_line_numbers) {
-
+
// $rcursor, however, is always at the start of a token.
$rcursor = $cursor - (int) $inside_tag;
-
+
// Column number is cheap, so we calculate it every round.
- // We're interested at the *end* of the newline string, so
+ // We're interested at the *end* of the newline string, so
// we need to add strlen($nl) == 1 to $nl_pos before subtracting it
// from our "rcursor" position.
$nl_pos = strrpos($html, $nl, $rcursor - $length);
$current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1);
-
+
// recalculate lines
if (
$synchronize_interval && // synchronization is on
) {
$current_line = 1 + $this->substrCount($html, $nl, 0, $cursor);
}
-
+
}
-
+
$position_next_lt = strpos($html, '<', $cursor);
$position_next_gt = strpos($html, '>', $cursor);
-
+
// triggers on "<b>asdf</b>" but not "asdf <b></b>"
// special case to set up context
if ($position_next_lt === $cursor) {
$inside_tag = true;
$cursor++;
}
-
+
if (!$inside_tag && $position_next_lt !== false) {
// We are not inside tag and there still is another tag to parse
$token = new
// We are in tag and it is well formed
// Grab the internals of the tag
$strlen_segment = $position_next_gt - $cursor;
-
+
if ($strlen_segment < 1) {
// there's nothing to process!
$token = new HTMLPurifier_Token_Text('<');
$cursor++;
continue;
}
-
+
$segment = substr($html, $cursor, $strlen_segment);
-
+
if ($segment === false) {
// somehow, we attempted to access beyond the end of
// the string, defense-in-depth, reported by Nate Abele
break;
}
-
+
// Check if it's a comment
if (
substr($segment, 0, 3) === '!--'
$inside_tag = false;
continue;
}
-
+
// Check if it's an end tag
$is_end_tag = (strpos($segment,'/') === 0);
if ($is_end_tag) {
$cursor = $position_next_gt + 1;
continue;
}
-
+
// Check leading character is alnum, if not, we may
// have accidently grabbed an emoticon. Translate into
// text and go our merry way
$inside_tag = false;
continue;
}
-
+
// Check if it is explicitly self closing, if so, remove
// trailing slash. Remember, we could have a tag like <br>, so
// any later token processing scripts must convert improperly
$strlen_segment--;
$segment = substr($segment, 0, $strlen_segment);
}
-
+
// Check if there are any attributes
$position_first_space = strcspn($segment, $this->_whitespace);
-
+
if ($position_first_space >= $strlen_segment) {
if ($is_self_closing) {
$token = new HTMLPurifier_Token_Empty($segment);
$cursor = $position_next_gt + 1;
continue;
}
-
+
// Grab out all the data
$type = substr($segment, 0, $position_first_space);
$attribute_string =
} else {
$attr = array();
}
-
+
if ($is_self_closing) {
$token = new HTMLPurifier_Token_Empty($type, $attr);
} else {
}
break;
}
-
+
$context->destroy('CurrentLine');
$context->destroy('CurrentCol');
return $array;
}
-
+
/**
* PHP 5.0.x compatible substr_count that implements offset and length
*/
return substr_count($haystack, $needle, $offset, $length);
}
}
-
+
/**
* Takes the inside of an HTML tag and makes an assoc array of attributes.
- *
+ *
* @param $string Inside of tag excluding name.
* @returns Assoc array of attributes.
*/
public function parseAttributeString($string, $config, $context) {
$string = (string) $string; // quick typecast
-
+
if ($string == '') return array(); // no attributes
-
+
$e = false;
if ($config->get('Core', 'CollectErrors')) {
$e =& $context->get('ErrorCollector');
}
-
+
// let's see if we can abort as quickly as possible
// one equal sign, no spaces => one attribute
$num_equal = substr_count($string, '=');
if (!$quoted_value) return array($key => '');
$first_char = @$quoted_value[0];
$last_char = @$quoted_value[strlen($quoted_value)-1];
-
+
$same_quote = ($first_char == $last_char);
$open_quote = ($first_char == '"' || $first_char == "'");
-
+
if ( $same_quote && $open_quote) {
// well behaved
$value = substr($quoted_value, 1, strlen($quoted_value) - 2);
if ($value === false) $value = '';
return array($key => $value);
}
-
+
// setup loop environment
$array = array(); // return assoc array of attributes
$cursor = 0; // current position in string (moves forward)
$size = strlen($string); // size of the string (stays the same)
-
+
// if we have unquoted attributes, the parser expects a terminating
// space, so let's guarantee that there's always a terminating space.
$string .= ' ';
-
+
while(true) {
-
+
if ($cursor >= $size) {
break;
}
-
+
$cursor += ($value = strspn($string, $this->_whitespace, $cursor));
// grab the key
-
+
$key_begin = $cursor; //we're currently at the start of the key
-
+
// scroll past all characters that are the key (not whitespace or =)
$cursor += strcspn($string, $this->_whitespace . '=', $cursor);
-
+
$key_end = $cursor; // now at the end of the key
-
+
$key = substr($string, $key_begin, $key_end - $key_begin);
-
+
if (!$key) {
if ($e) $e->send(E_ERROR, 'Lexer: Missing attribute key');
$cursor += strcspn($string, $this->_whitespace, $cursor + 1); // prevent infinite loop
continue; // empty key
}
-
+
// scroll past all whitespace
$cursor += strspn($string, $this->_whitespace, $cursor);
-
+
if ($cursor >= $size) {
$array[$key] = $key;
break;
}
-
+
// if the next character is an equal sign, we've got a regular
// pair, otherwise, it's a bool attribute
$first_char = @$string[$cursor];
-
+
if ($first_char == '=') {
// key="value"
-
+
$cursor++;
$cursor += strspn($string, $this->_whitespace, $cursor);
-
+
if ($cursor === false) {
$array[$key] = '';
break;
}
-
+
// we might be in front of a quote right now
-
+
$char = @$string[$cursor];
-
+
if ($char == '"' || $char == "'") {
// it's quoted, end bound is $char
$cursor++;
$cursor += strcspn($string, $this->_whitespace, $cursor);
$value_end = $cursor;
}
-
+
// we reached a premature end
if ($cursor === false) {
$cursor = $size;
$value_end = $cursor;
}
-
+
$value = substr($string, $value_begin, $value_end - $value_begin);
if ($value === false) $value = '';
$array[$key] = $this->parseData($value);
$cursor++;
-
+
} else {
// boolattr
if ($key !== '') {
// purely theoretical
if ($e) $e->send(E_ERROR, 'Lexer: Missing attribute key');
}
-
+
}
}
return $array;
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Proof-of-concept lexer that uses the PEAR package XML_HTMLSax3 to parse HTML.
- *
+ *
* PEAR, not suprisingly, also has a SAX parser for HTML. I don't know
* very much about implementation, but it's fairly well written. However, that
* abstraction comes at a price: performance. You need to have it installed,
* and if the API changes, it might break our adapter. Not sure whether or not
* it's UTF-8 aware, but it has some entity parsing trouble (in all areas,
* text and attributes).
- *
+ *
* Quite personally, I don't recommend using the PEAR class, and the defaults
* don't use it. The unit tests do perform the tests on the SAX parser too, but
* whatever it does for poorly formed HTML is up to it.
- *
+ *
* @todo Generalize so that XML_HTMLSax is also supported.
- *
+ *
* @warning Entity-resolution inside attributes is broken.
*/
class HTMLPurifier_Lexer_PEARSax3 extends HTMLPurifier_Lexer
{
-
+
/**
* Internal accumulator array for SAX parsers.
*/
protected $tokens = array();
-
+
public function tokenizeHTML($string, $config, $context) {
-
+
$this->tokens = array();
-
+
$string = $this->normalize($string, $config, $context);
-
+
$parser = new XML_HTMLSax3();
$parser->set_object($this);
$parser->set_element_handler('openHandler','closeHandler');
$parser->set_data_handler('dataHandler');
$parser->set_escape_handler('escapeHandler');
-
+
// doesn't seem to work correctly for attributes
$parser->set_option('XML_OPTION_ENTITIES_PARSED', 1);
-
+
$parser->parse($string);
-
+
return $this->tokens;
-
+
}
-
+
/**
* Open tag event handler, interface is defined by PEAR package.
*/
}
return true;
}
-
+
/**
* Close tag event handler, interface is defined by PEAR package.
*/
$this->tokens[] = new HTMLPurifier_Token_End($name);
return true;
}
-
+
/**
* Data event handler, interface is defined by PEAR package.
*/
$this->tokens[] = new HTMLPurifier_Token_Text($data);
return true;
}
-
+
/**
* Escaped text handler, interface is defined by PEAR package.
*/
//}
return true;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_PercentEncoder
{
-
+
/**
* Reserved characters to preserve when using encode().
*/
protected $preserve = array();
-
+
/**
* String of characters that should be preserved while using encode().
*/
$this->preserve[46] = true; // Period .
$this->preserve[95] = true; // Underscore _
$this->preserve[126]= true; // Tilde ~
-
+
// extra letters not to escape
if ($preserve !== false) {
for ($i = 0, $c = strlen($preserve); $i < $c; $i++) {
}
}
}
-
+
/**
* Our replacement for urlencode, it encodes all non-reserved characters,
* as well as any extra characters that were instructed to be preserved.
}
return $ret;
}
-
+
/**
* Fix up percent-encoding by decoding unreserved characters and normalizing.
* @warning This function is affected by $preserve, even though the
}
return $ret;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_Printer
{
-
+
/**
* Instance of HTMLPurifier_Generator for HTML generation convenience funcs
*/
protected $generator;
-
+
/**
* Instance of HTMLPurifier_Config, for easy access
*/
protected $config;
-
+
/**
* Initialize $generator.
*/
public function __construct() {
}
-
+
/**
* Give generator necessary configuration if possible
*/
$context = new HTMLPurifier_Context();
$this->generator = new HTMLPurifier_Generator($config, $context);
}
-
+
/**
* Main function that renders object or aspect of that object
* @note Parameters vary depending on printer
*/
// function render() {}
-
+
/**
* Returns a start tag
* @param $tag Tag name
new HTMLPurifier_Token_Start($tag, $attr ? $attr : array())
);
}
-
+
/**
* Returns an end teg
* @param $tag Tag name
new HTMLPurifier_Token_End($tag)
);
}
-
+
/**
* Prints a complete element with content inside
* @param $tag Tag name
($escape ? $this->escape($contents) : $contents) .
$this->end($tag);
}
-
+
protected function elementEmpty($tag, $attr = array()) {
return $this->generator->generateFromToken(
new HTMLPurifier_Token_Empty($tag, $attr)
);
}
-
+
protected function text($text) {
return $this->generator->generateFromToken(
new HTMLPurifier_Token_Text($text)
);
}
-
+
/**
* Prints a simple key/value row in a table.
* @param $name Key
$this->end('tr')
;
}
-
+
/**
* Escapes a string for HTML output.
* @param $string String to escape
$string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
return $string;
}
-
+
/**
* Takes a list of strings and turns them into a single list
* @param $array List of strings
}
return $ret;
}
-
+
/**
* Retrieves the class of an object without prefixes, as well as metadata
* @param $obj Object to determine class of
$class .= $this->getClass($obj->single, $sec_prefix) . ', ';
$class .= $obj->max;
break;
+ case 'css_denyelementdecorator':
+ $class .= $this->getClass($obj->def, $sec_prefix) . ', ';
+ $class .= $obj->element;
+ break;
+ case 'css_importantdecorator':
+ $class .= $this->getClass($obj->def, $sec_prefix);
+ if ($obj->allow) $class .= ', !important';
+ break;
}
$class .= ')';
return $class;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_Printer_CSSDefinition extends HTMLPurifier_Printer
{
-
+
protected $def;
-
+
public function render($config) {
$this->def = $config->getCSSDefinition();
$ret = '';
-
+
$ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));
$ret .= $this->start('table');
-
+
$ret .= $this->element('caption', 'Properties ($info)');
-
+
$ret .= $this->start('thead');
$ret .= $this->start('tr');
$ret .= $this->element('th', 'Property', array('class' => 'heavy'));
$ret .= $this->element('th', 'Definition', array('class' => 'heavy', 'style' => 'width:auto;'));
$ret .= $this->end('tr');
$ret .= $this->end('thead');
-
+
ksort($this->def->info);
foreach ($this->def->info as $property => $obj) {
$name = $this->getClass($obj, 'AttrDef_');
$ret .= $this->row($property, $name);
}
-
+
$ret .= $this->end('table');
$ret .= $this->end('div');
-
+
return $ret;
}
-
+
}
+// vim: et sw=4 sts=4
.hp-config .namespace th {text-align:center;}
.hp-config .verbose {display:none;}
.hp-config .controls {text-align:center;}
+
+/* vim: et sw=4 sts=4 */
function toggleWriteability(id_of_patient, checked) {
document.getElementById(id_of_patient).disabled = checked;
-}
\ No newline at end of file
+}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer
{
-
+
/**
* Printers for specific fields
*/
protected $fields = array();
-
+
/**
* Documentation URL, can have fragment tagged on end
*/
protected $docURL;
-
+
/**
* Name of form element to stuff config in
*/
protected $name;
-
+
/**
* Whether or not to compress directive names, clipping them off
* after a certain amount of letters. False to disable or integer letters
* before clipping.
*/
protected $compress = false;
-
+
/**
* @param $name Form element name for directives to be stuffed into
* @param $doc_url String documentation URL, will have fragment tagged on
$this->fields[0] = new HTMLPurifier_Printer_ConfigForm_default();
$this->fields[HTMLPurifier_VarParser::BOOL] = new HTMLPurifier_Printer_ConfigForm_bool();
}
-
+
/**
* Sets default column and row size for textareas in sub-printers
* @param $cols Integer columns of textarea, null to use default
if ($cols) $this->fields['default']->cols = $cols;
if ($rows) $this->fields['default']->rows = $rows;
}
-
+
/**
* Retrieves styling, in case it is not accessible by webserver
*/
public static function getCSS() {
return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css');
}
-
+
/**
* Retrieves JavaScript, in case it is not accessible by webserver
*/
public static function getJavaScript() {
return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js');
}
-
+
/**
* Returns HTML output for a configuration form
* @param $config Configuration object of current form state, or an array
} else {
$gen_config = $config;
}
-
+
$this->config = $config;
$this->genConfig = $gen_config;
$this->prepareGenerator($gen_config);
-
+
$allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def);
$all = array();
foreach ($allowed as $key) {
list($ns, $directive) = $key;
$all[$ns][$directive] = $config->get($ns, $directive);
}
-
+
$ret = '';
$ret .= $this->start('table', array('class' => 'hp-config'));
$ret .= $this->start('thead');
$ret .= $this->end('table');
return $ret;
}
-
+
/**
* Renders a single namespace
* @param $ns String namespace name
$ret .= $this->start('a', array('href' => $url));
}
$attr = array('for' => "{$this->name}:$ns.$directive");
-
+
// crop directive name if it's too long
if (!$this->compress || (strlen($directive) < $this->compress)) {
$directive_disp = $directive;
$directive_disp = substr($directive, 0, $this->compress - 2) . '...';
$attr['title'] = $directive;
}
-
+
$ret .= $this->element(
'label',
$directive_disp,
);
if ($this->docURL) $ret .= $this->end('a');
$ret .= $this->end('th');
-
+
$ret .= $this->start('td');
$def = $this->config->def->info[$ns][$directive];
if (is_int($def)) {
$ret .= $this->end('tbody');
return $ret;
}
-
+
}
/**
$gen_config = $config;
}
$this->prepareGenerator($gen_config);
-
+
$ret = '';
$ret .= $this->start('label', array('for' => "$name:Null_$ns.$directive"));
$ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
$this->prepareGenerator($gen_config);
$ret = '';
$ret .= $this->start('div', array('id' => "$name:$ns.$directive"));
-
+
$ret .= $this->start('label', array('for' => "$name:Yes_$ns.$directive"));
$ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
$ret .= $this->text(' Yes');
$ret .= $this->end('label');
-
+
$attr = array(
'type' => 'radio',
'name' => "$name"."[$ns.$directive]",
if ($value === true) $attr['checked'] = 'checked';
if ($value === null) $attr['disabled'] = 'disabled';
$ret .= $this->elementEmpty('input', $attr);
-
+
$ret .= $this->start('label', array('for' => "$name:No_$ns.$directive"));
$ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose'));
$ret .= $this->text(' No');
$ret .= $this->end('label');
-
+
$attr = array(
'type' => 'radio',
'name' => "$name"."[$ns.$directive]",
if ($value === false) $attr['checked'] = 'checked';
if ($value === null) $attr['disabled'] = 'disabled';
$ret .= $this->elementEmpty('input', $attr);
-
+
$ret .= $this->end('div');
-
+
return $ret;
}
}
+// vim: et sw=4 sts=4
class HTMLPurifier_Printer_HTMLDefinition extends HTMLPurifier_Printer
{
-
+
/**
* Instance of HTMLPurifier_HTMLDefinition, for easy access
*/
protected $def;
-
+
public function render($config) {
$ret = '';
$this->config =& $config;
-
+
$this->def = $config->getHTMLDefinition();
-
+
$ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer'));
-
+
$ret .= $this->renderDoctype();
$ret .= $this->renderEnvironment();
$ret .= $this->renderContentSets();
$ret .= $this->renderInfo();
-
+
$ret .= $this->end('div');
-
+
return $ret;
}
-
+
/**
* Renders the Doctype table
*/
$ret .= $this->end('table');
return $ret;
}
-
-
+
+
/**
* Renders environment table, which is miscellaneous info
*/
protected function renderEnvironment() {
$def = $this->def;
-
+
$ret = '';
-
+
$ret .= $this->start('table');
$ret .= $this->element('caption', 'Environment');
-
+
$ret .= $this->row('Parent of fragment', $def->info_parent);
$ret .= $this->renderChildren($def->info_parent_def->child);
$ret .= $this->row('Block wrap name', $def->info_block_wrapper);
-
+
$ret .= $this->start('tr');
$ret .= $this->element('th', 'Global attributes');
$ret .= $this->element('td', $this->listifyAttr($def->info_global_attr),0,0);
$ret .= $this->end('tr');
-
+
$ret .= $this->start('tr');
$ret .= $this->element('th', 'Tag transforms');
$list = array();
}
$ret .= $this->element('td', $this->listify($list));
$ret .= $this->end('tr');
-
+
$ret .= $this->start('tr');
$ret .= $this->element('th', 'Pre-AttrTransform');
$ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_pre));
$ret .= $this->end('tr');
-
+
$ret .= $this->start('tr');
$ret .= $this->element('th', 'Post-AttrTransform');
$ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_post));
$ret .= $this->end('tr');
-
+
$ret .= $this->end('table');
return $ret;
}
-
+
/**
* Renders the Content Sets table
*/
$ret .= $this->end('table');
return $ret;
}
-
+
/**
* Renders the Elements ($info) table
*/
$ret .= $this->element('th', 'Allowed attributes');
$ret .= $this->element('td',$this->listifyAttr($def->attr), array(), 0);
$ret .= $this->end('tr');
-
+
if (!empty($def->required_attr)) {
$ret .= $this->row('Required attributes', $this->listify($def->required_attr));
}
-
+
$ret .= $this->renderChildren($def->child);
}
$ret .= $this->end('table');
return $ret;
}
-
- /**
+
+ /**
* Renders a row describing the allowed children of an element
* @param $def HTMLPurifier_ChildDef of pertinent element
*/
'tfoot', 'tbody', 'tr'));
}
$ret .= $this->element('th', 'Allowed children', $attr);
-
+
if ($def->type == 'chameleon') {
-
+
$ret .= $this->element('td',
'<em>Block</em>: ' .
$this->escape($this->listifyTagLookup($def->block->elements)),0,0);
$ret .= $this->element('td',
'<em>Inline</em>: ' .
$this->escape($this->listifyTagLookup($def->inline->elements)),0,0);
-
+
} elseif ($def->type == 'custom') {
-
+
$ret .= $this->element('td', '<em>'.ucfirst($def->type).'</em>: ' .
$def->dtd_regex);
-
+
} else {
$ret .= $this->element('td',
'<em>'.ucfirst($def->type).'</em>: ' .
$ret .= $this->end('tr');
return $ret;
}
-
- /**
+
+ /**
* Listifies a tag lookup table.
* @param $array Tag lookup array in form of array('tagname' => true)
*/
}
return $this->listify($list);
}
-
+
/**
* Listifies a list of objects by retrieving class names and internal state
* @param $array List of objects
}
return $this->listify($list);
}
-
+
/**
* Listifies a hash of attributes to AttrDef classes
* @param $array Array hash in form of array('attrname' => HTMLPurifier_AttrDef)
}
return $this->listify($list);
}
-
+
/**
* Creates a heavy header row
*/
$ret .= $this->end('tr');
return $ret;
}
-
+
}
+// vim: et sw=4 sts=4
--- /dev/null
+<?php
+
+/**
+ * Generic property list implementation
+ */
+class HTMLPurifier_PropertyList
+{
+ /**
+ * Internal data-structure for properties
+ */
+ protected $data = array();
+
+ /**
+ * Parent plist
+ */
+ protected $parent;
+
+ protected $cache;
+
+ public function __construct($parent = null) {
+ $this->parent = $parent;
+ }
+
+ /**
+ * Recursively retrieves the value for a key
+ */
+ public function get($name) {
+ if ($this->has($name)) return $this->data[$name];
+ // possible performance bottleneck, convert to iterative if necessary
+ if ($this->parent) return $this->parent->get($name);
+ throw new HTMLPurifier_Exception("Key '$name' not found");
+ }
+
+ /**
+ * Sets the value of a key, for this plist
+ */
+ public function set($name, $value) {
+ $this->data[$name] = $value;
+ }
+
+ /**
+ * Returns true if a given key exists
+ */
+ public function has($name) {
+ return array_key_exists($name, $this->data);
+ }
+
+ /**
+ * Resets a value to the value of it's parent, usually the default. If
+ * no value is specified, the entire plist is reset.
+ */
+ public function reset($name = null) {
+ if ($name == null) $this->data = array();
+ else unset($this->data[$name]);
+ }
+
+ /**
+ * Squashes this property list and all of its property lists into a single
+ * array, and returns the array. This value is cached by default.
+ * @param $force If true, ignores the cache and regenerates the array.
+ */
+ public function squash($force = false) {
+ if ($this->cache !== null && !$force) return $this->cache;
+ if ($this->parent) {
+ return $this->cache = array_merge($this->parent->squash($force), $this->data);
+ } else {
+ return $this->cache = $this->data;
+ }
+ }
+
+ /**
+ * Returns the parent plist.
+ */
+ public function getParent() {
+ return $this->parent;
+ }
+
+ /**
+ * Sets the parent plist.
+ */
+ public function setParent($plist) {
+ $this->parent = $plist;
+ }
+}
+
+// vim: et sw=4 sts=4
--- /dev/null
+<?php
+
+/**
+ * Property list iterator. Do not instantiate this class directly.
+ */
+class HTMLPurifier_PropertyListIterator extends FilterIterator
+{
+
+ protected $l;
+ protected $filter;
+
+ /**
+ * @param $data Array of data to iterate over
+ * @param $filter Optional prefix to only allow values of
+ */
+ public function __construct(Iterator $iterator, $filter = null) {
+ parent::__construct($iterator);
+ $this->l = strlen($filter);
+ $this->filter = $filter;
+ }
+
+ public function accept() {
+ $key = $this->getInnerIterator()->key();
+ if( strncmp($key, $this->filter, $this->l) !== 0 ) {
+ return false;
+ }
+ return true;
+ }
+
+}
+
+// vim: et sw=4 sts=4
/**
* Supertype for classes that define a strategy for modifying/purifying tokens.
- *
- * While HTMLPurifier's core purpose is fixing HTML into something proper,
+ *
+ * While HTMLPurifier's core purpose is fixing HTML into something proper,
* strategies provide plug points for extra configuration or even extra
* features, such as custom tags, custom parsing of text, etc.
*/
-
+
abstract class HTMLPurifier_Strategy
{
-
+
/**
* Executes the strategy on the tokens.
- *
+ *
* @param $tokens Array of HTMLPurifier_Token objects to be operated on.
* @param $config Configuration options
* @returns Processed array of token objects.
*/
abstract public function execute($tokens, $config, $context);
-
+
}
+// vim: et sw=4 sts=4
*/
abstract class HTMLPurifier_Strategy_Composite extends HTMLPurifier_Strategy
{
-
+
/**
* List of strategies to run tokens through.
*/
protected $strategies = array();
-
+
abstract public function __construct();
-
+
public function execute($tokens, $config, $context) {
foreach ($this->strategies as $strategy) {
$tokens = $strategy->execute($tokens, $config, $context);
}
return $tokens;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Strategy_Core extends HTMLPurifier_Strategy_Composite
{
-
+
public function __construct() {
$this->strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements();
$this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed();
$this->strategies[] = new HTMLPurifier_Strategy_FixNesting();
$this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes();
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Takes a well formed list of tokens and fixes their nesting.
- *
+ *
* HTML elements dictate which elements are allowed to be their children,
* for example, you can't have a p tag in a span tag. Other elements have
* much more rigorous definitions: tables, for instance, require a specific
* order for their elements. There are also constraints not expressible by
* document type definitions, such as the chameleon nature of ins/del
* tags and global child exclusions.
- *
+ *
* The first major objective of this strategy is to iterate through all the
* nodes (not tokens) of the list of tokens and determine whether or not
* their children conform to the element's definition. If they do not, the
* child definition may optionally supply an amended list of elements that
* is valid or require that the entire node be deleted (and the previous
* node rescanned).
- *
+ *
* The second objective is to ensure that explicitly excluded elements of
* an element do not appear in its children. Code that accomplishes this
* task is pervasive through the strategy, though the two are distinct tasks
* and could, theoretically, be seperated (although it's not recommended).
- *
+ *
* @note Whether or not unrecognized children are silently dropped or
* translated into text depends on the child definitions.
- *
+ *
* @todo Enable nodes to be bubbled out of the structure.
*/
class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy
{
-
+
public function execute($tokens, $config, $context) {
//####################################################################//
// Pre-processing
-
+
// get a copy of the HTML definition
$definition = $config->getHTMLDefinition();
-
+
// insert implicit "parent" node, will be removed at end.
// DEFINITION CALL
$parent_name = $definition->info_parent;
array_unshift($tokens, new HTMLPurifier_Token_Start($parent_name));
$tokens[] = new HTMLPurifier_Token_End($parent_name);
-
+
// setup the context variable 'IsInline', for chameleon processing
// is 'false' when we are not inline, 'true' when it must always
// be inline, and an integer when it is inline for a certain
// branch of the document tree
$is_inline = $definition->info_parent_def->descendants_are_inline;
$context->register('IsInline', $is_inline);
-
+
// setup error collector
$e =& $context->get('ErrorCollector', true);
-
+
//####################################################################//
// Loop initialization
-
+
// stack that contains the indexes of all parents,
// $stack[count($stack)-1] being the current parent
$stack = array();
-
+
// stack that contains all elements that are excluded
- // it is organized by parent elements, similar to $stack,
+ // it is organized by parent elements, similar to $stack,
// but it is only populated when an element with exclusions is
// processed, i.e. there won't be empty exclusions.
$exclude_stack = array();
-
+
// variable that contains the start token while we are processing
// nodes. This enables error reporting to do its job
$start_token = false;
$context->register('CurrentToken', $start_token);
-
+
//####################################################################//
// Loop
-
+
// iterate through all start nodes. Determining the start node
// is complicated so it has been omitted from the loop construct
for ($i = 0, $size = count($tokens) ; $i < $size; ) {
-
+
//################################################################//
// Gather information on children
-
+
// child token accumulator
$child_tokens = array();
-
+
// scroll to the end of this node, report number, and collect
// all children
for ($j = $i, $depth = 0; ; $j++) {
}
$child_tokens[] = $tokens[$j];
}
-
+
// $i is index of start token
// $j is index of end token
-
+
$start_token = $tokens[$i]; // to make token available via CurrentToken
-
+
//################################################################//
// Gather information on parent
-
+
// calculate parent information
if ($count = count($stack)) {
$parent_index = $stack[$count-1];
} else {
// processing as if the parent were the "root" node
// unknown info, it won't be used anyway, in the future,
- // we may want to enforce one element only (this is
+ // we may want to enforce one element only (this is
// necessary for HTML Purifier to clean entire documents
$parent_index = $parent_name = $parent_def = null;
}
-
+
// calculate context
if ($is_inline === false) {
// check if conditions make it inline
$is_inline = false;
}
}
-
+
//################################################################//
// Determine whether element is explicitly excluded SGML-style
-
+
// determine whether or not element is excluded by checking all
// parent exclusions. The array should not be very large, two
// elements at most.
}
}
}
-
+
//################################################################//
// Perform child validation
-
+
if ($excluded) {
// there is an exclusion, remove the entire node
$result = false;
$def = $definition->info_parent_def;
} else {
$def = $definition->info[$tokens[$i]->name];
-
+
}
-
+
if (!empty($def->child)) {
// have DTD child def validate children
$result = $def->child->validateChildren(
// weird, no child definition, get rid of everything
$result = false;
}
-
+
// determine whether or not this element has any exclusions
$excludes = $def->excludes;
}
-
+
// $result is now a bool or array
-
+
//################################################################//
// Process result by interpreting $result
-
+
if ($result === true || $child_tokens === $result) {
// leave the node as is
-
+
// register start token as a parental node start
$stack[] = $i;
-
+
// register exclusions if there are any
if (!empty($excludes)) $exclude_stack[] = $excludes;
-
+
// move cursor to next possible start node
$i++;
-
+
} elseif($result === false) {
// remove entire node
-
+
if ($e) {
if ($excluded) {
$e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');
$e->send(E_ERROR, 'Strategy_FixNesting: Node removed');
}
}
-
+
// calculate length of inner tokens and current tokens
$length = $j - $i + 1;
-
+
// perform removal
array_splice($tokens, $i, $length);
-
+
// update size
$size -= $length;
-
+
// there is no start token to register,
// current node is now the next possible start node
// unless it turns out that we need to do a double-check
-
+
// this is a rought heuristic that covers 100% of HTML's
// cases and 99% of all other cases. A child definition
// that would be tricked by this would be something like:
$i = $parent_index;
array_pop($stack);
}
-
+
// PROJECTED OPTIMIZATION: Process all children elements before
// reprocessing parent node.
-
+
} else {
// replace node with $result
-
+
// calculate length of inner tokens
$length = $j - $i - 1;
-
+
if ($e) {
if (empty($result) && $length) {
$e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');
$e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');
}
}
-
+
// perform replacement
array_splice($tokens, $i + 1, $length, $result);
-
+
// update size
$size -= $length;
$size += count($result);
-
+
// register start token as a parental node start
$stack[] = $i;
-
+
// register exclusions if there are any
if (!empty($excludes)) $exclude_stack[] = $excludes;
-
+
// move cursor to next possible start node
$i++;
-
+
}
-
+
//################################################################//
// Scroll to next start node
-
+
// We assume, at this point, that $i is the index of the token
// that is the first possible new start point for a node.
-
+
// Test if the token indeed is a start tag, if not, move forward
// and test again.
$size = count($tokens);
}
$i++;
}
-
+
}
-
+
//####################################################################//
// Post-processing
-
+
// remove implicit parent tokens at the beginning and end
array_shift($tokens);
array_pop($tokens);
-
+
// remove context variables
$context->destroy('IsInline');
$context->destroy('CurrentToken');
-
+
//####################################################################//
// Return
-
+
return $tokens;
-
+
}
-
-}
+}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
{
-
+
/**
* Array stream of tokens being processed.
*/
protected $tokens;
-
+
/**
* Current index in $tokens.
*/
protected $t;
-
+
/**
* Current nesting of elements.
*/
protected $stack;
-
+
/**
* Injectors active in this stream processing.
*/
protected $injectors;
-
+
/**
* Current instance of HTMLPurifier_Config.
*/
protected $config;
-
+
/**
* Current instance of HTMLPurifier_Context.
*/
protected $context;
-
+
public function execute($tokens, $config, $context) {
-
+
$definition = $config->getHTMLDefinition();
-
+
// local variables
$generator = new HTMLPurifier_Generator($config, $context);
$escape_invalid_tags = $config->get('Core', 'EscapeInvalidTags');
$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'];
}
$this->injectors[] = $injector;
}
-
+
// give the injectors references to the definition and context
// variables for performance reasons
foreach ($this->injectors as $ix => $injector) {
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
// 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;
// only increment if we don't need to reprocess
$reprocess ? $reprocess = false : $t++
) {
-
+
// check for a rewind
if (is_int($i) && $i >= 0) {
// possibility: disable rewinding if the current token has a
}
$i = false;
}
-
+
// handle case of document end
if (!isset($tokens[$t])) {
// kill processing if stack is empty
if (empty($this->stack)) break;
-
+
// peek
$top_nesting = array_pop($this->stack);
$this->stack[] = $top_nesting;
-
+
// send error
if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {
$e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);
}
-
+
// append, don't splice, since this is the end
$tokens[] = new HTMLPurifier_Token_End($top_nesting->name);
-
+
// punt!
$reprocess = true;
continue;
}
-
- // if all goes well, this token will be passed through unharmed
+
$token = $tokens[$t];
-
- //echo '<hr>';
- //printTokens($tokens, $t);
- //var_dump($this->stack);
-
+
+ //echo '<br>'; printTokens($tokens, $t); printTokens($this->stack);
+
// quick-check: if it's not a tag, no need to process
if (empty($token->is_tag)) {
if ($token instanceof HTMLPurifier_Token_Text) {
// another possibility is a comment
continue;
}
-
+
if (isset($definition->info[$token->name])) {
$type = $definition->info[$token->name]->child->type;
} else {
$type = false; // Type is unknown, treat accordingly
}
-
+
// quick tag checks: anything that's *not* an end tag
$ok = false;
if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {
$ok = true;
} elseif ($token instanceof HTMLPurifier_Token_Start) {
// start tag
-
+
// ...unless they also have to close their parent
if (!empty($this->stack)) {
-
+
$parent = array_pop($this->stack);
$this->stack[] = $parent;
-
+
if (isset($definition->info[$parent->name])) {
- $elements = $definition->info[$parent->name]->child->getNonAutoCloseElements($config);
+ $elements = $definition->info[$parent->name]->child->getAllowedElements($config);
$autoclose = !isset($elements[$token->name]);
} else {
$autoclose = false;
}
-
+
+ $carryover = false;
+ if ($autoclose && $definition->info[$parent->name]->formatting) {
+ $carryover = true;
+ }
+
if ($autoclose) {
- if ($e) $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
- // insert parent end tag before this tag
+ // errors need to be updated
$new_token = new HTMLPurifier_Token_End($parent->name);
$new_token->start = $parent;
- $this->insertBefore($new_token);
+ if ($carryover) {
+ $element = clone $parent;
+ $element->armor['MakeWellFormed_TagClosedError'] = true;
+ $element->carryover = true;
+ $this->processToken(array($new_token, $token, $element));
+ } else {
+ $this->insertBefore($new_token);
+ }
+ if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) {
+ if (!$carryover) {
+ $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
+ } else {
+ $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent);
+ }
+ }
$reprocess = true;
continue;
}
-
+
}
$ok = true;
}
-
+
if ($ok) {
foreach ($this->injectors as $i => $injector) {
if (isset($token->skip[$i])) continue;
}
continue;
}
-
+
// sanity check: we should be dealing with a closing tag
if (!$token instanceof HTMLPurifier_Token_End) {
throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');
}
-
+
// make sure that we have something open
if (empty($this->stack)) {
if ($escape_invalid_tags) {
$reprocess = true;
continue;
}
-
+
// first, check for the simplest case: everything closes neatly.
// Eventually, everything passes through here; if there are problems
// we modify the input stream accordingly and then punt, so that
}
continue;
}
-
+
// okay, so we're trying to close the wrong tag
-
+
// undo the pop previous pop
$this->stack[] = $current_parent;
-
+
// scroll back the entire nest, trying to find our tag.
// (feature could be to specify how far you'd like to go)
$size = count($this->stack);
break;
}
}
-
+
// we didn't find the tag, so remove
if ($skipped_tags === false) {
if ($escape_invalid_tags) {
$reprocess = true;
continue;
}
-
+
// do errors, in REVERSE $j order: a,b,c with </a></b></c>
$c = count($skipped_tags);
if ($e) {
}
}
}
-
+
// insert tags, in FORWARD $j order: c,b,a with </a></b></c>
+ $replace = array($token);
for ($j = 1; $j < $c; $j++) {
// ...as well as from the insertions
$new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);
$new_token->start = $skipped_tags[$j];
- $this->insertBefore($new_token);
+ array_unshift($replace, $new_token);
+ if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) {
+ $element = clone $skipped_tags[$j];
+ $element->carryover = true;
+ $element->armor['MakeWellFormed_TagClosedError'] = true;
+ $replace[] = $element;
+ }
}
+ $this->processToken($replace);
$reprocess = true;
continue;
}
-
+
$context->destroy('CurrentNesting');
$context->destroy('InputTokens');
$context->destroy('InputIndex');
$context->destroy('CurrentToken');
-
+
unset($this->injectors, $this->stack, $this->tokens, $this->t);
return $tokens;
}
-
+
/**
* Processes arbitrary token values for complicated substitution patterns.
* In general:
- *
+ *
* If $token is an array, it is a list of tokens to substitute for the
* current token. These tokens then get individually processed. If there
* is a leading integer in the list, that integer determines how many
* tokens from the stream should be removed.
- *
+ *
* If $token is a regular token, it is swapped with the current token.
- *
+ *
* If $token is false, the current token is deleted.
- *
+ *
* If $token is an integer, that number of tokens (with the first token
* being the current one) will be deleted.
- *
+ *
* @param $token Token substitution value
* @param $injector Injector that performed the substitution; default is if
* this is not an injector related operation.
*/
protected function processToken($token, $injector = -1) {
-
+
// normalize forms of token
if (is_object($token)) $token = array(1, $token);
if (is_int($token)) $token = array($token);
if (!is_array($token)) throw new HTMLPurifier_Exception('Invalid token type from injector');
if (!is_int($token[0])) array_unshift($token, 1);
if ($token[0] === 0) throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');
-
+
// $token is now an array with the following form:
// array(number nodes to delete, new node 1, new node 2, ...)
-
+
$delete = array_shift($token);
$old = array_splice($this->tokens, $this->t, $delete, $token);
-
+
if ($injector > -1) {
// determine appropriate skips
$oldskip = isset($old[0]) ? $old[0]->skip : array();
$object->skip[$injector] = true;
}
}
-
+
}
-
+
/**
* Inserts a token before the current token. Cursor now points to this token
*/
private function remove() {
array_splice($this->tokens, $this->t, 1);
}
-
+
/**
* Swap current token with new token. Cursor points to new token (no change).
*/
private function swap($token) {
$this->tokens[$this->t] = $token;
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Removes all unrecognized tags from the list of tokens.
- *
+ *
* This strategy iterates through all the tokens and removes unrecognized
* tokens. If a token is not recognized but a TagTransform is defined for
* that element, the element will be transformed accordingly.
class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy
{
-
+
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');
-
+
$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) {
}
if (!empty( $token->is_tag )) {
// DEFINITION CALL
-
+
// before any processing, try to transform the element
if (
isset($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->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');
// we removed tokens until the end, throw error
$e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until);
}
-
+
$context->destroy('CurrentToken');
-
+
return $result;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy
{
-
+
public function execute($tokens, $config, $context) {
-
+
// setup validator
$validator = new HTMLPurifier_AttrValidator();
-
+
$token = false;
$context->register('CurrentToken', $token);
-
+
foreach ($tokens as $key => $token) {
-
+
// only process tokens that have attributes,
// namely start and empty tags
if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) continue;
-
+
// skip tokens that are armored
if (!empty($token->armor['ValidateAttributes'])) continue;
-
+
// note that we have no facilities here for removing tokens
$validator->validateToken($token, $config, $context);
-
+
$tokens[$key] = $token; // for PHP 4
}
$context->destroy('CurrentToken');
-
+
return $tokens;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_StringHash extends ArrayObject
{
protected $accessed = array();
-
+
/**
* Retrieves a value, and logs the access.
*/
$this->accessed[$index] = true;
return parent::offsetGet($index);
}
-
+
/**
* Returns a lookup array of all array indexes that have been accessed.
* @return Array in form array($index => true).
public function getAccessed() {
return $this->accessed;
}
-
+
/**
* Resets the access array.
*/
$this->accessed = array();
}
}
+
+// vim: et sw=4 sts=4
/**
* Parses string hash files. File format is as such:
- *
+ *
* DefaultKeyValue
* KEY: Value
* KEY2: Value2
*/
class HTMLPurifier_StringHashParser
{
-
+
public $default = 'ID';
-
+
/**
* Parses a file that contains a single string-hash.
*/
fclose($fh);
return $ret;
}
-
+
/**
* Parses a file that contains multiple string-hashes delimited by '----'
*/
fclose($fh);
return $ret;
}
-
+
/**
* Internal parser that acepts a file handle.
* @note While it's possible to simulate in-memory parsing by using
$line = rtrim($line, "\n\r");
if (!$state && $line === '') continue;
if ($line === '----') break;
- if (strncmp('--', $line, 2) === 0) {
+ if (strncmp('--#', $line, 3) === 0) {
+ // Comment
+ continue;
+ } elseif (strncmp('--', $line, 2) === 0) {
// Multiline declaration
$state = trim($line, '- ');
if (!isset($ret[$state])) $ret[$state] = '';
$single = true;
if (strpos($line, ':') !== false) {
// Single-line declaration
- list($state, $line) = explode(': ', $line, 2);
+ list($state, $line) = explode(':', $line, 2);
+ $line = trim($line);
} else {
// Use default declaration
$state = $this->default;
} while (!feof($fh));
return $ret;
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
abstract class HTMLPurifier_TagTransform
{
-
+
/**
* Tag name to transform the tag to.
*/
public $transform_to;
-
+
/**
* Transforms the obsolete tag into the valid tag.
* @param $tag Tag to be transformed.
* @param $context Mandatory HTMLPurifier_Context object
*/
abstract public function transform($tag, $config, $context);
-
+
/**
* Prepends CSS properties to the style attribute, creating the
* attribute if it doesn't exist.
$attr['style'] = isset($attr['style']) ? $attr['style'] : '';
$attr['style'] = $css . $attr['style'];
}
-
+
}
+// vim: et sw=4 sts=4
/**
* Transforms FONT tags to the proper form (SPAN with CSS styling)
- *
+ *
* This transformation takes the three proprietary attributes of FONT and
* transforms them into their corresponding CSS attributes. These are color,
* face, and size.
- *
+ *
* @note Size is an interesting case because it doesn't map cleanly to CSS.
* Thanks to
* http://style.cleverchimp.com/font_size_intervals/altintervals.html
* for reasonable mappings.
+ * @warning This doesn't work completely correctly; specifically, this
+ * TagTransform operates before well-formedness is enforced, so
+ * the "active formatting elements" algorithm doesn't get applied.
*/
class HTMLPurifier_TagTransform_Font extends HTMLPurifier_TagTransform
{
-
+
public $transform_to = 'span';
-
+
protected $_size_lookup = array(
'0' => 'xx-small',
'1' => 'xx-small',
'+3' => '200%',
'+4' => '300%'
);
-
+
public function transform($tag, $config, $context) {
-
+
if ($tag instanceof HTMLPurifier_Token_End) {
$new_tag = clone $tag;
$new_tag->name = $this->transform_to;
return $new_tag;
}
-
+
$attr = $tag->attr;
$prepend_style = '';
-
+
// handle color transform
if (isset($attr['color'])) {
$prepend_style .= 'color:' . $attr['color'] . ';';
unset($attr['color']);
}
-
+
// handle face transform
if (isset($attr['face'])) {
$prepend_style .= 'font-family:' . $attr['face'] . ';';
unset($attr['face']);
}
-
+
// handle size transform
if (isset($attr['size'])) {
// normalize large numbers
}
unset($attr['size']);
}
-
+
if ($prepend_style) {
$attr['style'] = isset($attr['style']) ?
$prepend_style . $attr['style'] :
$prepend_style;
}
-
+
$new_tag = clone $tag;
$new_tag->name = $this->transform_to;
$new_tag->attr = $attr;
-
+
return $new_tag;
-
+
}
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_TagTransform_Simple extends HTMLPurifier_TagTransform
{
-
+
protected $style;
-
+
/**
* @param $transform_to Tag name to transform to.
* @param $style CSS style to add to the tag
$this->transform_to = $transform_to;
$this->style = $style;
}
-
+
public function transform($tag, $config, $context) {
$new_tag = clone $tag;
$new_tag->name = $this->transform_to;
}
return $new_tag;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_Token {
public $line; /**< Line number node was on in source document. Null if unknown. */
public $col; /**< Column of line node was on in source document. Null if unknown. */
-
+
/**
* Lookup array of processing that this token is exempt from.
* Currently, valid values are "ValidateAttributes" and
* "MakeWellFormed_TagClosedError"
*/
public $armor = array();
-
+
/**
* Used during MakeWellFormed.
*/
public $skip;
public $rewind;
-
+ public $carryover;
+
public function __get($n) {
if ($n === 'type') {
trigger_error('Deprecated type property called; use instanceof', E_USER_NOTICE);
}
}
}
-
+
/**
* Sets the position of the token in the source document.
*/
$this->line = $l;
$this->col = $c;
}
-
+
/**
* Convenience function for DirectLex settings line/col position.
*/
$this->line = $l;
$this->col = $c;
}
-
+
}
+
+// vim: et sw=4 sts=4
class HTMLPurifier_Token_Comment extends HTMLPurifier_Token
{
public $data; /**< Character data within comment. */
+ public $is_whitespace = true;
/**
* Transparent constructor.
- *
+ *
* @param $data String comment data.
*/
public function __construct($data, $line = null, $col = null) {
}
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Token_Empty extends HTMLPurifier_Token_Tag
{
-
+
}
+
+// vim: et sw=4 sts=4
/**
* Concrete end token class.
- *
+ *
* @warning This class accepts attributes even though end tags cannot. This
* is for optimization reasons, as under normal circumstances, the Lexers
* do not pass attributes.
*/
public $start;
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_Token_Start extends HTMLPurifier_Token_Tag
{
-
+
}
+
+// vim: et sw=4 sts=4
{
/**
* Static bool marker that indicates the class is a tag.
- *
+ *
* This allows us to check objects with <tt>!empty($obj->is_tag)</tt>
* without having to use a function call <tt>is_a()</tt>.
*/
public $is_tag = true;
-
+
/**
* The lower-case name of the tag, like 'a', 'b' or 'blockquote'.
- *
+ *
* @note Strictly speaking, XML tags are case sensitive, so we shouldn't
* be lower-casing them, but these tokens cater to HTML tags, which are
* insensitive.
*/
public $name;
-
+
/**
* Associative array of the tag's attributes.
*/
public $attr = array();
-
+
/**
* Non-overloaded constructor, which lower-cases passed tag name.
- *
+ *
* @param $name String name.
* @param $attr Associative array of attributes.
*/
$this->col = $col;
}
}
+
+// vim: et sw=4 sts=4
/**
* Concrete text token class.
- *
+ *
* Text tokens comprise of regular parsed character data (PCDATA) and raw
* character data (from the CDATA sections). Internally, their
* data is parsed with all entities expanded. Surprisingly, the text token
*/
class HTMLPurifier_Token_Text extends HTMLPurifier_Token
{
-
+
public $name = '#PCDATA'; /**< PCDATA tag name compatible with DTD. */
public $data; /**< Parsed character data of text. */
public $is_whitespace; /**< Bool indicating if node is whitespace. */
-
+
/**
* Constructor, accepts data and determines if it is whitespace.
- *
+ *
* @param $data String parsed character data.
*/
public function __construct($data, $line = null, $col = null) {
$this->line = $line;
$this->col = $col;
}
-
+
}
+
+// vim: et sw=4 sts=4
/**
* Factory for token generation.
- *
+ *
* @note Doing some benchmarking indicates that the new operator is much
* slower than the clone operator (even discounting the cost of the
* constructor). This class is for that optimization.
*/
class HTMLPurifier_TokenFactory
{
-
+
/**
* Prototypes that will be cloned.
* @private
*/
// p stands for prototype
private $p_start, $p_end, $p_empty, $p_text, $p_comment;
-
+
/**
* Generates blank prototypes for cloning.
*/
$this->p_text = new HTMLPurifier_Token_Text('');
$this->p_comment= new HTMLPurifier_Token_Comment('');
}
-
+
/**
* Creates a HTMLPurifier_Token_Start.
* @param $name Tag name
$p->__construct($name, $attr);
return $p;
}
-
+
/**
* Creates a HTMLPurifier_Token_End.
* @param $name Tag name
$p->__construct($name);
return $p;
}
-
+
/**
* Creates a HTMLPurifier_Token_Empty.
* @param $name Tag name
$p->__construct($name, $attr);
return $p;
}
-
+
/**
* Creates a HTMLPurifier_Token_Text.
* @param $data Data of text token
$p->__construct($data);
return $p;
}
-
+
/**
* Creates a HTMLPurifier_Token_Comment.
* @param $data Data of comment token
$p->__construct($data);
return $p;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_URI
{
-
+
public $scheme, $userinfo, $host, $port, $path, $query, $fragment;
-
+
/**
* @note Automatically normalizes scheme and port
*/
$this->query = $query;
$this->fragment = $fragment;
}
-
+
/**
* Retrieves a scheme object corresponding to the URI's scheme/default
* @param $config Instance of HTMLPurifier_Config
}
return $scheme_obj;
}
-
+
/**
* Generic validation method applicable for all schemes. May modify
* this URI in order to get it into a compliant form.
* @return True if validation/filtering succeeds, false if failure
*/
public function validate($config, $context) {
-
+
// ABNF definitions from RFC 3986
$chars_sub_delims = '!$&\'()*+,;=';
$chars_gen_delims = ':/?#[]@';
$chars_pchar = $chars_sub_delims . ':@';
-
+
// validate scheme (MUST BE FIRST!)
if (!is_null($this->scheme) && is_null($this->host)) {
$def = $config->getDefinition('URI');
$this->scheme = null;
}
}
-
+
// validate host
if (!is_null($this->host)) {
$host_def = new HTMLPurifier_AttrDef_URI_Host();
$this->host = $host_def->validate($this->host, $config, $context);
if ($this->host === false) $this->host = null;
}
-
+
// validate username
if (!is_null($this->userinfo)) {
$encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . ':');
$this->userinfo = $encoder->encode($this->userinfo);
}
-
+
// validate port
if (!is_null($this->port)) {
if ($this->port < 1 || $this->port > 65535) $this->port = null;
}
-
+
// validate path
$path_parts = array();
$segments_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/');
$segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@');
$c = strpos($this->path, '/');
if ($c !== false) {
- $this->path =
+ $this->path =
$segment_nc_encoder->encode(substr($this->path, 0, $c)) .
$segments_encoder->encode(substr($this->path, $c));
} else {
// path-empty (hier and relative)
$this->path = ''; // just to be safe
}
-
+
// qf = query and fragment
$qf_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/?');
-
+
if (!is_null($this->query)) {
$this->query = $qf_encoder->encode($this->query);
}
-
+
if (!is_null($this->fragment)) {
$this->fragment = $qf_encoder->encode($this->fragment);
}
-
+
return true;
-
+
}
-
+
/**
* Convert URI back to string
* @return String URI appropriate for output
$authority .= $this->host;
if(!is_null($this->port)) $authority .= ':' . $this->port;
}
-
+
// reconstruct the result
$result = '';
if (!is_null($this->scheme)) $result .= $this->scheme . ':';
$result .= $this->path;
if (!is_null($this->query)) $result .= '?' . $this->query;
if (!is_null($this->fragment)) $result .= '#' . $this->fragment;
-
+
return $result;
}
-
+
}
+// vim: et sw=4 sts=4
class HTMLPurifier_URIDefinition extends HTMLPurifier_Definition
{
-
+
public $type = 'URI';
protected $filters = array();
protected $postFilters = array();
protected $registeredFilters = array();
-
+
/**
* HTMLPurifier_URI object of the base specified at %URI.Base
*/
public $base;
-
+
/**
* String host to consider "home" base, derived off of $base
*/
public $host;
-
+
/**
* Name of default scheme based on %URI.DefaultScheme and %URI.Base
*/
public $defaultScheme;
-
+
public function __construct() {
$this->registerFilter(new HTMLPurifier_URIFilter_DisableExternal());
$this->registerFilter(new HTMLPurifier_URIFilter_DisableExternalResources());
$this->registerFilter(new HTMLPurifier_URIFilter_MakeAbsolute());
$this->registerFilter(new HTMLPurifier_URIFilter_Munge());
}
-
+
public function registerFilter($filter) {
$this->registeredFilters[$filter->name] = $filter;
}
-
+
public function addFilter($filter, $config) {
$r = $filter->prepare($config);
if ($r === false) return; // null is ok, for backwards compat
$this->filters[$filter->name] = $filter;
}
}
-
+
protected function doSetup($config) {
$this->setupMemberVariables($config);
$this->setupFilters($config);
}
-
+
protected function setupFilters($config) {
foreach ($this->registeredFilters as $name => $filter) {
$conf = $config->get('URI', $name);
}
unset($this->registeredFilters);
}
-
+
protected function setupMemberVariables($config) {
$this->host = $config->get('URI', 'Host');
$base_uri = $config->get('URI', 'Base');
}
if (is_null($this->defaultScheme)) $this->defaultScheme = $config->get('URI', 'DefaultScheme');
}
-
+
public function filter(&$uri, $config, $context) {
foreach ($this->filters as $name => $f) {
$result = $f->filter($uri, $config, $context);
}
return true;
}
-
+
public function postFilter(&$uri, $config, $context) {
foreach ($this->postFilters as $name => $f) {
$result = $f->filter($uri, $config, $context);
}
return true;
}
-
+
}
+
+// vim: et sw=4 sts=4
/**
* Chainable filters for custom URI processing.
- *
+ *
* These filters can perform custom actions on a URI filter object,
* including transformation or blacklisting.
- *
+ *
* @warning This filter is called before scheme object validation occurs.
* Make sure, if you require a specific scheme object, you
* you check that it exists. This allows filters to convert
*/
abstract class HTMLPurifier_URIFilter
{
-
+
/**
* Unique identifier of filter
*/
public $name;
-
+
/**
* True if this filter should be run after scheme validation.
*/
public $post = false;
-
+
/**
* Performs initialization for the filter
*/
public function prepare($config) {return true;}
-
+
/**
* Filter a URI object
* @param $uri Reference to URI object variable
* all changes are committed directly on the URI object
*/
abstract public function filter(&$uri, $config, $context);
-
+
}
+
+// vim: et sw=4 sts=4
}
}
+// vim: et sw=4 sts=4
}
}
+// vim: et sw=4 sts=4
return true;
}
}
+
+// vim: et sw=4 sts=4
if (is_null($uri->port)) $uri->port = $this->base->port;
return true;
}
-
+
/**
* Resolve dots and double-dots in a path stack
*/
}
}
+// vim: et sw=4 sts=4
public $name = 'Munge';
public $post = true;
private $target, $parser, $doEmbed, $secretKey;
-
+
protected $replace = array();
-
+
public function prepare($config) {
$this->target = $config->get('URI', $this->name);
$this->parser = new HTMLPurifier_URIParser();
}
public function filter(&$uri, $config, $context) {
if ($context->get('EmbeddedURI', true) && !$this->doEmbed) return true;
-
+
$scheme_obj = $uri->getSchemeObj($config, $context);
if (!$scheme_obj) return true; // ignore unknown schemes, maybe another postfilter did it
if (is_null($uri->host) || empty($scheme_obj->browsable)) {
return true;
}
-
+
$this->makeReplace($uri, $config, $context);
$this->replace = array_map('rawurlencode', $this->replace);
-
+
$new_uri = strtr($this->target, $this->replace);
$new_uri = $this->parser->parse($new_uri);
- // don't redirect if the target host is the same as the
+ // don't redirect if the target host is the same as the
// starting host
if ($uri->host === $new_uri->host) return true;
$uri = $new_uri; // overwrite
return true;
}
-
+
protected function makeReplace($uri, $config, $context) {
$string = $uri->toString();
// always available
// not always available
if ($this->secretKey) $this->replace['%t'] = sha1($this->secretKey . ':' . $string);
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_URIParser
{
-
+
/**
* Instance of HTMLPurifier_PercentEncoder to do normalization with.
*/
protected $percentEncoder;
-
+
public function __construct() {
$this->percentEncoder = new HTMLPurifier_PercentEncoder();
}
-
+
/**
* Parses a URI.
* @param $uri string URI to parse
* not been validated yet and may not conform to RFC.
*/
public function parse($uri) {
-
+
$uri = $this->percentEncoder->normalize($uri);
-
+
// Regexp is as per Appendix B.
- // Note that ["<>] are an addition to the RFC's recommended
+ // Note that ["<>] are an addition to the RFC's recommended
// characters, because they represent external delimeters.
$r_URI = '!'.
'(([^:/?#"<>]+):)?'. // 2. Scheme
'(\?([^#"<>]*))?'. // 7. Query
'(#([^"<>]*))?'. // 8. Fragment
'!';
-
+
$matches = array();
$result = preg_match($r_URI, $uri, $matches);
-
+
if (!$result) return false; // *really* invalid URI
-
+
// seperate out parts
$scheme = !empty($matches[1]) ? $matches[2] : null;
$authority = !empty($matches[3]) ? $matches[4] : null;
$path = $matches[5]; // always present, can be empty
$query = !empty($matches[6]) ? $matches[7] : null;
$fragment = !empty($matches[8]) ? $matches[9] : null;
-
+
// further parse authority
if ($authority !== null) {
$r_authority = "/^((.+?)@)?(\[[^\]]+\]|[^:]*)(:(\d*))?/";
} else {
$port = $host = $userinfo = null;
}
-
+
return new HTMLPurifier_URI(
$scheme, $userinfo, $host, $port, $path, $query, $fragment);
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_URIScheme
{
-
+
/**
* Scheme's default port (integer)
*/
public $default_port = null;
-
+
/**
* Whether or not URIs of this schem are locatable by a browser
* http and ftp are accessible, while mailto and news are not.
*/
public $browsable = false;
-
+
/**
* Whether or not the URI always uses <hier_part>, resolves edge cases
* with making relative URIs absolute
*/
public $hierarchical = false;
-
+
/**
* Validates the components of a URI
* @note This implementation should be called by children if they define
if ($this->default_port == $uri->port) $uri->port = null;
return true;
}
-
+
}
+// vim: et sw=4 sts=4
* Validates ftp (File Transfer Protocol) URIs as defined by generic RFC 1738.
*/
class HTMLPurifier_URIScheme_ftp extends HTMLPurifier_URIScheme {
-
+
public $default_port = 21;
public $browsable = true; // usually
public $hierarchical = true;
-
+
public function validate(&$uri, $config, $context) {
parent::validate($uri, $config, $context);
$uri->query = null;
-
+
// typecode check
$semicolon_pos = strrpos($uri->path, ';'); // reverse
if ($semicolon_pos !== false) {
$uri->path = str_replace(';', '%3B', $uri->path);
$uri->path .= $type_ret;
}
-
+
return true;
}
-
+
}
+// vim: et sw=4 sts=4
* Validates http (HyperText Transfer Protocol) as defined by RFC 2616
*/
class HTMLPurifier_URIScheme_http extends HTMLPurifier_URIScheme {
-
+
public $default_port = 80;
public $browsable = true;
public $hierarchical = true;
-
+
public function validate(&$uri, $config, $context) {
parent::validate($uri, $config, $context);
$uri->userinfo = null;
return true;
}
-
+
}
+// vim: et sw=4 sts=4
* Validates https (Secure HTTP) according to http scheme.
*/
class HTMLPurifier_URIScheme_https extends HTMLPurifier_URIScheme_http {
-
+
public $default_port = 443;
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_URIScheme_mailto extends HTMLPurifier_URIScheme {
-
+
public $browsable = false;
-
+
public function validate(&$uri, $config, $context) {
parent::validate($uri, $config, $context);
$uri->userinfo = null;
// we need to validate path against RFC 2368's addr-spec
return true;
}
-
+
}
+// vim: et sw=4 sts=4
* Validates news (Usenet) as defined by generic RFC 1738
*/
class HTMLPurifier_URIScheme_news extends HTMLPurifier_URIScheme {
-
+
public $browsable = false;
-
+
public function validate(&$uri, $config, $context) {
parent::validate($uri, $config, $context);
$uri->userinfo = null;
// typecode check needed on path
return true;
}
-
+
}
+// vim: et sw=4 sts=4
* Validates nntp (Network News Transfer Protocol) as defined by generic RFC 1738
*/
class HTMLPurifier_URIScheme_nntp extends HTMLPurifier_URIScheme {
-
+
public $default_port = 119;
public $browsable = false;
-
+
public function validate(&$uri, $config, $context) {
parent::validate($uri, $config, $context);
$uri->userinfo = null;
$uri->query = null;
return true;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_URISchemeRegistry
{
-
+
/**
* Retrieve sole instance of the registry.
* @param $prototype Optional prototype to overload sole instance with,
}
return $instance;
}
-
+
/**
* Cache of retrieved schemes.
*/
protected $schemes = array();
-
+
/**
* Retrieves a scheme validator object
* @param $scheme String scheme name like http or mailto
public function getScheme($scheme, $config, $context) {
if (!$config) $config = HTMLPurifier_Config::createDefault();
$null = null; // for the sake of passing by reference
-
+
// important, otherwise attacker could include arbitrary file
$allowed_schemes = $config->get('URI', 'AllowedSchemes');
if (!$config->get('URI', 'OverrideAllowedSchemes') &&
) {
return $null;
}
-
+
if (isset($this->schemes[$scheme])) return $this->schemes[$scheme];
if (!isset($allowed_schemes[$scheme])) return $null;
-
+
$class = 'HTMLPurifier_URIScheme_' . $scheme;
if (!class_exists($class)) return $null;
$this->schemes[$scheme] = new $class();
return $this->schemes[$scheme];
}
-
+
/**
* Registers a custom scheme to the cache, bypassing reflection.
* @param $scheme Scheme name
public function register($scheme, $scheme_obj) {
$this->schemes[$scheme] = $scheme_obj;
}
-
-}
+}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_UnitConverter
{
-
+
const ENGLISH = 1;
const METRIC = 2;
const DIGITAL = 3;
-
+
/**
* Units information array. Units are grouped into measuring systems
* (English, Metric), and are assigned an integer representing
self::ENGLISH => array('mm', '2.83464567', 'pt'),
),
);
-
+
/**
* Minimum bcmath precision for output.
*/
protected $outputPrecision;
-
+
/**
* Bcmath precision for internal calculations.
*/
protected $internalPrecision;
-
+
/**
* Whether or not BCMath is available
*/
private $bcmath;
-
+
public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false) {
$this->outputPrecision = $output_precision;
$this->internalPrecision = $internal_precision;
$this->bcmath = !$force_no_bcmath && function_exists('bcmul');
}
-
+
/**
* Converts a length object of one unit into another unit.
* @param HTMLPurifier_Length $length
* decimals will be added on.
*/
public function convert($length, $to_unit) {
-
+
if (!$length->isValid()) return false;
-
+
$n = $length->getN();
$unit = $length->getUnit();
-
+
if ($n === '0' || $unit === false) {
return new HTMLPurifier_Length('0', false);
}
-
+
$state = $dest_state = false;
foreach (self::$units as $k => $x) {
if (isset($x[$unit])) $state = $k;
if (isset($x[$to_unit])) $dest_state = $k;
}
if (!$state || !$dest_state) return false;
-
+
// Some calculations about the initial precision of the number;
// this will be useful when we need to do final rounding.
$sigfigs = $this->getSigFigs($n);
if ($sigfigs < $this->outputPrecision) $sigfigs = $this->outputPrecision;
-
+
// BCMath's internal precision deals only with decimals. Use
// our default if the initial number has no decimals, or increase
// it by how ever many decimals, thus, the number of guard digits
// will always be greater than or equal to internalPrecision.
$log = (int) floor(log(abs($n), 10));
$cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision
-
+
for ($i = 0; $i < 2; $i++) {
-
+
// Determine what unit IN THIS SYSTEM we need to convert to
if ($dest_state === $state) {
// Simple conversion
// Convert to the smallest unit, pending a system shift
$dest_unit = self::$units[$state][$dest_state][0];
}
-
+
// Do the conversion if necessary
if ($dest_unit !== $unit) {
$factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);
$n = $this->mul($n, $factor, $cp);
$unit = $dest_unit;
}
-
+
// Output was zero, so bail out early. Shouldn't ever happen.
if ($n === '') {
$n = '0';
$unit = $to_unit;
break;
}
-
+
// It was a simple conversion, so bail out
if ($dest_state === $state) {
break;
}
-
+
if ($i !== 0) {
// Conversion failed! Apparently, the system we forwarded
// to didn't have this unit. This should never happen!
return false;
}
-
+
// Pre-condition: $i == 0
-
+
// Perform conversion to next system of units
$n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);
$unit = self::$units[$state][$dest_state][2];
$state = $dest_state;
-
+
// One more loop around to convert the unit in the new system.
-
+
}
-
+
// Post-condition: $unit == $to_unit
if ($unit !== $to_unit) return false;
-
+
// Useful for debugging:
//echo "<pre>n";
//echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n</pre>\n";
-
+
$n = $this->round($n, $sigfigs);
if (strpos($n, '.') !== false) $n = rtrim($n, '0');
$n = rtrim($n, '.');
-
+
return new HTMLPurifier_Length($n, $unit);
}
-
+
/**
* Returns the number of significant figures in a string number.
* @param string $n Decimal number
}
return $sigfigs;
}
-
+
/**
* Adds two numbers, using arbitrary precision when available.
*/
if ($this->bcmath) return bcadd($s1, $s2, $scale);
else return $this->scale($s1 + $s2, $scale);
}
-
+
/**
* Multiples two numbers, using arbitrary precision when available.
*/
if ($this->bcmath) return bcmul($s1, $s2, $scale);
else return $this->scale($s1 * $s2, $scale);
}
-
+
/**
* Divides two numbers, using arbitrary precision when available.
*/
if ($this->bcmath) return bcdiv($s1, $s2, $scale);
else return $this->scale($s1 / $s2, $scale);
}
-
+
/**
* Rounds a number according to the number of sigfigs it should have,
* using arbitrary precision when available.
return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);
}
}
-
+
/**
* Scales a float to $scale digits right of decimal point, like BCMath.
*/
}
return sprintf('%.' . $scale . 'f', (float) $r);
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_VarParser
{
-
+
const STRING = 1;
const ISTRING = 2;
const TEXT = 3;
const ALIST = 9;
const HASH = 10;
const MIXED = 11;
-
+
/**
* Lookup table of allowed types. Mainly for backwards compatibility, but
* also convenient for transforming string type names to the integer constants.
'hash' => self::HASH,
'mixed' => self::MIXED
);
-
+
/**
* Lookup table of types that are string, and can have aliases or
* allowed value lists.
self::TEXT => true,
self::ITEXT => true,
);
-
+
/**
* Validate a variable according to type. Throws
* HTMLPurifier_VarParserException if invalid.
}
$this->errorGeneric($var, $type);
}
-
+
/**
* Actually implements the parsing. Base implementation is to not
* do anything to $var. Subclasses should overload this!
protected function parseImplementation($var, $type, $allow_null) {
return $var;
}
-
+
/**
* Throws an exception.
*/
protected function error($msg) {
throw new HTMLPurifier_VarParserException($msg);
}
-
+
/**
* Throws an inconsistency exception.
* @note This should not ever be called. It would be called if we
protected function errorInconsistent($class, $type) {
throw new HTMLPurifier_Exception("Inconsistency in $class: ".HTMLPurifier_VarParser::getTypeName($type)." not implemented");
}
-
+
/**
* Generic error for if a type didn't work.
*/
$vtype = gettype($var);
$this->error("Expected type ".HTMLPurifier_VarParser::getTypeName($type).", got $vtype");
}
-
+
static public function getTypeName($type) {
static $lookup;
if (!$lookup) {
if (!isset($lookup[$type])) return 'unknown';
return $lookup[$type];
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_VarParser_Flexible extends HTMLPurifier_VarParser
{
-
+
protected function parseImplementation($var, $type, $allow_null) {
if ($allow_null && $var === null) return null;
switch ($type) {
}
$this->errorGeneric($var, $type);
}
-
+
}
+
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_VarParser_Native extends HTMLPurifier_VarParser
{
-
+
protected function parseImplementation($var, $type, $allow_null) {
return $this->evalExpression($var);
}
-
+
protected function evalExpression($expr) {
$var = null;
$result = eval("\$var = $expr;");
}
return $var;
}
-
+
}
+// vim: et sw=4 sts=4
*/
class HTMLPurifier_VarParserException extends HTMLPurifier_Exception
{
-
+
}
+
+// vim: et sw=4 sts=4
-Description of HTML Purifier v3.2.0 library import into Moodle
+Description of HTML Purifier v3.3.0 library import into Moodle
Changes:
* HMLTModule/Text.php - added <nolink>, <tex>, <lang> and <algebra> tags