Implement %HTML.Attr.Name.UseCDATA which relaxes name validation rules.
[htmlpurifier.git] / library / HTMLPurifier / Config.php
blobbe8bd0b86666f6046f919de29501319c66f1a194
1 <?php
3 /**
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
20 /**
21 * HTML Purifier's version
23 public $version = '3.3.0';
25 /**
26 * Bool indicator whether or not to automatically finalize
27 * the object if a read operation is done
29 public $autoFinalize = true;
31 // protected member variables
33 /**
34 * Namespace indexed array of serials for specific namespaces (see
35 * getSerial() for more info).
37 protected $serials = array();
39 /**
40 * Serial for entire configuration object
42 protected $serial;
44 /**
45 * Parser for variables
47 protected $parser;
49 /**
50 * Reference HTMLPurifier_ConfigSchema for value checking
51 * @note This is public for introspective purposes. Please don't
52 * abuse!
54 public $def;
56 /**
57 * Indexed array of definitions
59 protected $definitions;
61 /**
62 * Bool indicator whether or not config is finalized
64 protected $finalized = false;
66 /**
67 * Property list containing configuration directives.
69 protected $plist;
71 /**
72 * Whether or not a set is taking place due to an
73 * alias lookup.
75 private $aliasMode;
77 /**
78 * Set to false if you do not want line and file numbers in errors
79 * (useful when unit testing)
81 public $chatty = true;
83 /**
84 * @param $definition HTMLPurifier_ConfigSchema that defines what directives
85 * are allowed.
87 public function __construct($definition, $parent = null) {
88 $parent = $parent ? $parent : $definition->defaultPlist;
89 $this->plist = new HTMLPurifier_PropertyList($parent);
90 $this->def = $definition; // keep a copy around for checking
91 $this->parser = new HTMLPurifier_VarParser_Flexible();
94 /**
95 * Convenience constructor that creates a config object based on a mixed var
96 * @param mixed $config Variable that defines the state of the config
97 * object. Can be: a HTMLPurifier_Config() object,
98 * an array of directives based on loadArray(),
99 * or a string filename of an ini file.
100 * @param HTMLPurifier_ConfigSchema Schema object
101 * @return Configured HTMLPurifier_Config object
103 public static function create($config, $schema = null) {
104 if ($config instanceof HTMLPurifier_Config) {
105 // pass-through
106 return $config;
108 if (!$schema) {
109 $ret = HTMLPurifier_Config::createDefault();
110 } else {
111 $ret = new HTMLPurifier_Config($schema);
113 if (is_string($config)) $ret->loadIni($config);
114 elseif (is_array($config)) $ret->loadArray($config);
115 return $ret;
119 * Creates a new config object that inherits from a previous one.
120 * @param HTMLPurifier_Config $config Configuration object to inherit
121 * from.
122 * @return HTMLPurifier_Config object with $config as its parent.
124 public static function inherit(HTMLPurifier_Config $config) {
125 return new HTMLPurifier_Config($config->def, $config->plist);
129 * Convenience constructor that creates a default configuration object.
130 * @return Default HTMLPurifier_Config object.
132 public static function createDefault() {
133 $definition = HTMLPurifier_ConfigSchema::instance();
134 $config = new HTMLPurifier_Config($definition);
135 return $config;
139 * Retreives a value from the configuration.
140 * @param $key String key
142 public function get($key, $a = null) {
143 if ($a !== null) {
144 $this->triggerError("Using deprecated API: use \$config->get('$key.$a') instead", E_USER_WARNING);
145 $key = "$key.$a";
147 if (!$this->finalized) $this->autoFinalize();
148 if (!isset($this->def->info[$key])) {
149 // can't add % due to SimpleTest bug
150 $this->triggerError('Cannot retrieve value of undefined directive ' . htmlspecialchars($key),
151 E_USER_WARNING);
152 return;
154 if (isset($this->def->info[$key]->isAlias)) {
155 $d = $this->def->info[$key];
156 $this->triggerError('Cannot get value from aliased directive, use real name ' . $d->key,
157 E_USER_ERROR);
158 return;
160 return $this->plist->get($key);
164 * Retreives an array of directives to values from a given namespace
165 * @param $namespace String namespace
167 public function getBatch($namespace) {
168 if (!$this->finalized) $this->autoFinalize();
169 $full = $this->getAll();
170 if (!isset($full[$namespace])) {
171 $this->triggerError('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace),
172 E_USER_WARNING);
173 return;
175 return $full[$namespace];
179 * Returns a md5 signature of a segment of the configuration object
180 * that uniquely identifies that particular configuration
181 * @note Revision is handled specially and is removed from the batch
182 * before processing!
183 * @param $namespace Namespace to get serial for
185 public function getBatchSerial($namespace) {
186 if (empty($this->serials[$namespace])) {
187 $batch = $this->getBatch($namespace);
188 unset($batch['DefinitionRev']);
189 $this->serials[$namespace] = md5(serialize($batch));
191 return $this->serials[$namespace];
195 * Returns a md5 signature for the entire configuration object
196 * that uniquely identifies that particular configuration
198 public function getSerial() {
199 if (empty($this->serial)) {
200 $this->serial = md5(serialize($this->getAll()));
202 return $this->serial;
206 * Retrieves all directives, organized by namespace
208 public function getAll() {
209 if (!$this->finalized) $this->autoFinalize();
210 $ret = array();
211 foreach ($this->plist->squash() as $name => $value) {
212 list($ns, $key) = explode('.', $name, 2);
213 $ret[$ns][$key] = $value;
215 return $ret;
219 * Sets a value to configuration.
220 * @param $key String key
221 * @param $value Mixed value
223 public function set($key, $value, $a = null) {
224 if (strpos($key, '.') === false) {
225 $namespace = $key;
226 $directive = $value;
227 $value = $a;
228 $key = "$key.$directive";
229 $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);
230 } else {
231 list($namespace) = explode('.', $key);
233 if ($this->isFinalized('Cannot set directive after finalization')) return;
234 if (!isset($this->def->info[$key])) {
235 $this->triggerError('Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',
236 E_USER_WARNING);
237 return;
239 $def = $this->def->info[$key];
241 if (isset($def->isAlias)) {
242 if ($this->aliasMode) {
243 $this->triggerError('Double-aliases not allowed, please fix '.
244 'ConfigSchema bug with' . $key, E_USER_ERROR);
245 return;
247 $this->aliasMode = true;
248 $this->set($def->key, $value);
249 $this->aliasMode = false;
250 $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);
251 return;
254 // Raw type might be negative when using the fully optimized form
255 // of stdclass, which indicates allow_null == true
256 $rtype = is_int($def) ? $def : $def->type;
257 if ($rtype < 0) {
258 $type = -$rtype;
259 $allow_null = true;
260 } else {
261 $type = $rtype;
262 $allow_null = isset($def->allow_null);
265 try {
266 $value = $this->parser->parse($value, $type, $allow_null);
267 } catch (HTMLPurifier_VarParserException $e) {
268 $this->triggerError('Value for ' . $key . ' is of invalid type, should be ' . HTMLPurifier_VarParser::getTypeName($type), E_USER_WARNING);
269 return;
271 if (is_string($value) && is_object($def)) {
272 // resolve value alias if defined
273 if (isset($def->aliases[$value])) {
274 $value = $def->aliases[$value];
276 // check to see if the value is allowed
277 if (isset($def->allowed) && !isset($def->allowed[$value])) {
278 $this->triggerError('Value not supported, valid values are: ' .
279 $this->_listify($def->allowed), E_USER_WARNING);
280 return;
283 $this->plist->set($key, $value);
285 // reset definitions if the directives they depend on changed
286 // this is a very costly process, so it's discouraged
287 // with finalization
288 if ($namespace == 'HTML' || $namespace == 'CSS') {
289 $this->definitions[$namespace] = null;
292 $this->serials[$namespace] = false;
296 * Convenience function for error reporting
298 private function _listify($lookup) {
299 $list = array();
300 foreach ($lookup as $name => $b) $list[] = $name;
301 return implode(', ', $list);
305 * Retrieves object reference to the HTML definition.
306 * @param $raw Return a copy that has not been setup yet. Must be
307 * called before it's been setup, otherwise won't work.
309 public function getHTMLDefinition($raw = false) {
310 return $this->getDefinition('HTML', $raw);
314 * Retrieves object reference to the CSS definition
315 * @param $raw Return a copy that has not been setup yet. Must be
316 * called before it's been setup, otherwise won't work.
318 public function getCSSDefinition($raw = false) {
319 return $this->getDefinition('CSS', $raw);
323 * Retrieves a definition
324 * @param $type Type of definition: HTML, CSS, etc
325 * @param $raw Whether or not definition should be returned raw
327 public function getDefinition($type, $raw = false) {
328 if (!$this->finalized) $this->autoFinalize();
329 $factory = HTMLPurifier_DefinitionCacheFactory::instance();
330 $cache = $factory->create($type, $this);
331 if (!$raw) {
332 // see if we can quickly supply a definition
333 if (!empty($this->definitions[$type])) {
334 if (!$this->definitions[$type]->setup) {
335 $this->definitions[$type]->setup($this);
336 $cache->set($this->definitions[$type], $this);
338 return $this->definitions[$type];
340 // memory check missed, try cache
341 $this->definitions[$type] = $cache->get($this);
342 if ($this->definitions[$type]) {
343 // definition in cache, return it
344 return $this->definitions[$type];
346 } elseif (
347 !empty($this->definitions[$type]) &&
348 !$this->definitions[$type]->setup
350 // raw requested, raw in memory, quick return
351 return $this->definitions[$type];
353 // quick checks failed, let's create the object
354 if ($type == 'HTML') {
355 $this->definitions[$type] = new HTMLPurifier_HTMLDefinition();
356 } elseif ($type == 'CSS') {
357 $this->definitions[$type] = new HTMLPurifier_CSSDefinition();
358 } elseif ($type == 'URI') {
359 $this->definitions[$type] = new HTMLPurifier_URIDefinition();
360 } else {
361 throw new HTMLPurifier_Exception("Definition of $type type not supported");
363 // quick abort if raw
364 if ($raw) {
365 if (is_null($this->get($type . '.DefinitionID'))) {
366 // fatally error out if definition ID not set
367 throw new HTMLPurifier_Exception("Cannot retrieve raw version without specifying %$type.DefinitionID");
369 return $this->definitions[$type];
371 // set it up
372 $this->definitions[$type]->setup($this);
373 // save in cache
374 $cache->set($this->definitions[$type], $this);
375 return $this->definitions[$type];
379 * Loads configuration values from an array with the following structure:
380 * Namespace.Directive => Value
381 * @param $config_array Configuration associative array
383 public function loadArray($config_array) {
384 if ($this->isFinalized('Cannot load directives after finalization')) return;
385 foreach ($config_array as $key => $value) {
386 $key = str_replace('_', '.', $key);
387 if (strpos($key, '.') !== false) {
388 $this->set($key, $value);
389 } else {
390 $namespace = $key;
391 $namespace_values = $value;
392 foreach ($namespace_values as $directive => $value) {
393 $this->set($namespace .'.'. $directive, $value);
400 * Returns a list of array(namespace, directive) for all directives
401 * that are allowed in a web-form context as per an allowed
402 * namespaces/directives list.
403 * @param $allowed List of allowed namespaces/directives
405 public static function getAllowedDirectivesForForm($allowed, $schema = null) {
406 if (!$schema) {
407 $schema = HTMLPurifier_ConfigSchema::instance();
409 if ($allowed !== true) {
410 if (is_string($allowed)) $allowed = array($allowed);
411 $allowed_ns = array();
412 $allowed_directives = array();
413 $blacklisted_directives = array();
414 foreach ($allowed as $ns_or_directive) {
415 if (strpos($ns_or_directive, '.') !== false) {
416 // directive
417 if ($ns_or_directive[0] == '-') {
418 $blacklisted_directives[substr($ns_or_directive, 1)] = true;
419 } else {
420 $allowed_directives[$ns_or_directive] = true;
422 } else {
423 // namespace
424 $allowed_ns[$ns_or_directive] = true;
428 $ret = array();
429 foreach ($schema->info as $key => $def) {
430 list($ns, $directive) = explode('.', $key, 2);
431 if ($allowed !== true) {
432 if (isset($blacklisted_directives["$ns.$directive"])) continue;
433 if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) continue;
435 if (isset($def->isAlias)) continue;
436 if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;
437 $ret[] = array($ns, $directive);
439 return $ret;
443 * Loads configuration values from $_GET/$_POST that were posted
444 * via ConfigForm
445 * @param $array $_GET or $_POST array to import
446 * @param $index Index/name that the config variables are in
447 * @param $allowed List of allowed namespaces/directives
448 * @param $mq_fix Boolean whether or not to enable magic quotes fix
449 * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
451 public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
452 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
453 $config = HTMLPurifier_Config::create($ret, $schema);
454 return $config;
458 * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
459 * @note Same parameters as loadArrayFromForm
461 public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) {
462 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
463 $this->loadArray($ret);
467 * Prepares an array from a form into something usable for the more
468 * strict parts of HTMLPurifier_Config
470 public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
471 if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
472 $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
474 $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
475 $ret = array();
476 foreach ($allowed as $key) {
477 list($ns, $directive) = $key;
478 $skey = "$ns.$directive";
479 if (!empty($array["Null_$skey"])) {
480 $ret[$ns][$directive] = null;
481 continue;
483 if (!isset($array[$skey])) continue;
484 $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
485 $ret[$ns][$directive] = $value;
487 return $ret;
491 * Loads configuration values from an ini file
492 * @param $filename Name of ini file
494 public function loadIni($filename) {
495 if ($this->isFinalized('Cannot load directives after finalization')) return;
496 $array = parse_ini_file($filename, true);
497 $this->loadArray($array);
501 * Checks whether or not the configuration object is finalized.
502 * @param $error String error message, or false for no error
504 public function isFinalized($error = false) {
505 if ($this->finalized && $error) {
506 $this->triggerError($error, E_USER_ERROR);
508 return $this->finalized;
512 * Finalizes configuration only if auto finalize is on and not
513 * already finalized
515 public function autoFinalize() {
516 if ($this->autoFinalize) {
517 $this->finalize();
518 } else {
519 $this->plist->squash(true);
524 * Finalizes a configuration object, prohibiting further change
526 public function finalize() {
527 $this->finalized = true;
531 * Produces a nicely formatted error message by supplying the
532 * stack frame information from two levels up and OUTSIDE of
533 * HTMLPurifier_Config.
535 protected function triggerError($msg, $no) {
536 // determine previous stack frame
537 $backtrace = debug_backtrace();
538 if ($this->chatty && isset($backtrace[1])) {
539 $frame = $backtrace[1];
540 $extra = " on line {$frame['line']} in file {$frame['file']}";
541 } else {
542 $extra = '';
544 trigger_error($msg . $extra, $no);
549 // vim: et sw=4 sts=4