[3.1.1] Further optimize ConfigSchema by eliminating stdclass when only type is set.
[htmlpurifier.git] / library / HTMLPurifier / Config.php
blob3f700daf087e9c7e99db7a371dbda293b4b21745
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.
8 *
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.1.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 * Two-level associative array of configuration directives
47 protected $conf;
49 /**
50 * Parser for variables
52 protected $parser;
54 /**
55 * Reference HTMLPurifier_ConfigSchema for value checking
56 * @note This is public for introspective purposes. Please don't
57 * abuse!
59 public $def;
61 /**
62 * Indexed array of definitions
64 protected $definitions;
66 /**
67 * Bool indicator whether or not config is finalized
69 protected $finalized = false;
71 /**
72 * @param $definition HTMLPurifier_ConfigSchema that defines what directives
73 * are allowed.
75 public function __construct($definition) {
76 $this->conf = $definition->defaults; // set up, copy in defaults
77 $this->def = $definition; // keep a copy around for checking
78 $this->parser = new HTMLPurifier_VarParser_Flexible();
81 /**
82 * Convenience constructor that creates a config object based on a mixed var
83 * @param mixed $config Variable that defines the state of the config
84 * object. Can be: a HTMLPurifier_Config() object,
85 * an array of directives based on loadArray(),
86 * or a string filename of an ini file.
87 * @param HTMLPurifier_ConfigSchema Schema object
88 * @return Configured HTMLPurifier_Config object
90 public static function create($config, $schema = null) {
91 if ($config instanceof HTMLPurifier_Config) {
92 // pass-through
93 return $config;
95 if (!$schema) {
96 $ret = HTMLPurifier_Config::createDefault();
97 } else {
98 $ret = new HTMLPurifier_Config($schema);
100 if (is_string($config)) $ret->loadIni($config);
101 elseif (is_array($config)) $ret->loadArray($config);
102 return $ret;
106 * Convenience constructor that creates a default configuration object.
107 * @return Default HTMLPurifier_Config object.
109 public static function createDefault() {
110 $definition = HTMLPurifier_ConfigSchema::instance();
111 $config = new HTMLPurifier_Config($definition);
112 return $config;
116 * Retreives a value from the configuration.
117 * @param $namespace String namespace
118 * @param $key String key
120 public function get($namespace, $key) {
121 if (!$this->finalized && $this->autoFinalize) $this->finalize();
122 if (!isset($this->def->info[$namespace][$key])) {
123 // can't add % due to SimpleTest bug
124 trigger_error('Cannot retrieve value of undefined directive ' . htmlspecialchars("$namespace.$key"),
125 E_USER_WARNING);
126 return;
128 if (isset($this->def->info[$namespace][$key]->isAlias)) {
129 $d = $this->def->info[$namespace][$key];
130 trigger_error('Cannot get value from aliased directive, use real name ' . $d->namespace . '.' . $d->name,
131 E_USER_ERROR);
132 return;
134 return $this->conf[$namespace][$key];
138 * Retreives an array of directives to values from a given namespace
139 * @param $namespace String namespace
141 public function getBatch($namespace) {
142 if (!$this->finalized && $this->autoFinalize) $this->finalize();
143 if (!isset($this->def->info[$namespace])) {
144 trigger_error('Cannot retrieve undefined namespace ' . htmlspecialchars($namespace),
145 E_USER_WARNING);
146 return;
148 return $this->conf[$namespace];
152 * Returns a md5 signature of a segment of the configuration object
153 * that uniquely identifies that particular configuration
154 * @note Revision is handled specially and is removed from the batch
155 * before processing!
156 * @param $namespace Namespace to get serial for
158 public function getBatchSerial($namespace) {
159 if (empty($this->serials[$namespace])) {
160 $batch = $this->getBatch($namespace);
161 unset($batch['DefinitionRev']);
162 $this->serials[$namespace] = md5(serialize($batch));
164 return $this->serials[$namespace];
168 * Returns a md5 signature for the entire configuration object
169 * that uniquely identifies that particular configuration
171 public function getSerial() {
172 if (empty($this->serial)) {
173 $this->serial = md5(serialize($this->getAll()));
175 return $this->serial;
179 * Retrieves all directives, organized by namespace
181 public function getAll() {
182 if (!$this->finalized && $this->autoFinalize) $this->finalize();
183 return $this->conf;
187 * Sets a value to configuration.
188 * @param $namespace String namespace
189 * @param $key String key
190 * @param $value Mixed value
192 public function set($namespace, $key, $value, $from_alias = false) {
193 if ($this->isFinalized('Cannot set directive after finalization')) return;
194 if (!isset($this->def->info[$namespace][$key])) {
195 trigger_error('Cannot set undefined directive ' . htmlspecialchars("$namespace.$key") . ' to value',
196 E_USER_WARNING);
197 return;
199 if (isset($this->def->info[$namespace][$key]->isAlias)) {
200 if ($from_alias) {
201 trigger_error('Double-aliases not allowed, please fix '.
202 'ConfigSchema bug with' . "$namespace.$key", E_USER_ERROR);
203 return;
205 $this->set($new_ns = $this->def->info[$namespace][$key]->namespace,
206 $new_dir = $this->def->info[$namespace][$key]->name,
207 $value, true);
208 trigger_error("$namespace.$key is an alias, preferred directive name is $new_ns.$new_dir", E_USER_NOTICE);
209 return;
211 try {
212 $value = $this->parser->parse(
213 $value,
214 $type =
215 is_int($this->def->info[$namespace][$key]) ?
216 $this->def->info[$namespace][$key] :
217 $this->def->info[$namespace][$key]->type,
218 isset($this->def->info[$namespace][$key]->allow_null)
220 } catch (HTMLPurifier_VarParserException $e) {
221 trigger_error('Value for ' . "$namespace.$key" . ' is of invalid type, should be ' . HTMLPurifier_VarParser::getTypeName($type), E_USER_WARNING);
222 return;
224 if (is_string($value)) {
225 // resolve value alias if defined
226 if (isset($this->def->info[$namespace][$key]->aliases[$value])) {
227 $value = $this->def->info[$namespace][$key]->aliases[$value];
229 if (isset($this->def->info[$namespace][$key])) {
230 // check to see if the value is allowed
231 if (isset($this->def->info[$namespace][$key]->allowed) && !isset($this->def->info[$namespace][$key]->allowed[$value])) {
232 trigger_error('Value not supported, valid values are: ' .
233 $this->_listify($this->def->info[$namespace][$key]->allowed), E_USER_WARNING);
234 return;
238 $this->conf[$namespace][$key] = $value;
240 // reset definitions if the directives they depend on changed
241 // this is a very costly process, so it's discouraged
242 // with finalization
243 if ($namespace == 'HTML' || $namespace == 'CSS') {
244 $this->definitions[$namespace] = null;
247 $this->serials[$namespace] = false;
251 * Convenience function for error reporting
253 private function _listify($lookup) {
254 $list = array();
255 foreach ($lookup as $name => $b) $list[] = $name;
256 return implode(', ', $list);
260 * Retrieves object reference to the HTML definition.
261 * @param $raw Return a copy that has not been setup yet. Must be
262 * called before it's been setup, otherwise won't work.
264 public function getHTMLDefinition($raw = false) {
265 return $this->getDefinition('HTML', $raw);
269 * Retrieves object reference to the CSS definition
270 * @param $raw Return a copy that has not been setup yet. Must be
271 * called before it's been setup, otherwise won't work.
273 public function getCSSDefinition($raw = false) {
274 return $this->getDefinition('CSS', $raw);
278 * Retrieves a definition
279 * @param $type Type of definition: HTML, CSS, etc
280 * @param $raw Whether or not definition should be returned raw
282 public function getDefinition($type, $raw = false) {
283 if (!$this->finalized && $this->autoFinalize) $this->finalize();
284 $factory = HTMLPurifier_DefinitionCacheFactory::instance();
285 $cache = $factory->create($type, $this);
286 if (!$raw) {
287 // see if we can quickly supply a definition
288 if (!empty($this->definitions[$type])) {
289 if (!$this->definitions[$type]->setup) {
290 $this->definitions[$type]->setup($this);
291 $cache->set($this->definitions[$type], $this);
293 return $this->definitions[$type];
295 // memory check missed, try cache
296 $this->definitions[$type] = $cache->get($this);
297 if ($this->definitions[$type]) {
298 // definition in cache, return it
299 return $this->definitions[$type];
301 } elseif (
302 !empty($this->definitions[$type]) &&
303 !$this->definitions[$type]->setup
305 // raw requested, raw in memory, quick return
306 return $this->definitions[$type];
308 // quick checks failed, let's create the object
309 if ($type == 'HTML') {
310 $this->definitions[$type] = new HTMLPurifier_HTMLDefinition();
311 } elseif ($type == 'CSS') {
312 $this->definitions[$type] = new HTMLPurifier_CSSDefinition();
313 } elseif ($type == 'URI') {
314 $this->definitions[$type] = new HTMLPurifier_URIDefinition();
315 } else {
316 throw new HTMLPurifier_Exception("Definition of $type type not supported");
318 // quick abort if raw
319 if ($raw) {
320 if (is_null($this->get($type, 'DefinitionID'))) {
321 // fatally error out if definition ID not set
322 throw new HTMLPurifier_Exception("Cannot retrieve raw version without specifying %$type.DefinitionID");
324 return $this->definitions[$type];
326 // set it up
327 $this->definitions[$type]->setup($this);
328 // save in cache
329 $cache->set($this->definitions[$type], $this);
330 return $this->definitions[$type];
334 * Loads configuration values from an array with the following structure:
335 * Namespace.Directive => Value
336 * @param $config_array Configuration associative array
338 public function loadArray($config_array) {
339 if ($this->isFinalized('Cannot load directives after finalization')) return;
340 foreach ($config_array as $key => $value) {
341 $key = str_replace('_', '.', $key);
342 if (strpos($key, '.') !== false) {
343 // condensed form
344 list($namespace, $directive) = explode('.', $key);
345 $this->set($namespace, $directive, $value);
346 } else {
347 $namespace = $key;
348 $namespace_values = $value;
349 foreach ($namespace_values as $directive => $value) {
350 $this->set($namespace, $directive, $value);
357 * Returns a list of array(namespace, directive) for all directives
358 * that are allowed in a web-form context as per an allowed
359 * namespaces/directives list.
360 * @param $allowed List of allowed namespaces/directives
362 public static function getAllowedDirectivesForForm($allowed, $schema = null) {
363 if (!$schema) {
364 $schema = HTMLPurifier_ConfigSchema::instance();
366 if ($allowed !== true) {
367 if (is_string($allowed)) $allowed = array($allowed);
368 $allowed_ns = array();
369 $allowed_directives = array();
370 $blacklisted_directives = array();
371 foreach ($allowed as $ns_or_directive) {
372 if (strpos($ns_or_directive, '.') !== false) {
373 // directive
374 if ($ns_or_directive[0] == '-') {
375 $blacklisted_directives[substr($ns_or_directive, 1)] = true;
376 } else {
377 $allowed_directives[$ns_or_directive] = true;
379 } else {
380 // namespace
381 $allowed_ns[$ns_or_directive] = true;
385 $ret = array();
386 foreach ($schema->info as $ns => $keypairs) {
387 foreach ($keypairs as $directive => $def) {
388 if ($allowed !== true) {
389 if (isset($blacklisted_directives["$ns.$directive"])) continue;
390 if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) continue;
392 if (isset($def->isAlias)) continue;
393 if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;
394 $ret[] = array($ns, $directive);
397 return $ret;
401 * Loads configuration values from $_GET/$_POST that were posted
402 * via ConfigForm
403 * @param $array $_GET or $_POST array to import
404 * @param $index Index/name that the config variables are in
405 * @param $allowed List of allowed namespaces/directives
406 * @param $mq_fix Boolean whether or not to enable magic quotes fix
407 * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
409 public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
410 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
411 $config = HTMLPurifier_Config::create($ret, $schema);
412 return $config;
416 * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
417 * @note Same parameters as loadArrayFromForm
419 public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) {
420 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
421 $this->loadArray($ret);
425 * Prepares an array from a form into something usable for the more
426 * strict parts of HTMLPurifier_Config
428 public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) {
429 if ($index !== false) $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
430 $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
432 $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
433 $ret = array();
434 foreach ($allowed as $key) {
435 list($ns, $directive) = $key;
436 $skey = "$ns.$directive";
437 if (!empty($array["Null_$skey"])) {
438 $ret[$ns][$directive] = null;
439 continue;
441 if (!isset($array[$skey])) continue;
442 $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
443 $ret[$ns][$directive] = $value;
445 return $ret;
449 * Loads configuration values from an ini file
450 * @param $filename Name of ini file
452 public function loadIni($filename) {
453 if ($this->isFinalized('Cannot load directives after finalization')) return;
454 $array = parse_ini_file($filename, true);
455 $this->loadArray($array);
459 * Checks whether or not the configuration object is finalized.
460 * @param $error String error message, or false for no error
462 public function isFinalized($error = false) {
463 if ($this->finalized && $error) {
464 trigger_error($error, E_USER_ERROR);
466 return $this->finalized;
470 * Finalizes configuration only if auto finalize is on and not
471 * already finalized
473 public function autoFinalize() {
474 if (!$this->finalized && $this->autoFinalize) $this->finalize();
478 * Finalizes a configuration object, prohibiting further change
480 public function finalize() {
481 $this->finalized = true;