Add conversion functions for our own tree format.
[htmlpurifier.git] / library / HTMLPurifier / Strategy / FixNesting.php
blobf78ad08653566a70563e5ce60081d957f38620ce
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 //$node = HTMLPurifier_Arborize::arborize($tokens, $config, $context);
62 //$new_tokens = HTMLPurifier_Arborize::flatten($node, $config, $context);
64 // get a copy of the HTML definition
65 $definition = $config->getHTMLDefinition();
67 $excludes_enabled = !$config->get('Core.DisableExcludes');
69 // insert implicit "parent" node, will be removed at end.
70 // DEFINITION CALL
71 $parent_name = $definition->info_parent;
72 array_unshift($tokens, new HTMLPurifier_Token_Start($parent_name));
73 $tokens[] = new HTMLPurifier_Token_End($parent_name);
75 // setup the context variable 'IsInline', for chameleon processing
76 // is 'false' when we are not inline, 'true' when it must always
77 // be inline, and an integer when it is inline for a certain
78 // branch of the document tree
79 $is_inline = $definition->info_parent_def->descendants_are_inline;
80 $context->register('IsInline', $is_inline);
82 // setup error collector
83 $e =& $context->get('ErrorCollector', true);
85 //####################################################################//
86 // Loop initialization
88 // stack that contains the indexes of all parents,
89 // $stack[count($stack)-1] being the current parent
90 $stack = array();
92 // stack that contains all elements that are excluded
93 // it is organized by parent elements, similar to $stack,
94 // but it is only populated when an element with exclusions is
95 // processed, i.e. there won't be empty exclusions.
96 $exclude_stack = array();
98 // variable that contains the start token while we are processing
99 // nodes. This enables error reporting to do its job
100 $start_token = false;
101 $context->register('CurrentToken', $start_token);
103 //####################################################################//
104 // Loop
106 // iterate through all start nodes. Determining the start node
107 // is complicated so it has been omitted from the loop construct
108 for ($i = 0, $size = count($tokens); $i < $size;) {
110 //################################################################//
111 // Gather information on children
113 // child token accumulator
114 $child_tokens = array();
116 // scroll to the end of this node, report number, and collect
117 // all children
118 for ($j = $i, $depth = 0; ; $j++) {
119 if ($tokens[$j] instanceof HTMLPurifier_Token_Start) {
120 $depth++;
121 // skip token assignment on first iteration, this is the
122 // token we currently are on
123 if ($depth == 1) {
124 continue;
126 } elseif ($tokens[$j] instanceof HTMLPurifier_Token_End) {
127 $depth--;
128 // skip token assignment on last iteration, this is the
129 // end token of the token we're currently on
130 if ($depth == 0) {
131 break;
134 $child_tokens[] = $tokens[$j];
137 // $i is index of start token
138 // $j is index of end token
140 $start_token = $tokens[$i]; // to make token available via CurrentToken
142 //################################################################//
143 // Gather information on parent
145 // calculate parent information
146 if ($count = count($stack)) {
147 $parent_index = $stack[$count - 1];
148 $parent_name = $tokens[$parent_index]->name;
149 if ($parent_index == 0) {
150 $parent_def = $definition->info_parent_def;
151 } else {
152 $parent_def = $definition->info[$parent_name];
154 } else {
155 // processing as if the parent were the "root" node
156 // unknown info, it won't be used anyway, in the future,
157 // we may want to enforce one element only (this is
158 // necessary for HTML Purifier to clean entire documents
159 $parent_index = $parent_name = $parent_def = null;
162 // calculate context
163 if ($is_inline === false) {
164 // check if conditions make it inline
165 if (!empty($parent_def) && $parent_def->descendants_are_inline) {
166 $is_inline = $count - 1;
168 } else {
169 // check if we're out of inline
170 if ($count === $is_inline) {
171 $is_inline = false;
175 //################################################################//
176 // Determine whether element is explicitly excluded SGML-style
178 // determine whether or not element is excluded by checking all
179 // parent exclusions. The array should not be very large, two
180 // elements at most.
181 $excluded = false;
182 if (!empty($exclude_stack) && $excludes_enabled) {
183 foreach ($exclude_stack as $lookup) {
184 if (isset($lookup[$tokens[$i]->name])) {
185 $excluded = true;
186 // no need to continue processing
187 break;
192 //################################################################//
193 // Perform child validation
195 if ($excluded) {
196 // there is an exclusion, remove the entire node
197 $result = false;
198 $excludes = array(); // not used, but good to initialize anyway
199 } else {
200 // DEFINITION CALL
201 if ($i === 0) {
202 // special processing for the first node
203 $def = $definition->info_parent_def;
204 } else {
205 $def = $definition->info[$tokens[$i]->name];
209 if (!empty($def->child)) {
210 // have DTD child def validate children
211 $result = $def->child->validateChildren(
212 $child_tokens,
213 $config,
214 $context
216 } else {
217 // weird, no child definition, get rid of everything
218 $result = false;
221 // determine whether or not this element has any exclusions
222 $excludes = $def->excludes;
225 // $result is now a bool or array
227 //################################################################//
228 // Process result by interpreting $result
230 if ($result === true || $child_tokens === $result) {
231 // leave the node as is
233 // register start token as a parental node start
234 $stack[] = $i;
236 // register exclusions if there are any
237 if (!empty($excludes)) {
238 $exclude_stack[] = $excludes;
241 // move cursor to next possible start node
242 $i++;
244 } elseif ($result === false) {
245 // remove entire node
247 if ($e) {
248 if ($excluded) {
249 $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');
250 } else {
251 $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');
255 // calculate length of inner tokens and current tokens
256 $length = $j - $i + 1;
258 // perform removal
259 array_splice($tokens, $i, $length);
261 // update size
262 $size -= $length;
264 // there is no start token to register,
265 // current node is now the next possible start node
266 // unless it turns out that we need to do a double-check
268 // this is a rought heuristic that covers 100% of HTML's
269 // cases and 99% of all other cases. A child definition
270 // that would be tricked by this would be something like:
271 // ( | a b c) where it's all or nothing. Fortunately,
272 // our current implementation claims that that case would
273 // not allow empty, even if it did
274 if (!$parent_def->child->allow_empty) {
275 // we need to do a double-check [BACKTRACK]
276 $i = $parent_index;
277 array_pop($stack);
280 // PROJECTED OPTIMIZATION: Process all children elements before
281 // reprocessing parent node.
283 } else {
284 // replace node with $result
286 // calculate length of inner tokens
287 $length = $j - $i - 1;
289 if ($e) {
290 if (empty($result) && $length) {
291 $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');
292 } else {
293 $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');
297 // perform replacement
298 array_splice($tokens, $i + 1, $length, $result);
300 // update size
301 $size -= $length;
302 $size += count($result);
304 // register start token as a parental node start
305 $stack[] = $i;
307 // register exclusions if there are any
308 if (!empty($excludes)) {
309 $exclude_stack[] = $excludes;
312 // move cursor to next possible start node
313 $i++;
316 //################################################################//
317 // Scroll to next start node
319 // We assume, at this point, that $i is the index of the token
320 // that is the first possible new start point for a node.
322 // Test if the token indeed is a start tag, if not, move forward
323 // and test again.
324 $size = count($tokens);
325 while ($i < $size and !$tokens[$i] instanceof HTMLPurifier_Token_Start) {
326 if ($tokens[$i] instanceof HTMLPurifier_Token_End) {
327 // pop a token index off the stack if we ended a node
328 array_pop($stack);
329 // pop an exclusion lookup off exclusion stack if
330 // we ended node and that node had exclusions
331 if ($i == 0 || $i == $size - 1) {
332 // use specialized var if it's the super-parent
333 $s_excludes = $definition->info_parent_def->excludes;
334 } else {
335 $s_excludes = $definition->info[$tokens[$i]->name]->excludes;
337 if ($s_excludes) {
338 array_pop($exclude_stack);
341 $i++;
346 //####################################################################//
347 // Post-processing
349 // remove implicit parent tokens at the beginning and end
350 array_shift($tokens);
351 array_pop($tokens);
353 // remove context variables
354 $context->destroy('IsInline');
355 $context->destroy('CurrentToken');
357 //####################################################################//
358 // Return
359 return $tokens;
363 // vim: et sw=4 sts=4