FixNesting.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. /**
  3. * Takes a well formed list of tokens and fixes their nesting.
  4. *
  5. * HTML elements dictate which elements are allowed to be their children,
  6. * for example, you can't have a p tag in a span tag. Other elements have
  7. * much more rigorous definitions: tables, for instance, require a specific
  8. * order for their elements. There are also constraints not expressible by
  9. * document type definitions, such as the chameleon nature of ins/del
  10. * tags and global child exclusions.
  11. *
  12. * The first major objective of this strategy is to iterate through all the
  13. * nodes (not tokens) of the list of tokens and determine whether or not
  14. * their children conform to the element's definition. If they do not, the
  15. * child definition may optionally supply an amended list of elements that
  16. * is valid or require that the entire node be deleted (and the previous
  17. * node rescanned).
  18. *
  19. * The second objective is to ensure that explicitly excluded elements of
  20. * an element do not appear in its children. Code that accomplishes this
  21. * task is pervasive through the strategy, though the two are distinct tasks
  22. * and could, theoretically, be seperated (although it's not recommended).
  23. *
  24. * @note Whether or not unrecognized children are silently dropped or
  25. * translated into text depends on the child definitions.
  26. *
  27. * @todo Enable nodes to be bubbled out of the structure.
  28. */
  29. class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy
  30. {
  31. public function execute($tokens, $config, $context) {
  32. //####################################################################//
  33. // Pre-processing
  34. // get a copy of the HTML definition
  35. $definition = $config->getHTMLDefinition();
  36. // insert implicit "parent" node, will be removed at end.
  37. // DEFINITION CALL
  38. $parent_name = $definition->info_parent;
  39. array_unshift($tokens, new HTMLPurifier_Token_Start($parent_name));
  40. $tokens[] = new HTMLPurifier_Token_End($parent_name);
  41. // setup the context variable 'IsInline', for chameleon processing
  42. // is 'false' when we are not inline, 'true' when it must always
  43. // be inline, and an integer when it is inline for a certain
  44. // branch of the document tree
  45. $is_inline = $definition->info_parent_def->descendants_are_inline;
  46. $context->register('IsInline', $is_inline);
  47. // setup error collector
  48. $e =& $context->get('ErrorCollector', true);
  49. //####################################################################//
  50. // Loop initialization
  51. // stack that contains the indexes of all parents,
  52. // $stack[count($stack)-1] being the current parent
  53. $stack = array();
  54. // stack that contains all elements that are excluded
  55. // it is organized by parent elements, similar to $stack,
  56. // but it is only populated when an element with exclusions is
  57. // processed, i.e. there won't be empty exclusions.
  58. $exclude_stack = array();
  59. // variable that contains the start token while we are processing
  60. // nodes. This enables error reporting to do its job
  61. $start_token = false;
  62. $context->register('CurrentToken', $start_token);
  63. //####################################################################//
  64. // Loop
  65. // iterate through all start nodes. Determining the start node
  66. // is complicated so it has been omitted from the loop construct
  67. for ($i = 0, $size = count($tokens) ; $i < $size; ) {
  68. //################################################################//
  69. // Gather information on children
  70. // child token accumulator
  71. $child_tokens = array();
  72. // scroll to the end of this node, report number, and collect
  73. // all children
  74. for ($j = $i, $depth = 0; ; $j++) {
  75. if ($tokens[$j] instanceof HTMLPurifier_Token_Start) {
  76. $depth++;
  77. // skip token assignment on first iteration, this is the
  78. // token we currently are on
  79. if ($depth == 1) continue;
  80. } elseif ($tokens[$j] instanceof HTMLPurifier_Token_End) {
  81. $depth--;
  82. // skip token assignment on last iteration, this is the
  83. // end token of the token we're currently on
  84. if ($depth == 0) break;
  85. }
  86. $child_tokens[] = $tokens[$j];
  87. }
  88. // $i is index of start token
  89. // $j is index of end token
  90. $start_token = $tokens[$i]; // to make token available via CurrentToken
  91. //################################################################//
  92. // Gather information on parent
  93. // calculate parent information
  94. if ($count = count($stack)) {
  95. $parent_index = $stack[$count-1];
  96. $parent_name = $tokens[$parent_index]->name;
  97. if ($parent_index == 0) {
  98. $parent_def = $definition->info_parent_def;
  99. } else {
  100. $parent_def = $definition->info[$parent_name];
  101. }
  102. } else {
  103. // processing as if the parent were the "root" node
  104. // unknown info, it won't be used anyway, in the future,
  105. // we may want to enforce one element only (this is
  106. // necessary for HTML Purifier to clean entire documents
  107. $parent_index = $parent_name = $parent_def = null;
  108. }
  109. // calculate context
  110. if ($is_inline === false) {
  111. // check if conditions make it inline
  112. if (!empty($parent_def) && $parent_def->descendants_are_inline) {
  113. $is_inline = $count - 1;
  114. }
  115. } else {
  116. // check if we're out of inline
  117. if ($count === $is_inline) {
  118. $is_inline = false;
  119. }
  120. }
  121. //################################################################//
  122. // Determine whether element is explicitly excluded SGML-style
  123. // determine whether or not element is excluded by checking all
  124. // parent exclusions. The array should not be very large, two
  125. // elements at most.
  126. $excluded = false;
  127. if (!empty($exclude_stack)) {
  128. foreach ($exclude_stack as $lookup) {
  129. if (isset($lookup[$tokens[$i]->name])) {
  130. $excluded = true;
  131. // no need to continue processing
  132. break;
  133. }
  134. }
  135. }
  136. //################################################################//
  137. // Perform child validation
  138. if ($excluded) {
  139. // there is an exclusion, remove the entire node
  140. $result = false;
  141. $excludes = array(); // not used, but good to initialize anyway
  142. } else {
  143. // DEFINITION CALL
  144. if ($i === 0) {
  145. // special processing for the first node
  146. $def = $definition->info_parent_def;
  147. } else {
  148. $def = $definition->info[$tokens[$i]->name];
  149. }
  150. if (!empty($def->child)) {
  151. // have DTD child def validate children
  152. $result = $def->child->validateChildren(
  153. $child_tokens, $config, $context);
  154. } else {
  155. // weird, no child definition, get rid of everything
  156. $result = false;
  157. }
  158. // determine whether or not this element has any exclusions
  159. $excludes = $def->excludes;
  160. }
  161. // $result is now a bool or array
  162. //################################################################//
  163. // Process result by interpreting $result
  164. if ($result === true || $child_tokens === $result) {
  165. // leave the node as is
  166. // register start token as a parental node start
  167. $stack[] = $i;
  168. // register exclusions if there are any
  169. if (!empty($excludes)) $exclude_stack[] = $excludes;
  170. // move cursor to next possible start node
  171. $i++;
  172. } elseif($result === false) {
  173. // remove entire node
  174. if ($e) {
  175. if ($excluded) {
  176. $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');
  177. } else {
  178. $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');
  179. }
  180. }
  181. // calculate length of inner tokens and current tokens
  182. $length = $j - $i + 1;
  183. // perform removal
  184. array_splice($tokens, $i, $length);
  185. // update size
  186. $size -= $length;
  187. // there is no start token to register,
  188. // current node is now the next possible start node
  189. // unless it turns out that we need to do a double-check
  190. // this is a rought heuristic that covers 100% of HTML's
  191. // cases and 99% of all other cases. A child definition
  192. // that would be tricked by this would be something like:
  193. // ( | a b c) where it's all or nothing. Fortunately,
  194. // our current implementation claims that that case would
  195. // not allow empty, even if it did
  196. if (!$parent_def->child->allow_empty) {
  197. // we need to do a double-check
  198. $i = $parent_index;
  199. array_pop($stack);
  200. }
  201. // PROJECTED OPTIMIZATION: Process all children elements before
  202. // reprocessing parent node.
  203. } else {
  204. // replace node with $result
  205. // calculate length of inner tokens
  206. $length = $j - $i - 1;
  207. if ($e) {
  208. if (empty($result) && $length) {
  209. $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');
  210. } else {
  211. $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');
  212. }
  213. }
  214. // perform replacement
  215. array_splice($tokens, $i + 1, $length, $result);
  216. // update size
  217. $size -= $length;
  218. $size += count($result);
  219. // register start token as a parental node start
  220. $stack[] = $i;
  221. // register exclusions if there are any
  222. if (!empty($excludes)) $exclude_stack[] = $excludes;
  223. // move cursor to next possible start node
  224. $i++;
  225. }
  226. //################################################################//
  227. // Scroll to next start node
  228. // We assume, at this point, that $i is the index of the token
  229. // that is the first possible new start point for a node.
  230. // Test if the token indeed is a start tag, if not, move forward
  231. // and test again.
  232. $size = count($tokens);
  233. while ($i < $size and !$tokens[$i] instanceof HTMLPurifier_Token_Start) {
  234. if ($tokens[$i] instanceof HTMLPurifier_Token_End) {
  235. // pop a token index off the stack if we ended a node
  236. array_pop($stack);
  237. // pop an exclusion lookup off exclusion stack if
  238. // we ended node and that node had exclusions
  239. if ($i == 0 || $i == $size - 1) {
  240. // use specialized var if it's the super-parent
  241. $s_excludes = $definition->info_parent_def->excludes;
  242. } else {
  243. $s_excludes = $definition->info[$tokens[$i]->name]->excludes;
  244. }
  245. if ($s_excludes) {
  246. array_pop($exclude_stack);
  247. }
  248. }
  249. $i++;
  250. }
  251. }
  252. //####################################################################//
  253. // Post-processing
  254. // remove implicit parent tokens at the beginning and end
  255. array_shift($tokens);
  256. array_pop($tokens);
  257. // remove context variables
  258. $context->destroy('IsInline');
  259. $context->destroy('CurrentToken');
  260. //####################################################################//
  261. // Return
  262. return $tokens;
  263. }
  264. }
  265. // vim: et sw=4 sts=4