[3.1.0] Emit notice if setting configuration alias, and fix up our test code not...
[htmlpurifier/rdancer.git] / library / HTMLPurifier / Config.php
blob6a282ef03d5472cbae65be23fc93dfccf9a7c026
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.0.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 ($this->def->info[$namespace][$key]->class == 'alias') {
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 ($this->def->info[$namespace][$key]->class == 'alias') {
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 = $this->def->info[$namespace][$key]->type,
215 $this->def->info[$namespace][$key]->allow_null
217 } catch (HTMLPurifier_VarParserException $e) {
218 trigger_error('Value for ' . "$namespace.$key" . ' is of invalid type, should be ' . $type, E_USER_WARNING);
219 return;
221 if (is_string($value)) {
222 // resolve value alias if defined
223 if (isset($this->def->info[$namespace][$key]->aliases[$value])) {
224 $value = $this->def->info[$namespace][$key]->aliases[$value];
226 if ($this->def->info[$namespace][$key]->allowed !== true) {
227 // check to see if the value is allowed
228 if (!isset($this->def->info[$namespace][$key]->allowed[$value])) {
229 trigger_error('Value not supported, valid values are: ' .
230 $this->_listify($this->def->info[$namespace][$key]->allowed), E_USER_WARNING);
231 return;
235 $this->conf[$namespace][$key] = $value;
237 // reset definitions if the directives they depend on changed
238 // this is a very costly process, so it's discouraged
239 // with finalization
240 if ($namespace == 'HTML' || $namespace == 'CSS') {
241 $this->definitions[$namespace] = null;
244 $this->serials[$namespace] = false;
248 * Convenience function for error reporting
250 private function _listify($lookup) {
251 $list = array();
252 foreach ($lookup as $name => $b) $list[] = $name;
253 return implode(', ', $list);
257 * Retrieves reference to the HTML definition.
258 * @param $raw Return a copy that has not been setup yet. Must be
259 * called before it's been setup, otherwise won't work.
261 public function &getHTMLDefinition($raw = false) {
262 $def =& $this->getDefinition('HTML', $raw);
263 return $def; // prevent PHP 4.4.0 from complaining
267 * Retrieves reference to the CSS definition
269 public function &getCSSDefinition($raw = false) {
270 $def =& $this->getDefinition('CSS', $raw);
271 return $def;
275 * Retrieves a definition
276 * @param $type Type of definition: HTML, CSS, etc
277 * @param $raw Whether or not definition should be returned raw
279 public function &getDefinition($type, $raw = false) {
280 if (!$this->finalized && $this->autoFinalize) $this->finalize();
281 $factory = HTMLPurifier_DefinitionCacheFactory::instance();
282 $cache = $factory->create($type, $this);
283 if (!$raw) {
284 // see if we can quickly supply a definition
285 if (!empty($this->definitions[$type])) {
286 if (!$this->definitions[$type]->setup) {
287 $this->definitions[$type]->setup($this);
288 $cache->set($this->definitions[$type], $this);
290 return $this->definitions[$type];
292 // memory check missed, try cache
293 $this->definitions[$type] = $cache->get($this);
294 if ($this->definitions[$type]) {
295 // definition in cache, return it
296 return $this->definitions[$type];
298 } elseif (
299 !empty($this->definitions[$type]) &&
300 !$this->definitions[$type]->setup
302 // raw requested, raw in memory, quick return
303 return $this->definitions[$type];
305 // quick checks failed, let's create the object
306 if ($type == 'HTML') {
307 $this->definitions[$type] = new HTMLPurifier_HTMLDefinition();
308 } elseif ($type == 'CSS') {
309 $this->definitions[$type] = new HTMLPurifier_CSSDefinition();
310 } elseif ($type == 'URI') {
311 $this->definitions[$type] = new HTMLPurifier_URIDefinition();
312 } else {
313 trigger_error("Definition of $type type not supported");
314 $false = false;
315 return $false;
317 // quick abort if raw
318 if ($raw) {
319 if (is_null($this->get($type, 'DefinitionID'))) {
320 // fatally error out if definition ID not set
321 trigger_error("Cannot retrieve raw version without specifying %$type.DefinitionID", E_USER_ERROR);
322 $false = new HTMLPurifier_Error();
323 return $false;
325 return $this->definitions[$type];
327 // set it up
328 $this->definitions[$type]->setup($this);
329 // save in cache
330 $cache->set($this->definitions[$type], $this);
331 return $this->definitions[$type];
335 * Loads configuration values from an array with the following structure:
336 * Namespace.Directive => Value
337 * @param $config_array Configuration associative array
339 public function loadArray($config_array) {
340 if ($this->isFinalized('Cannot load directives after finalization')) return;
341 foreach ($config_array as $key => $value) {
342 $key = str_replace('_', '.', $key);
343 if (strpos($key, '.') !== false) {
344 // condensed form
345 list($namespace, $directive) = explode('.', $key);
346 $this->set($namespace, $directive, $value);
347 } else {
348 $namespace = $key;
349 $namespace_values = $value;
350 foreach ($namespace_values as $directive => $value) {
351 $this->set($namespace, $directive, $value);
358 * Returns a list of array(namespace, directive) for all directives
359 * that are allowed in a web-form context as per an allowed
360 * namespaces/directives list.
361 * @param $allowed List of allowed namespaces/directives
363 public static function getAllowedDirectivesForForm($allowed, $schema = null) {
364 if (!$schema) {
365 $schema = HTMLPurifier_ConfigSchema::instance();
367 if ($allowed !== true) {
368 if (is_string($allowed)) $allowed = array($allowed);
369 $allowed_ns = array();
370 $allowed_directives = array();
371 $blacklisted_directives = array();
372 foreach ($allowed as $ns_or_directive) {
373 if (strpos($ns_or_directive, '.') !== false) {
374 // directive
375 if ($ns_or_directive[0] == '-') {
376 $blacklisted_directives[substr($ns_or_directive, 1)] = true;
377 } else {
378 $allowed_directives[$ns_or_directive] = true;
380 } else {
381 // namespace
382 $allowed_ns[$ns_or_directive] = true;
386 $ret = array();
387 foreach ($schema->info as $ns => $keypairs) {
388 foreach ($keypairs as $directive => $def) {
389 if ($allowed !== true) {
390 if (isset($blacklisted_directives["$ns.$directive"])) continue;
391 if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) continue;
393 if ($def->class == 'alias') continue;
394 if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') continue;
395 $ret[] = array($ns, $directive);
398 return $ret;
402 * Loads configuration values from $_GET/$_POST that were posted
403 * via ConfigForm
404 * @param $array $_GET or $_POST array to import
405 * @param $index Index/name that the config variables are in
406 * @param $allowed List of allowed namespaces/directives
407 * @param $mq_fix Boolean whether or not to enable magic quotes fix
408 * @param $schema Instance of HTMLPurifier_ConfigSchema to use, if not global copy
410 public static function loadArrayFromForm($array, $index, $allowed = true, $mq_fix = true, $schema = null) {
411 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
412 $config = HTMLPurifier_Config::create($ret, $schema);
413 return $config;
417 * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
418 * @note Same parameters as loadArrayFromForm
420 public function mergeArrayFromForm($array, $index, $allowed = true, $mq_fix = true) {
421 $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
422 $this->loadArray($ret);
426 * Prepares an array from a form into something usable for the more
427 * strict parts of HTMLPurifier_Config
429 public static function prepareArrayFromForm($array, $index, $allowed = true, $mq_fix = true, $schema = null) {
430 $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
431 $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
433 $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
434 $ret = array();
435 foreach ($allowed as $key) {
436 list($ns, $directive) = $key;
437 $skey = "$ns.$directive";
438 if (!empty($array["Null_$skey"])) {
439 $ret[$ns][$directive] = null;
440 continue;
442 if (!isset($array[$skey])) continue;
443 $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
444 $ret[$ns][$directive] = $value;
446 return $ret;
450 * Loads configuration values from an ini file
451 * @param $filename Name of ini file
453 public function loadIni($filename) {
454 if ($this->isFinalized('Cannot load directives after finalization')) return;
455 $array = parse_ini_file($filename, true);
456 $this->loadArray($array);
460 * Checks whether or not the configuration object is finalized.
461 * @param $error String error message, or false for no error
463 public function isFinalized($error = false) {
464 if ($this->finalized && $error) {
465 trigger_error($error, E_USER_ERROR);
467 return $this->finalized;
471 * Finalizes configuration only if auto finalize is on and not
472 * already finalized
474 public function autoFinalize() {
475 if (!$this->finalized && $this->autoFinalize) $this->finalize();
479 * Finalizes a configuration object, prohibiting further change
481 public function finalize() {
482 $this->finalized = true;