4 * Configuration object that triggers customizable behavior.
6 * @warning This class is strongly defined: that means that the class
7 * will fail if an undefined directive is retrieved or set.
9 * @note Many classes that could (although many times don't) use the
10 * configuration object make it a mandatory parameter. This is
11 * because a configuration object should always be forwarded,
12 * otherwise, you run the risk of missing a parameter and then
13 * being stumped when a configuration directive doesn't work.
15 * @todo Reconsider some of the public member variables
17 class HTMLPurifier_Config
21 * HTML Purifier's version
24 public $version = '4.10.0';
27 * Whether or not to automatically finalize
28 * the object if a read operation is done.
31 public $autoFinalize = true;
33 // protected member variables
36 * Namespace indexed array of serials for specific namespaces.
37 * @see getSerial() for more info.
40 protected $serials = array();
43 * Serial for entire configuration object.
49 * Parser for variables.
50 * @type HTMLPurifier_VarParser_Flexible
52 protected $parser = null;
55 * Reference HTMLPurifier_ConfigSchema for value checking.
56 * @type HTMLPurifier_ConfigSchema
57 * @note This is public for introspective purposes. Please don't
63 * Indexed array of definitions.
64 * @type HTMLPurifier_Definition[]
66 protected $definitions;
69 * Whether or not config is finalized.
72 protected $finalized = false;
75 * Property list containing configuration directives.
81 * Whether or not a set is taking place due to an alias lookup.
87 * Set to false if you do not want line and file numbers in errors.
88 * (useful when unit testing). This will also compress some errors
92 public $chatty = true;
95 * Current lock; only gets to this namespace are allowed.
102 * @param HTMLPurifier_ConfigSchema $definition ConfigSchema that defines
103 * what directives are allowed.
104 * @param HTMLPurifier_PropertyList $parent
106 public function __construct($definition, $parent = null)
108 $parent = $parent ?
$parent : $definition->defaultPlist
;
109 $this->plist
= new HTMLPurifier_PropertyList($parent);
110 $this->def
= $definition; // keep a copy around for checking
111 $this->parser
= new HTMLPurifier_VarParser_Flexible();
115 * Convenience constructor that creates a config object based on a mixed var
116 * @param mixed $config Variable that defines the state of the config
117 * object. Can be: a HTMLPurifier_Config() object,
118 * an array of directives based on loadArray(),
119 * or a string filename of an ini file.
120 * @param HTMLPurifier_ConfigSchema $schema Schema object
121 * @return HTMLPurifier_Config Configured object
123 public static function create($config, $schema = null)
125 if ($config instanceof HTMLPurifier_Config
) {
130 $ret = HTMLPurifier_Config
::createDefault();
132 $ret = new HTMLPurifier_Config($schema);
134 if (is_string($config)) {
135 $ret->loadIni($config);
136 } elseif (is_array($config)) $ret->loadArray($config);
141 * Creates a new config object that inherits from a previous one.
142 * @param HTMLPurifier_Config $config Configuration object to inherit from.
143 * @return HTMLPurifier_Config object with $config as its parent.
145 public static function inherit(HTMLPurifier_Config
$config)
147 return new HTMLPurifier_Config($config->def
, $config->plist
);
151 * Convenience constructor that creates a default configuration object.
152 * @return HTMLPurifier_Config default object.
154 public static function createDefault()
156 $definition = HTMLPurifier_ConfigSchema
::instance();
157 $config = new HTMLPurifier_Config($definition);
162 * Retrieves a value from the configuration.
164 * @param string $key String key
169 public function get($key, $a = null)
173 "Using deprecated API: use \$config->get('$key.$a') instead",
178 if (!$this->finalized
) {
179 $this->autoFinalize();
181 if (!isset($this->def
->info
[$key])) {
182 // can't add % due to SimpleTest bug
184 'Cannot retrieve value of undefined directive ' . htmlspecialchars($key),
189 if (isset($this->def
->info
[$key]->isAlias
)) {
190 $d = $this->def
->info
[$key];
192 'Cannot get value from aliased directive, use real name ' . $d->key
,
198 list($ns) = explode('.', $key);
199 if ($ns !== $this->lock
) {
201 'Cannot get value of namespace ' . $ns . ' when lock for ' .
203 ' is active, this probably indicates a Definition setup method ' .
204 'is accessing directives that are not within its namespace',
210 return $this->plist
->get($key);
214 * Retrieves an array of directives to values from a given namespace
216 * @param string $namespace String namespace
220 public function getBatch($namespace)
222 if (!$this->finalized
) {
223 $this->autoFinalize();
225 $full = $this->getAll();
226 if (!isset($full[$namespace])) {
228 'Cannot retrieve undefined namespace ' .
229 htmlspecialchars($namespace),
234 return $full[$namespace];
238 * Returns a SHA-1 signature of a segment of the configuration object
239 * that uniquely identifies that particular configuration
241 * @param string $namespace Namespace to get serial for
244 * @note Revision is handled specially and is removed from the batch
247 public function getBatchSerial($namespace)
249 if (empty($this->serials
[$namespace])) {
250 $batch = $this->getBatch($namespace);
251 unset($batch['DefinitionRev']);
252 $this->serials
[$namespace] = sha1(serialize($batch));
254 return $this->serials
[$namespace];
258 * Returns a SHA-1 signature for the entire configuration object
259 * that uniquely identifies that particular configuration
263 public function getSerial()
265 if (empty($this->serial
)) {
266 $this->serial
= sha1(serialize($this->getAll()));
268 return $this->serial
;
272 * Retrieves all directives, organized by namespace
274 * @warning This is a pretty inefficient function, avoid if you can
276 public function getAll()
278 if (!$this->finalized
) {
279 $this->autoFinalize();
282 foreach ($this->plist
->squash() as $name => $value) {
283 list($ns, $key) = explode('.', $name, 2);
284 $ret[$ns][$key] = $value;
290 * Sets a value to configuration.
292 * @param string $key key
293 * @param mixed $value value
296 public function set($key, $value, $a = null)
298 if (strpos($key, '.') === false) {
302 $key = "$key.$directive";
303 $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE
);
305 list($namespace) = explode('.', $key);
307 if ($this->isFinalized('Cannot set directive after finalization')) {
310 if (!isset($this->def
->info
[$key])) {
312 'Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',
317 $def = $this->def
->info
[$key];
319 if (isset($def->isAlias
)) {
320 if ($this->aliasMode
) {
322 'Double-aliases not allowed, please fix '.
323 'ConfigSchema bug with' . $key,
328 $this->aliasMode
= true;
329 $this->set($def->key
, $value);
330 $this->aliasMode
= false;
331 $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE
);
335 // Raw type might be negative when using the fully optimized form
336 // of stdClass, which indicates allow_null == true
337 $rtype = is_int($def) ?
$def : $def->type
;
343 $allow_null = isset($def->allow_null
);
347 $value = $this->parser
->parse($value, $type, $allow_null);
348 } catch (HTMLPurifier_VarParserException
$e) {
350 'Value for ' . $key . ' is of invalid type, should be ' .
351 HTMLPurifier_VarParser
::getTypeName($type),
356 if (is_string($value) && is_object($def)) {
357 // resolve value alias if defined
358 if (isset($def->aliases
[$value])) {
359 $value = $def->aliases
[$value];
361 // check to see if the value is allowed
362 if (isset($def->allowed
) && !isset($def->allowed
[$value])) {
364 'Value not supported, valid values are: ' .
365 $this->_listify($def->allowed
),
371 $this->plist
->set($key, $value);
373 // reset definitions if the directives they depend on changed
374 // this is a very costly process, so it's discouraged
376 if ($namespace == 'HTML' ||
$namespace == 'CSS' ||
$namespace == 'URI') {
377 $this->definitions
[$namespace] = null;
380 $this->serials
[$namespace] = false;
384 * Convenience function for error reporting
386 * @param array $lookup
390 private function _listify($lookup)
393 foreach ($lookup as $name => $b) {
396 return implode(', ', $list);
400 * Retrieves object reference to the HTML definition.
402 * @param bool $raw Return a copy that has not been setup yet. Must be
403 * called before it's been setup, otherwise won't work.
404 * @param bool $optimized If true, this method may return null, to
405 * indicate that a cached version of the modified
406 * definition object is available and no further edits
407 * are necessary. Consider using
408 * maybeGetRawHTMLDefinition, which is more explicitly
411 * @return HTMLPurifier_HTMLDefinition
413 public function getHTMLDefinition($raw = false, $optimized = false)
415 return $this->getDefinition('HTML', $raw, $optimized);
419 * Retrieves object reference to the CSS definition
421 * @param bool $raw Return a copy that has not been setup yet. Must be
422 * called before it's been setup, otherwise won't work.
423 * @param bool $optimized If true, this method may return null, to
424 * indicate that a cached version of the modified
425 * definition object is available and no further edits
426 * are necessary. Consider using
427 * maybeGetRawCSSDefinition, which is more explicitly
430 * @return HTMLPurifier_CSSDefinition
432 public function getCSSDefinition($raw = false, $optimized = false)
434 return $this->getDefinition('CSS', $raw, $optimized);
438 * Retrieves object reference to the URI definition
440 * @param bool $raw Return a copy that has not been setup yet. Must be
441 * called before it's been setup, otherwise won't work.
442 * @param bool $optimized If true, this method may return null, to
443 * indicate that a cached version of the modified
444 * definition object is available and no further edits
445 * are necessary. Consider using
446 * maybeGetRawURIDefinition, which is more explicitly
449 * @return HTMLPurifier_URIDefinition
451 public function getURIDefinition($raw = false, $optimized = false)
453 return $this->getDefinition('URI', $raw, $optimized);
457 * Retrieves a definition
459 * @param string $type Type of definition: HTML, CSS, etc
460 * @param bool $raw Whether or not definition should be returned raw
461 * @param bool $optimized Only has an effect when $raw is true. Whether
462 * or not to return null if the result is already present in
463 * the cache. This is off by default for backwards
464 * compatibility reasons, but you need to do things this
465 * way in order to ensure that caching is done properly.
466 * Check out enduser-customize.html for more details.
467 * We probably won't ever change this default, as much as the
468 * maybe semantics is the "right thing to do."
470 * @throws HTMLPurifier_Exception
471 * @return HTMLPurifier_Definition
473 public function getDefinition($type, $raw = false, $optimized = false)
475 if ($optimized && !$raw) {
476 throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false");
478 if (!$this->finalized
) {
479 $this->autoFinalize();
481 // temporarily suspend locks, so we can handle recursive definition calls
484 $factory = HTMLPurifier_DefinitionCacheFactory
::instance();
485 $cache = $factory->create($type, $this);
490 // check if definition is in memory
491 if (!empty($this->definitions
[$type])) {
492 $def = $this->definitions
[$type];
493 // check if the definition is setup
498 if ($def->optimized
) {
499 $cache->add($def, $this);
504 // check if definition is in cache
505 $def = $cache->get($this);
507 // definition in cache, save to memory and return it
508 $this->definitions
[$type] = $def;
512 $def = $this->initDefinition($type);
518 $cache->add($def, $this);
524 // check preconditions
527 if (is_null($this->get($type . '.DefinitionID'))) {
528 // fatally error out if definition ID not set
529 throw new HTMLPurifier_Exception(
530 "Cannot retrieve raw version without specifying %$type.DefinitionID"
534 if (!empty($this->definitions
[$type])) {
535 $def = $this->definitions
[$type];
536 if ($def->setup
&& !$optimized) {
537 $extra = $this->chatty ?
538 " (try moving this code block earlier in your initialization)" :
540 throw new HTMLPurifier_Exception(
541 "Cannot retrieve raw definition after it has already been setup" .
545 if ($def->optimized
=== null) {
546 $extra = $this->chatty ?
" (try flushing your cache)" : "";
547 throw new HTMLPurifier_Exception(
548 "Optimization status of definition is unknown" . $extra
551 if ($def->optimized
!== $optimized) {
552 $msg = $optimized ?
"optimized" : "unoptimized";
553 $extra = $this->chatty ?
554 " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)"
556 throw new HTMLPurifier_Exception(
557 "Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra
561 // check if definition was in memory
564 // invariant: $optimized === true (checked above)
570 // if optimized, check if definition was in cache
571 // (because we do the memory check first, this formulation
572 // is prone to cache slamming, but I think
573 // guaranteeing that either /all/ of the raw
574 // setup code or /none/ of it is run is more important.)
576 // This code path only gets run once; once we put
577 // something in $definitions (which is guaranteed by the
578 // trailing code), we always short-circuit above.
579 $def = $cache->get($this);
581 // save the full definition for later, but don't
583 $this->definitions
[$type] = $def;
587 // check invariants for creation
589 if (!is_null($this->get($type . '.DefinitionID'))) {
592 'Due to a documentation error in previous version of HTML Purifier, your ' .
593 'definitions are not being cached. If this is OK, you can remove the ' .
594 '%$type.DefinitionRev and %$type.DefinitionID declaration. Otherwise, ' .
595 'modify your code to use maybeGetRawDefinition, and test if the returned ' .
596 'value is null before making any edits (if it is null, that means that a ' .
597 'cached version is available, and no raw operations are necessary). See ' .
598 '<a href="http://htmlpurifier.org/docs/enduser-customize.html#optimized">' .
599 'Customize</a> for more details',
604 "Useless DefinitionID declaration",
611 $def = $this->initDefinition($type);
612 $def->optimized
= $optimized;
615 throw new HTMLPurifier_Exception("The impossible happened!");
619 * Initialise definition
621 * @param string $type What type of definition to create
623 * @return HTMLPurifier_CSSDefinition|HTMLPurifier_HTMLDefinition|HTMLPurifier_URIDefinition
624 * @throws HTMLPurifier_Exception
626 private function initDefinition($type)
628 // quick checks failed, let's create the object
629 if ($type == 'HTML') {
630 $def = new HTMLPurifier_HTMLDefinition();
631 } elseif ($type == 'CSS') {
632 $def = new HTMLPurifier_CSSDefinition();
633 } elseif ($type == 'URI') {
634 $def = new HTMLPurifier_URIDefinition();
636 throw new HTMLPurifier_Exception(
637 "Definition of $type type not supported"
640 $this->definitions
[$type] = $def;
644 public function maybeGetRawDefinition($name)
646 return $this->getDefinition($name, true, true);
650 * @return HTMLPurifier_HTMLDefinition
652 public function maybeGetRawHTMLDefinition()
654 return $this->getDefinition('HTML', true, true);
658 * @return HTMLPurifier_CSSDefinition
660 public function maybeGetRawCSSDefinition()
662 return $this->getDefinition('CSS', true, true);
666 * @return HTMLPurifier_URIDefinition
668 public function maybeGetRawURIDefinition()
670 return $this->getDefinition('URI', true, true);
674 * Loads configuration values from an array with the following structure:
675 * Namespace.Directive => Value
677 * @param array $config_array Configuration associative array
679 public function loadArray($config_array)
681 if ($this->isFinalized('Cannot load directives after finalization')) {
684 foreach ($config_array as $key => $value) {
685 $key = str_replace('_', '.', $key);
686 if (strpos($key, '.') !== false) {
687 $this->set($key, $value);
690 $namespace_values = $value;
691 foreach ($namespace_values as $directive => $value2) {
692 $this->set($namespace .'.'. $directive, $value2);
699 * Returns a list of array(namespace, directive) for all directives
700 * that are allowed in a web-form context as per an allowed
701 * namespaces/directives list.
703 * @param array $allowed List of allowed namespaces/directives
704 * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy
708 public static function getAllowedDirectivesForForm($allowed, $schema = null)
711 $schema = HTMLPurifier_ConfigSchema
::instance();
713 if ($allowed !== true) {
714 if (is_string($allowed)) {
715 $allowed = array($allowed);
717 $allowed_ns = array();
718 $allowed_directives = array();
719 $blacklisted_directives = array();
720 foreach ($allowed as $ns_or_directive) {
721 if (strpos($ns_or_directive, '.') !== false) {
723 if ($ns_or_directive[0] == '-') {
724 $blacklisted_directives[substr($ns_or_directive, 1)] = true;
726 $allowed_directives[$ns_or_directive] = true;
730 $allowed_ns[$ns_or_directive] = true;
735 foreach ($schema->info
as $key => $def) {
736 list($ns, $directive) = explode('.', $key, 2);
737 if ($allowed !== true) {
738 if (isset($blacklisted_directives["$ns.$directive"])) {
741 if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) {
745 if (isset($def->isAlias
)) {
748 if ($directive == 'DefinitionID' ||
$directive == 'DefinitionRev') {
751 $ret[] = array($ns, $directive);
757 * Loads configuration values from $_GET/$_POST that were posted
760 * @param array $array $_GET or $_POST array to import
761 * @param string|bool $index Index/name that the config variables are in
762 * @param array|bool $allowed List of allowed namespaces/directives
763 * @param bool $mq_fix Boolean whether or not to enable magic quotes fix
764 * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy
768 public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null)
770 $ret = HTMLPurifier_Config
::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
771 $config = HTMLPurifier_Config
::create($ret, $schema);
776 * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
778 * @param array $array $_GET or $_POST array to import
779 * @param string|bool $index Index/name that the config variables are in
780 * @param array|bool $allowed List of allowed namespaces/directives
781 * @param bool $mq_fix Boolean whether or not to enable magic quotes fix
783 public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true)
785 $ret = HTMLPurifier_Config
::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def
);
786 $this->loadArray($ret);
790 * Prepares an array from a form into something usable for the more
791 * strict parts of HTMLPurifier_Config
793 * @param array $array $_GET or $_POST array to import
794 * @param string|bool $index Index/name that the config variables are in
795 * @param array|bool $allowed List of allowed namespaces/directives
796 * @param bool $mq_fix Boolean whether or not to enable magic quotes fix
797 * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy
801 public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null)
803 if ($index !== false) {
804 $array = (isset($array[$index]) && is_array($array[$index])) ?
$array[$index] : array();
806 $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
808 $allowed = HTMLPurifier_Config
::getAllowedDirectivesForForm($allowed, $schema);
810 foreach ($allowed as $key) {
811 list($ns, $directive) = $key;
812 $skey = "$ns.$directive";
813 if (!empty($array["Null_$skey"])) {
814 $ret[$ns][$directive] = null;
817 if (!isset($array[$skey])) {
820 $value = $mq ?
stripslashes($array[$skey]) : $array[$skey];
821 $ret[$ns][$directive] = $value;
827 * Loads configuration values from an ini file
829 * @param string $filename Name of ini file
831 public function loadIni($filename)
833 if ($this->isFinalized('Cannot load directives after finalization')) {
836 $array = parse_ini_file($filename, true);
837 $this->loadArray($array);
841 * Checks whether or not the configuration object is finalized.
843 * @param string|bool $error String error message, or false for no error
847 public function isFinalized($error = false)
849 if ($this->finalized
&& $error) {
850 $this->triggerError($error, E_USER_ERROR
);
852 return $this->finalized
;
856 * Finalizes configuration only if auto finalize is on and not
859 public function autoFinalize()
861 if ($this->autoFinalize
) {
864 $this->plist
->squash(true);
869 * Finalizes a configuration object, prohibiting further change
871 public function finalize()
873 $this->finalized
= true;
874 $this->parser
= null;
878 * Produces a nicely formatted error message by supplying the
879 * stack frame information OUTSIDE of HTMLPurifier_Config.
881 * @param string $msg An error message
882 * @param int $no An error number
884 protected function triggerError($msg, $no)
886 // determine previous stack frame
889 $trace = debug_backtrace();
890 // zip(tail(trace), trace) -- but PHP is not Haskell har har
891 for ($i = 0, $c = count($trace); $i < $c - 1; $i++
) {
892 // XXX this is not correct on some versions of HTML Purifier
893 if ($trace[$i +
1]['class'] === 'HTMLPurifier_Config') {
897 $extra = " invoked on line {$frame['line']} in file {$frame['file']}";
901 trigger_error($msg . $extra, $no);
905 * Returns a serialized form of the configuration object that can
910 public function serialize()
912 $this->getDefinition('HTML');
913 $this->getDefinition('CSS');
914 $this->getDefinition('URI');
915 return serialize($this);
920 // vim: et sw=4 sts=4