Convert all to new configuration get/set format.
[htmlpurifier/bfroehle.git] / library / HTMLPurifier / Config.php
blobab925c913b9133137796f5203706624df86154cd
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) {
88 $this->plist = new HTMLPurifier_PropertyList($definition->defaultPlist);
89 $this->def = $definition; // keep a copy around for checking
90 $this->parser = new HTMLPurifier_VarParser_Flexible();
93 /**
94 * Convenience constructor that creates a config object based on a mixed var
95 * @param mixed $config Variable that defines the state of the config
96 * object. Can be: a HTMLPurifier_Config() object,
97 * an array of directives based on loadArray(),
98 * or a string filename of an ini file.
99 * @param HTMLPurifier_ConfigSchema Schema object
100 * @return Configured HTMLPurifier_Config object
102 public static function create($config, $schema = null) {
103 if ($config instanceof HTMLPurifier_Config) {
104 // pass-through
105 return $config;
107 if (!$schema) {
108 $ret = HTMLPurifier_Config::createDefault();
109 } else {
110 $ret = new HTMLPurifier_Config($schema);
112 if (is_string($config)) $ret->loadIni($config);
113 elseif (is_array($config)) $ret->loadArray($config);
114 return $ret;
118 * Convenience constructor that creates a default configuration object.
119 * @return Default HTMLPurifier_Config object.
121 public static function createDefault() {
122 $definition = HTMLPurifier_ConfigSchema::instance();
123 $config = new HTMLPurifier_Config($definition);
124 return $config;
128 * Retreives a value from the configuration.
129 * @param $namespace String namespace
130 * @param $key String key
132 public function get($key, $a = null) {
133 if ($a !== null) {
134 $this->triggerError("Using deprecated API: use \$config->get('$key.$a') instead", E_USER_WARNING);
135 $key = "$key.$a";
137 if (!$this->finalized) $this->autoFinalize ? $this->finalize() : $this->plist->squash(true);
138 if (!isset($this->def->info[$key])) {
139 // can't add % due to SimpleTest bug
140 $this->triggerError('Cannot retrieve value of undefined directive ' . htmlspecialchars($key),
141 E_USER_WARNING);
142 return;
144 if (isset($this->def->info[$key]->isAlias)) {
145 $d = $this->def->info[$key];
146 $this->triggerError('Cannot get value from aliased directive, use real name ' . $d->key,
147 E_USER_ERROR);
148 return;
150 return $this->plist->get($key);
154 * Retreives an array of directives to values from a given namespace
155 * @param $namespace String namespace
157 public function getBatch($namespace) {
158 if (!$this->finalized) $this->autoFinalize ? $this->finalize() : $this->plist->squash(true);
159 $full = $this->getAll();
160 if (!isset($full[$namespace])) {
161 $this->triggerError('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace),
162 E_USER_WARNING);
163 return;
165 return $full[$namespace];
169 * Returns a md5 signature of a segment of the configuration object
170 * that uniquely identifies that particular configuration
171 * @note Revision is handled specially and is removed from the batch
172 * before processing!
173 * @param $namespace Namespace to get serial for
175 public function getBatchSerial($namespace) {
176 if (empty($this->serials[$namespace])) {
177 $batch = $this->getBatch($namespace);
178 unset($batch['DefinitionRev']);
179 $this->serials[$namespace] = md5(serialize($batch));
181 return $this->serials[$namespace];
185 * Returns a md5 signature for the entire configuration object
186 * that uniquely identifies that particular configuration
188 public function getSerial() {
189 if (empty($this->serial)) {
190 $this->serial = md5(serialize($this->getAll()));
192 return $this->serial;
196 * Retrieves all directives, organized by namespace
198 public function getAll() {
199 if (!$this->finalized) $this->autoFinalize ? $this->finalize() : $this->plist->squash(true);
200 $ret = array();
201 foreach ($this->plist->squash() as $name => $value) {
202 list($ns, $key) = explode('.', $name, 2);
203 $ret[$ns][$key] = $value;
205 return $ret;
209 * Sets a value to configuration.
210 * @param $namespace String namespace
211 * @param $key String key
212 * @param $value Mixed value
214 public function set($key, $value, $a = null) {
215 if (strpos($key, '.') === false) {
216 $namespace = $key;
217 $directive = $value;
218 $value = $a;
219 $key = "$key.$directive";
220 $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);
221 } else {
222 list($namespace) = explode('.', $key);
224 if ($this->isFinalized('Cannot set directive after finalization')) return;
225 if (!isset($this->def->info[$key])) {
226 $this->triggerError('Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',
227 E_USER_WARNING);
228 return;
230 $def = $this->def->info[$key];
232 if (isset($def->isAlias)) {
233 if ($this->aliasMode) {
234 $this->triggerError('Double-aliases not allowed, please fix '.
235 'ConfigSchema bug with' . $key, E_USER_ERROR);
236 return;
238 $this->aliasMode = true;
239 $this->set($def->key, $value);
240 $this->aliasMode = false;
241 $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);
242 return;
245 // Raw type might be negative when using the fully optimized form
246 // of stdclass, which indicates allow_null == true
247 $rtype = is_int($def) ? $def : $def->type;
248 if ($rtype < 0) {
249 $type = -$rtype;
250 $allow_null = true;
251 } else {
252 $type = $rtype;
253 $allow_null = isset($def->allow_null);
256 try {
257 $value = $this->parser->parse($value, $type, $allow_null);
258 } catch (HTMLPurifier_VarParserException $e) {
259 $this->triggerError('Value for ' . $key . ' is of invalid type, should be ' . HTMLPurifier_VarParser::getTypeName($type), E_USER_WARNING);
260 return;
262 if (is_string($value) && is_object($def)) {
263 // resolve value alias if defined
264 if (isset($def->aliases[$value])) {
265 $value = $def->aliases[$value];
267 // check to see if the value is allowed
268 if (isset($def->allowed) && !isset($def->allowed[$value])) {
269 $this->triggerError('Value not supported, valid values are: ' .
270 $this->_listify($def->allowed), E_USER_WARNING);
271 return;
274 $this->plist->set($key, $value);
276 // reset definitions if the directives they depend on changed
277 // this is a very costly process, so it's discouraged
278 // with finalization
279 if ($namespace == 'HTML' || $namespace == 'CSS') {
280 $this->definitions[$namespace] = null;
283 $this->serials[$namespace] = false;
287 * Convenience function for error reporting
289 private function _listify($lookup) {
290 $list = array();
291 foreach ($lookup as $name => $b) $list[] = $name;
292 return implode(', ', $list);
296 * Retrieves object reference to the HTML definition.
297 * @param $raw Return a copy that has not been setup yet. Must be
298 * called before it's been setup, otherwise won't work.
300 public function getHTMLDefinition($raw = false) {
301 return $this->getDefinition('HTML', $raw);
305 * Retrieves object reference to the CSS 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 getCSSDefinition($raw = false) {
310 return $this->getDefinition('CSS', $raw);
314 * Retrieves a definition
315 * @param $type Type of definition: HTML, CSS, etc
316 * @param $raw Whether or not definition should be returned raw
318 public function getDefinition($type, $raw = false) {
319 if (!$this->finalized) $this->autoFinalize ? $this->finalize() : $this->plist->squash(true);
320 $factory = HTMLPurifier_DefinitionCacheFactory::instance();
321 $cache = $factory->create($type, $this);
322 if (!$raw) {
323 // see if we can quickly supply a definition
324 if (!empty($this->definitions[$type])) {
325 if (!$this->definitions[$type]->setup) {
326 $this->definitions[$type]->setup($this);
327 $cache->set($this->definitions[$type], $this);
329 return $this->definitions[$type];
331 // memory check missed, try cache
332 $this->definitions[$type] = $cache->get($this);
333 if ($this->definitions[$type]) {
334 // definition in cache, return it
335 return $this->definitions[$type];
337 } elseif (
338 !empty($this->definitions[$type]) &&
339 !$this->definitions[$type]->setup
341 // raw requested, raw in memory, quick return
342 return $this->definitions[$type];
344 // quick checks failed, let's create the object
345 if ($type == 'HTML') {
346 $this->definitions[$type] = new HTMLPurifier_HTMLDefinition();
347 } elseif ($type == 'CSS') {
348 $this->definitions[$type] = new HTMLPurifier_CSSDefinition();
349 } elseif ($type == 'URI') {
350 $this->definitions[$type] = new HTMLPurifier_URIDefinition();
351 } else {
352 throw new HTMLPurifier_Exception("Definition of $type type not supported");
354 // quick abort if raw
355 if ($raw) {
356 if (is_null($this->get($type . '.DefinitionID'))) {
357 // fatally error out if definition ID not set
358 throw new HTMLPurifier_Exception("Cannot retrieve raw version without specifying %$type.DefinitionID");
360 return $this->definitions[$type];
362 // set it up
363 $this->definitions[$type]->setup($this);
364 // save in cache
365 $cache->set($this->definitions[$type], $this);
366 return $this->definitions[$type];
370 * Loads configuration values from an array with the following structure:
371 * Namespace.Directive => Value
372 * @param $config_array Configuration associative array
374 public function loadArray($config_array) {
375 if ($this->isFinalized('Cannot load directives after finalization')) return;
376 foreach ($config_array as $key => $value) {
377 $key = str_replace('_', '.', $key);
378 if (strpos($key, '.') !== false) {
379 list($namespace, $directive) = explode(".", $key, 2);
380 $this->set($key, $value);
381 } else {
382 $namespace = $key;
383 $namespace_values = $value;
384 foreach ($namespace_values as $directive => $value) {
385 $this->set($namespace .'.'. $directive, $value);
392 * Returns a list of array(namespace, directive) for all directives
393 * that are allowed in a web-form context as per an allowed
394 * namespaces/directives list.
395 * @param $allowed List of allowed namespaces/directives
397 public static function getAllowedDirectivesForForm($allowed, $schema = null) {
398 if (!$schema) {
399 $schema = HTMLPurifier_ConfigSchema::instance();
401 if ($allowed !== true) {
402 if (is_string($allowed)) $allowed = array($allowed);
403 $allowed_ns = array();
404 $allowed_directives = array();
405 $blacklisted_directives = array();
406 foreach ($allowed as $ns_or_directive) {
407 if (strpos($ns_or_directive, '.') !== false) {
408 // directive
409 if ($ns_or_directive[0] == '-') {
410 $blacklisted_directives[substr($ns_or_directive, 1)] = true;
411 } else {
412 $allowed_directives[$ns_or_directive] = true;
414 } else {
415 // namespace
416 $allowed_ns[$ns_or_directive] = true;
420 $ret = array();
421 foreach ($schema->info as $key => $def) {
422 list($ns, $directive) = explode('.', $key, 2);
423 if ($allowed !== true) {
424 if (isset($blacklisted_directives["$ns.$directive"])) continue;
425 if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) continue;
427 if (isset($def->isAlias)) continue;
428 if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;
429 $ret[] = array($ns, $directive);
431 return $ret;
435 * Loads configuration values from $_GET/$_POST that were posted
436 * via ConfigForm
437 * @param $array $_GET or $_POST array to import
438 * @param $index Index/name that the config variables are in
439 * @param $allowed List of allowed namespaces/directives
440 * @param $mq_fix Boolean whether or not to enable magic quotes fix
441 * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
443 public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
444 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
445 $config = HTMLPurifier_Config::create($ret, $schema);
446 return $config;
450 * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
451 * @note Same parameters as loadArrayFromForm
453 public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) {
454 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
455 $this->loadArray($ret);
459 * Prepares an array from a form into something usable for the more
460 * strict parts of HTMLPurifier_Config
462 public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
463 if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
464 $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
466 $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
467 $ret = array();
468 foreach ($allowed as $key) {
469 list($ns, $directive) = $key;
470 $skey = "$ns.$directive";
471 if (!empty($array["Null_$skey"])) {
472 $ret[$ns][$directive] = null;
473 continue;
475 if (!isset($array[$skey])) continue;
476 $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
477 $ret[$ns][$directive] = $value;
479 return $ret;
483 * Loads configuration values from an ini file
484 * @param $filename Name of ini file
486 public function loadIni($filename) {
487 if ($this->isFinalized('Cannot load directives after finalization')) return;
488 $array = parse_ini_file($filename, true);
489 $this->loadArray($array);
493 * Checks whether or not the configuration object is finalized.
494 * @param $error String error message, or false for no error
496 public function isFinalized($error = false) {
497 if ($this->finalized && $error) {
498 $this->triggerError($error, E_USER_ERROR);
500 return $this->finalized;
504 * Finalizes configuration only if auto finalize is on and not
505 * already finalized
507 public function autoFinalize() {
508 if (!$this->finalized && $this->autoFinalize) $this->finalize();
512 * Finalizes a configuration object, prohibiting further change
514 public function finalize() {
515 $this->finalized = true;
519 * Produces a nicely formatted error message by supplying the
520 * stack frame information from two levels up and OUTSIDE of
521 * HTMLPurifier_Config.
523 protected function triggerError($msg, $no) {
524 // determine previous stack frame
525 $backtrace = debug_backtrace();
526 if ($this->chatty && isset($backtrace[1])) {
527 $frame = $backtrace[1];
528 $extra = " on line {$frame['line']} in file {$frame['file']}";
529 } else {
530 $extra = '';
532 trigger_error($msg . $extra, $no);
537 // vim: et sw=4 sts=4