Minor updates to Config and TODO items thereof.
[htmlpurifier.git] / library / HTMLPurifier / Config.php
blob5f709e68be1ac6a6f409991bb14c5768d7b3f52e
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 * Current lock; only gets to this namespace are allowed.
86 private $lock;
88 /**
89 * @param $definition HTMLPurifier_ConfigSchema that defines what directives
90 * are allowed.
92 public function __construct($definition, $parent = null) {
93 $parent = $parent ? $parent : $definition->defaultPlist;
94 $this->plist = new HTMLPurifier_PropertyList($parent);
95 $this->def = $definition; // keep a copy around for checking
96 $this->parser = new HTMLPurifier_VarParser_Flexible();
99 /**
100 * Convenience constructor that creates a config object based on a mixed var
101 * @param mixed $config Variable that defines the state of the config
102 * object. Can be: a HTMLPurifier_Config() object,
103 * an array of directives based on loadArray(),
104 * or a string filename of an ini file.
105 * @param HTMLPurifier_ConfigSchema Schema object
106 * @return Configured HTMLPurifier_Config object
108 public static function create($config, $schema = null) {
109 if ($config instanceof HTMLPurifier_Config) {
110 // pass-through
111 return $config;
113 if (!$schema) {
114 $ret = HTMLPurifier_Config::createDefault();
115 } else {
116 $ret = new HTMLPurifier_Config($schema);
118 if (is_string($config)) $ret->loadIni($config);
119 elseif (is_array($config)) $ret->loadArray($config);
120 return $ret;
124 * Creates a new config object that inherits from a previous one.
125 * @param HTMLPurifier_Config $config Configuration object to inherit
126 * from.
127 * @return HTMLPurifier_Config object with $config as its parent.
129 public static function inherit(HTMLPurifier_Config $config) {
130 return new HTMLPurifier_Config($config->def, $config->plist);
134 * Convenience constructor that creates a default configuration object.
135 * @return Default HTMLPurifier_Config object.
137 public static function createDefault() {
138 $definition = HTMLPurifier_ConfigSchema::instance();
139 $config = new HTMLPurifier_Config($definition);
140 return $config;
144 * Retreives a value from the configuration.
145 * @param $key String key
147 public function get($key, $a = null) {
148 if ($a !== null) {
149 $this->triggerError("Using deprecated API: use \$config->get('$key.$a') instead", E_USER_WARNING);
150 $key = "$key.$a";
152 if (!$this->finalized) $this->autoFinalize();
153 if (!isset($this->def->info[$key])) {
154 // can't add % due to SimpleTest bug
155 $this->triggerError('Cannot retrieve value of undefined directive ' . htmlspecialchars($key),
156 E_USER_WARNING);
157 return;
159 if (isset($this->def->info[$key]->isAlias)) {
160 $d = $this->def->info[$key];
161 $this->triggerError('Cannot get value from aliased directive, use real name ' . $d->key,
162 E_USER_ERROR);
163 return;
165 if ($this->lock) {
166 list($ns) = explode('.', $key);
167 if ($ns !== $this->lock) {
168 $this->triggerError('Cannot get value of namespace ' . $ns . ' when lock for ' . $this->lock . ' is active, this probably indicates a Definition setup method is accessing directives that are not within its namespace', E_USER_ERROR);
169 return;
172 return $this->plist->get($key);
176 * Retreives an array of directives to values from a given namespace
177 * @param $namespace String namespace
179 public function getBatch($namespace) {
180 if (!$this->finalized) $this->autoFinalize();
181 $full = $this->getAll();
182 if (!isset($full[$namespace])) {
183 $this->triggerError('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace),
184 E_USER_WARNING);
185 return;
187 return $full[$namespace];
191 * Returns a md5 signature of a segment of the configuration object
192 * that uniquely identifies that particular configuration
193 * @note Revision is handled specially and is removed from the batch
194 * before processing!
195 * @param $namespace Namespace to get serial for
197 public function getBatchSerial($namespace) {
198 if (empty($this->serials[$namespace])) {
199 $batch = $this->getBatch($namespace);
200 unset($batch['DefinitionRev']);
201 $this->serials[$namespace] = md5(serialize($batch));
203 return $this->serials[$namespace];
207 * Returns a md5 signature for the entire configuration object
208 * that uniquely identifies that particular configuration
210 public function getSerial() {
211 if (empty($this->serial)) {
212 $this->serial = md5(serialize($this->getAll()));
214 return $this->serial;
218 * Retrieves all directives, organized by namespace
220 public function getAll() {
221 if (!$this->finalized) $this->autoFinalize();
222 $ret = array();
223 foreach ($this->plist->squash() as $name => $value) {
224 list($ns, $key) = explode('.', $name, 2);
225 $ret[$ns][$key] = $value;
227 return $ret;
231 * Sets a value to configuration.
232 * @param $key String key
233 * @param $value Mixed value
235 public function set($key, $value, $a = null) {
236 if (strpos($key, '.') === false) {
237 $namespace = $key;
238 $directive = $value;
239 $value = $a;
240 $key = "$key.$directive";
241 $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);
242 } else {
243 list($namespace) = explode('.', $key);
245 if ($this->isFinalized('Cannot set directive after finalization')) return;
246 if (!isset($this->def->info[$key])) {
247 $this->triggerError('Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',
248 E_USER_WARNING);
249 return;
251 $def = $this->def->info[$key];
253 if (isset($def->isAlias)) {
254 if ($this->aliasMode) {
255 $this->triggerError('Double-aliases not allowed, please fix '.
256 'ConfigSchema bug with' . $key, E_USER_ERROR);
257 return;
259 $this->aliasMode = true;
260 $this->set($def->key, $value);
261 $this->aliasMode = false;
262 $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);
263 return;
266 // Raw type might be negative when using the fully optimized form
267 // of stdclass, which indicates allow_null == true
268 $rtype = is_int($def) ? $def : $def->type;
269 if ($rtype < 0) {
270 $type = -$rtype;
271 $allow_null = true;
272 } else {
273 $type = $rtype;
274 $allow_null = isset($def->allow_null);
277 try {
278 $value = $this->parser->parse($value, $type, $allow_null);
279 } catch (HTMLPurifier_VarParserException $e) {
280 $this->triggerError('Value for ' . $key . ' is of invalid type, should be ' . HTMLPurifier_VarParser::getTypeName($type), E_USER_WARNING);
281 return;
283 if (is_string($value) && is_object($def)) {
284 // resolve value alias if defined
285 if (isset($def->aliases[$value])) {
286 $value = $def->aliases[$value];
288 // check to see if the value is allowed
289 if (isset($def->allowed) && !isset($def->allowed[$value])) {
290 $this->triggerError('Value not supported, valid values are: ' .
291 $this->_listify($def->allowed), E_USER_WARNING);
292 return;
295 $this->plist->set($key, $value);
297 // reset definitions if the directives they depend on changed
298 // this is a very costly process, so it's discouraged
299 // with finalization
300 if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') {
301 $this->definitions[$namespace] = null;
304 $this->serials[$namespace] = false;
308 * Convenience function for error reporting
310 private function _listify($lookup) {
311 $list = array();
312 foreach ($lookup as $name => $b) $list[] = $name;
313 return implode(', ', $list);
317 * Retrieves object reference to the HTML definition.
318 * @param $raw Return a copy that has not been setup yet. Must be
319 * called before it's been setup, otherwise won't work.
321 public function getHTMLDefinition($raw = false) {
322 return $this->getDefinition('HTML', $raw);
326 * Retrieves object reference to the CSS definition
327 * @param $raw Return a copy that has not been setup yet. Must be
328 * called before it's been setup, otherwise won't work.
330 public function getCSSDefinition($raw = false) {
331 return $this->getDefinition('CSS', $raw);
335 * Retrieves a definition
336 * @param $type Type of definition: HTML, CSS, etc
337 * @param $raw Whether or not definition should be returned raw
339 public function getDefinition($type, $raw = false) {
340 if (!$this->finalized) $this->autoFinalize();
341 // temporarily suspend locks, so we can handle recursive definition calls
342 $lock = $this->lock;
343 $this->lock = null;
344 $factory = HTMLPurifier_DefinitionCacheFactory::instance();
345 $cache = $factory->create($type, $this);
346 $this->lock = $lock;
347 if (!$raw) {
348 // see if we can quickly supply a definition
349 if (!empty($this->definitions[$type])) {
350 if (!$this->definitions[$type]->setup) {
351 $this->definitions[$type]->setup($this);
352 $cache->set($this->definitions[$type], $this);
354 return $this->definitions[$type];
356 // memory check missed, try cache
357 $this->definitions[$type] = $cache->get($this);
358 if ($this->definitions[$type]) {
359 // definition in cache, return it
360 return $this->definitions[$type];
362 } elseif (
363 !empty($this->definitions[$type]) &&
364 !$this->definitions[$type]->setup
366 // raw requested, raw in memory, quick return
367 return $this->definitions[$type];
369 // quick checks failed, let's create the object
370 if ($type == 'HTML') {
371 $this->definitions[$type] = new HTMLPurifier_HTMLDefinition();
372 } elseif ($type == 'CSS') {
373 $this->definitions[$type] = new HTMLPurifier_CSSDefinition();
374 } elseif ($type == 'URI') {
375 $this->definitions[$type] = new HTMLPurifier_URIDefinition();
376 } else {
377 throw new HTMLPurifier_Exception("Definition of $type type not supported");
379 // quick abort if raw
380 if ($raw) {
381 if (is_null($this->get($type . '.DefinitionID'))) {
382 // fatally error out if definition ID not set
383 throw new HTMLPurifier_Exception("Cannot retrieve raw version without specifying %$type.DefinitionID");
385 return $this->definitions[$type];
387 // set it up
388 $this->lock = $type;
389 $this->definitions[$type]->setup($this);
390 $this->lock = null;
391 // save in cache
392 $cache->set($this->definitions[$type], $this);
393 return $this->definitions[$type];
397 * Loads configuration values from an array with the following structure:
398 * Namespace.Directive => Value
399 * @param $config_array Configuration associative array
401 public function loadArray($config_array) {
402 if ($this->isFinalized('Cannot load directives after finalization')) return;
403 foreach ($config_array as $key => $value) {
404 $key = str_replace('_', '.', $key);
405 if (strpos($key, '.') !== false) {
406 $this->set($key, $value);
407 } else {
408 $namespace = $key;
409 $namespace_values = $value;
410 foreach ($namespace_values as $directive => $value) {
411 $this->set($namespace .'.'. $directive, $value);
418 * Returns a list of array(namespace, directive) for all directives
419 * that are allowed in a web-form context as per an allowed
420 * namespaces/directives list.
421 * @param $allowed List of allowed namespaces/directives
423 public static function getAllowedDirectivesForForm($allowed, $schema = null) {
424 if (!$schema) {
425 $schema = HTMLPurifier_ConfigSchema::instance();
427 if ($allowed !== true) {
428 if (is_string($allowed)) $allowed = array($allowed);
429 $allowed_ns = array();
430 $allowed_directives = array();
431 $blacklisted_directives = array();
432 foreach ($allowed as $ns_or_directive) {
433 if (strpos($ns_or_directive, '.') !== false) {
434 // directive
435 if ($ns_or_directive[0] == '-') {
436 $blacklisted_directives[substr($ns_or_directive, 1)] = true;
437 } else {
438 $allowed_directives[$ns_or_directive] = true;
440 } else {
441 // namespace
442 $allowed_ns[$ns_or_directive] = true;
446 $ret = array();
447 foreach ($schema->info as $key => $def) {
448 list($ns, $directive) = explode('.', $key, 2);
449 if ($allowed !== true) {
450 if (isset($blacklisted_directives["$ns.$directive"])) continue;
451 if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) continue;
453 if (isset($def->isAlias)) continue;
454 if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;
455 $ret[] = array($ns, $directive);
457 return $ret;
461 * Loads configuration values from $_GET/$_POST that were posted
462 * via ConfigForm
463 * @param $array $_GET or $_POST array to import
464 * @param $index Index/name that the config variables are in
465 * @param $allowed List of allowed namespaces/directives
466 * @param $mq_fix Boolean whether or not to enable magic quotes fix
467 * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
469 public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
470 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
471 $config = HTMLPurifier_Config::create($ret, $schema);
472 return $config;
476 * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
477 * @note Same parameters as loadArrayFromForm
479 public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) {
480 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
481 $this->loadArray($ret);
485 * Prepares an array from a form into something usable for the more
486 * strict parts of HTMLPurifier_Config
488 public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
489 if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
490 $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
492 $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
493 $ret = array();
494 foreach ($allowed as $key) {
495 list($ns, $directive) = $key;
496 $skey = "$ns.$directive";
497 if (!empty($array["Null_$skey"])) {
498 $ret[$ns][$directive] = null;
499 continue;
501 if (!isset($array[$skey])) continue;
502 $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
503 $ret[$ns][$directive] = $value;
505 return $ret;
509 * Loads configuration values from an ini file
510 * @param $filename Name of ini file
512 public function loadIni($filename) {
513 if ($this->isFinalized('Cannot load directives after finalization')) return;
514 $array = parse_ini_file($filename, true);
515 $this->loadArray($array);
519 * Checks whether or not the configuration object is finalized.
520 * @param $error String error message, or false for no error
522 public function isFinalized($error = false) {
523 if ($this->finalized && $error) {
524 $this->triggerError($error, E_USER_ERROR);
526 return $this->finalized;
530 * Finalizes configuration only if auto finalize is on and not
531 * already finalized
533 public function autoFinalize() {
534 if ($this->autoFinalize) {
535 $this->finalize();
536 } else {
537 $this->plist->squash(true);
542 * Finalizes a configuration object, prohibiting further change
544 public function finalize() {
545 $this->finalized = true;
546 unset($this->parser);
550 * Produces a nicely formatted error message by supplying the
551 * stack frame information from two levels up and OUTSIDE of
552 * HTMLPurifier_Config.
554 protected function triggerError($msg, $no) {
555 // determine previous stack frame
556 $backtrace = debug_backtrace();
557 if ($this->chatty && isset($backtrace[1])) {
558 $frame = $backtrace[1];
559 $extra = " on line {$frame['line']} in file {$frame['file']}";
560 } else {
561 $extra = '';
563 trigger_error($msg . $extra, $no);
568 // vim: et sw=4 sts=4