PSR-2 reformatting PHPDoc corrections
[htmlpurifier.git] / library / HTMLPurifier / Strategy / FixNesting.php
blobd00c6d04d95dbec7c69c9aedd890d374dd0c4e3a
1 <?php
3 /**
4 * Takes a well formed list of tokens and fixes their nesting.
6 * HTML elements dictate which elements are allowed to be their children,
7 * for example, you can't have a p tag in a span tag. Other elements have
8 * much more rigorous definitions: tables, for instance, require a specific
9 * order for their elements. There are also constraints not expressible by
10 * document type definitions, such as the chameleon nature of ins/del
11 * tags and global child exclusions.
13 * The first major objective of this strategy is to iterate through all the
14 * nodes (not tokens) of the list of tokens and determine whether or not
15 * their children conform to the element's definition. If they do not, the
16 * child definition may optionally supply an amended list of elements that
17 * is valid or require that the entire node be deleted (and the previous
18 * node rescanned).
20 * The second objective is to ensure that explicitly excluded elements of
21 * an element do not appear in its children. Code that accomplishes this
22 * task is pervasive through the strategy, though the two are distinct tasks
23 * and could, theoretically, be seperated (although it's not recommended).
25 * @note Whether or not unrecognized children are silently dropped or
26 * translated into text depends on the child definitions.
28 * @todo Enable nodes to be bubbled out of the structure.
30 * @warning This algorithm (though it may be hard to see) proceeds from
31 * a top-down fashion. Thus, parents are processed before
32 * children. This is easy to implement and has a nice effiency
33 * benefit, in that if a node is removed, we never waste any
34 * time processing it, but it also means that if a child
35 * changes in a non-encapsulated way (e.g. it is removed), we
36 * need to go back and reprocess the parent to see if those
37 * changes resulted in problems for the parent. See
38 * [BACKTRACK] for an example of this. In the current
39 * implementation, this backtracking can only be triggered when
40 * a node is removed and if that node was the sole node, the
41 * parent would need to be removed. As such, it is easy to see
42 * that backtracking only incurs constant overhead. If more
43 * sophisticated backtracking is implemented, care must be
44 * taken to avoid nontermination or exponential blowup.
47 class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy
50 /**
51 * @param HTMLPurifier_Token[] $tokens
52 * @param HTMLPurifier_Config $config
53 * @param HTMLPurifier_Context $context
54 * @return array|HTMLPurifier_Token[]
56 public function execute($tokens, $config, $context)
58 //####################################################################//
59 // Pre-processing
61 // get a copy of the HTML definition
62 $definition = $config->getHTMLDefinition();
64 $excludes_enabled = !$config->get('Core.DisableExcludes');
66 // insert implicit "parent" node, will be removed at end.
67 // DEFINITION CALL
68 $parent_name = $definition->info_parent;
69 array_unshift($tokens, new HTMLPurifier_Token_Start($parent_name));
70 $tokens[] = new HTMLPurifier_Token_End($parent_name);
72 // setup the context variable 'IsInline', for chameleon processing
73 // is 'false' when we are not inline, 'true' when it must always
74 // be inline, and an integer when it is inline for a certain
75 // branch of the document tree
76 $is_inline = $definition->info_parent_def->descendants_are_inline;
77 $context->register('IsInline', $is_inline);
79 // setup error collector
80 $e =& $context->get('ErrorCollector', true);
82 //####################################################################//
83 // Loop initialization
85 // stack that contains the indexes of all parents,
86 // $stack[count($stack)-1] being the current parent
87 $stack = array();
89 // stack that contains all elements that are excluded
90 // it is organized by parent elements, similar to $stack,
91 // but it is only populated when an element with exclusions is
92 // processed, i.e. there won't be empty exclusions.
93 $exclude_stack = array();
95 // variable that contains the start token while we are processing
96 // nodes. This enables error reporting to do its job
97 $start_token = false;
98 $context->register('CurrentToken', $start_token);
100 //####################################################################//
101 // Loop
103 // iterate through all start nodes. Determining the start node
104 // is complicated so it has been omitted from the loop construct
105 for ($i = 0, $size = count($tokens); $i < $size;) {
107 //################################################################//
108 // Gather information on children
110 // child token accumulator
111 $child_tokens = array();
113 // scroll to the end of this node, report number, and collect
114 // all children
115 for ($j = $i, $depth = 0; ; $j++) {
116 if ($tokens[$j] instanceof HTMLPurifier_Token_Start) {
117 $depth++;
118 // skip token assignment on first iteration, this is the
119 // token we currently are on
120 if ($depth == 1) {
121 continue;
123 } elseif ($tokens[$j] instanceof HTMLPurifier_Token_End) {
124 $depth--;
125 // skip token assignment on last iteration, this is the
126 // end token of the token we're currently on
127 if ($depth == 0) {
128 break;
131 $child_tokens[] = $tokens[$j];
134 // $i is index of start token
135 // $j is index of end token
137 $start_token = $tokens[$i]; // to make token available via CurrentToken
139 //################################################################//
140 // Gather information on parent
142 // calculate parent information
143 if ($count = count($stack)) {
144 $parent_index = $stack[$count - 1];
145 $parent_name = $tokens[$parent_index]->name;
146 if ($parent_index == 0) {
147 $parent_def = $definition->info_parent_def;
148 } else {
149 $parent_def = $definition->info[$parent_name];
151 } else {
152 // processing as if the parent were the "root" node
153 // unknown info, it won't be used anyway, in the future,
154 // we may want to enforce one element only (this is
155 // necessary for HTML Purifier to clean entire documents
156 $parent_index = $parent_name = $parent_def = null;
159 // calculate context
160 if ($is_inline === false) {
161 // check if conditions make it inline
162 if (!empty($parent_def) && $parent_def->descendants_are_inline) {
163 $is_inline = $count - 1;
165 } else {
166 // check if we're out of inline
167 if ($count === $is_inline) {
168 $is_inline = false;
172 //################################################################//
173 // Determine whether element is explicitly excluded SGML-style
175 // determine whether or not element is excluded by checking all
176 // parent exclusions. The array should not be very large, two
177 // elements at most.
178 $excluded = false;
179 if (!empty($exclude_stack) && $excludes_enabled) {
180 foreach ($exclude_stack as $lookup) {
181 if (isset($lookup[$tokens[$i]->name])) {
182 $excluded = true;
183 // no need to continue processing
184 break;
189 //################################################################//
190 // Perform child validation
192 if ($excluded) {
193 // there is an exclusion, remove the entire node
194 $result = false;
195 $excludes = array(); // not used, but good to initialize anyway
196 } else {
197 // DEFINITION CALL
198 if ($i === 0) {
199 // special processing for the first node
200 $def = $definition->info_parent_def;
201 } else {
202 $def = $definition->info[$tokens[$i]->name];
206 if (!empty($def->child)) {
207 // have DTD child def validate children
208 $result = $def->child->validateChildren(
209 $child_tokens,
210 $config,
211 $context
213 } else {
214 // weird, no child definition, get rid of everything
215 $result = false;
218 // determine whether or not this element has any exclusions
219 $excludes = $def->excludes;
222 // $result is now a bool or array
224 //################################################################//
225 // Process result by interpreting $result
227 if ($result === true || $child_tokens === $result) {
228 // leave the node as is
230 // register start token as a parental node start
231 $stack[] = $i;
233 // register exclusions if there are any
234 if (!empty($excludes)) {
235 $exclude_stack[] = $excludes;
238 // move cursor to next possible start node
239 $i++;
241 } elseif ($result === false) {
242 // remove entire node
244 if ($e) {
245 if ($excluded) {
246 $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');
247 } else {
248 $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');
252 // calculate length of inner tokens and current tokens
253 $length = $j - $i + 1;
255 // perform removal
256 array_splice($tokens, $i, $length);
258 // update size
259 $size -= $length;
261 // there is no start token to register,
262 // current node is now the next possible start node
263 // unless it turns out that we need to do a double-check
265 // this is a rought heuristic that covers 100% of HTML's
266 // cases and 99% of all other cases. A child definition
267 // that would be tricked by this would be something like:
268 // ( | a b c) where it's all or nothing. Fortunately,
269 // our current implementation claims that that case would
270 // not allow empty, even if it did
271 if (!$parent_def->child->allow_empty) {
272 // we need to do a double-check [BACKTRACK]
273 $i = $parent_index;
274 array_pop($stack);
277 // PROJECTED OPTIMIZATION: Process all children elements before
278 // reprocessing parent node.
280 } else {
281 // replace node with $result
283 // calculate length of inner tokens
284 $length = $j - $i - 1;
286 if ($e) {
287 if (empty($result) && $length) {
288 $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');
289 } else {
290 $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');
294 // perform replacement
295 array_splice($tokens, $i + 1, $length, $result);
297 // update size
298 $size -= $length;
299 $size += count($result);
301 // register start token as a parental node start
302 $stack[] = $i;
304 // register exclusions if there are any
305 if (!empty($excludes)) {
306 $exclude_stack[] = $excludes;
309 // move cursor to next possible start node
310 $i++;
313 //################################################################//
314 // Scroll to next start node
316 // We assume, at this point, that $i is the index of the token
317 // that is the first possible new start point for a node.
319 // Test if the token indeed is a start tag, if not, move forward
320 // and test again.
321 $size = count($tokens);
322 while ($i < $size and !$tokens[$i] instanceof HTMLPurifier_Token_Start) {
323 if ($tokens[$i] instanceof HTMLPurifier_Token_End) {
324 // pop a token index off the stack if we ended a node
325 array_pop($stack);
326 // pop an exclusion lookup off exclusion stack if
327 // we ended node and that node had exclusions
328 if ($i == 0 || $i == $size - 1) {
329 // use specialized var if it's the super-parent
330 $s_excludes = $definition->info_parent_def->excludes;
331 } else {
332 $s_excludes = $definition->info[$tokens[$i]->name]->excludes;
334 if ($s_excludes) {
335 array_pop($exclude_stack);
338 $i++;
343 //####################################################################//
344 // Post-processing
346 // remove implicit parent tokens at the beginning and end
347 array_shift($tokens);
348 array_pop($tokens);
350 // remove context variables
351 $context->destroy('IsInline');
352 $context->destroy('CurrentToken');
354 //####################################################################//
355 // Return
356 return $tokens;
360 // vim: et sw=4 sts=4