PageRenderTime 71ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/school/605.441.Databases/project/htmlpurifier/maintenance/PH5P.php

https://github.com/hank/life
PHP | 3824 lines | 1943 code | 607 blank | 1274 comment | 299 complexity | f902c78700b9d61daafecaa569cf0b81 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, Apache-2.0
  1. <?php
  2. class HTML5 {
  3. private $data;
  4. private $char;
  5. private $EOF;
  6. private $state;
  7. private $tree;
  8. private $token;
  9. private $content_model;
  10. private $escape = false;
  11. private $entities = array('AElig;','AElig','AMP;','AMP','Aacute;','Aacute',
  12. 'Acirc;','Acirc','Agrave;','Agrave','Alpha;','Aring;','Aring','Atilde;',
  13. 'Atilde','Auml;','Auml','Beta;','COPY;','COPY','Ccedil;','Ccedil','Chi;',
  14. 'Dagger;','Delta;','ETH;','ETH','Eacute;','Eacute','Ecirc;','Ecirc','Egrave;',
  15. 'Egrave','Epsilon;','Eta;','Euml;','Euml','GT;','GT','Gamma;','Iacute;',
  16. 'Iacute','Icirc;','Icirc','Igrave;','Igrave','Iota;','Iuml;','Iuml','Kappa;',
  17. 'LT;','LT','Lambda;','Mu;','Ntilde;','Ntilde','Nu;','OElig;','Oacute;',
  18. 'Oacute','Ocirc;','Ocirc','Ograve;','Ograve','Omega;','Omicron;','Oslash;',
  19. 'Oslash','Otilde;','Otilde','Ouml;','Ouml','Phi;','Pi;','Prime;','Psi;',
  20. 'QUOT;','QUOT','REG;','REG','Rho;','Scaron;','Sigma;','THORN;','THORN',
  21. 'TRADE;','Tau;','Theta;','Uacute;','Uacute','Ucirc;','Ucirc','Ugrave;',
  22. 'Ugrave','Upsilon;','Uuml;','Uuml','Xi;','Yacute;','Yacute','Yuml;','Zeta;',
  23. 'aacute;','aacute','acirc;','acirc','acute;','acute','aelig;','aelig',
  24. 'agrave;','agrave','alefsym;','alpha;','amp;','amp','and;','ang;','apos;',
  25. 'aring;','aring','asymp;','atilde;','atilde','auml;','auml','bdquo;','beta;',
  26. 'brvbar;','brvbar','bull;','cap;','ccedil;','ccedil','cedil;','cedil',
  27. 'cent;','cent','chi;','circ;','clubs;','cong;','copy;','copy','crarr;',
  28. 'cup;','curren;','curren','dArr;','dagger;','darr;','deg;','deg','delta;',
  29. 'diams;','divide;','divide','eacute;','eacute','ecirc;','ecirc','egrave;',
  30. 'egrave','empty;','emsp;','ensp;','epsilon;','equiv;','eta;','eth;','eth',
  31. 'euml;','euml','euro;','exist;','fnof;','forall;','frac12;','frac12',
  32. 'frac14;','frac14','frac34;','frac34','frasl;','gamma;','ge;','gt;','gt',
  33. 'hArr;','harr;','hearts;','hellip;','iacute;','iacute','icirc;','icirc',
  34. 'iexcl;','iexcl','igrave;','igrave','image;','infin;','int;','iota;',
  35. 'iquest;','iquest','isin;','iuml;','iuml','kappa;','lArr;','lambda;','lang;',
  36. 'laquo;','laquo','larr;','lceil;','ldquo;','le;','lfloor;','lowast;','loz;',
  37. 'lrm;','lsaquo;','lsquo;','lt;','lt','macr;','macr','mdash;','micro;','micro',
  38. 'middot;','middot','minus;','mu;','nabla;','nbsp;','nbsp','ndash;','ne;',
  39. 'ni;','not;','not','notin;','nsub;','ntilde;','ntilde','nu;','oacute;',
  40. 'oacute','ocirc;','ocirc','oelig;','ograve;','ograve','oline;','omega;',
  41. 'omicron;','oplus;','or;','ordf;','ordf','ordm;','ordm','oslash;','oslash',
  42. 'otilde;','otilde','otimes;','ouml;','ouml','para;','para','part;','permil;',
  43. 'perp;','phi;','pi;','piv;','plusmn;','plusmn','pound;','pound','prime;',
  44. 'prod;','prop;','psi;','quot;','quot','rArr;','radic;','rang;','raquo;',
  45. 'raquo','rarr;','rceil;','rdquo;','real;','reg;','reg','rfloor;','rho;',
  46. 'rlm;','rsaquo;','rsquo;','sbquo;','scaron;','sdot;','sect;','sect','shy;',
  47. 'shy','sigma;','sigmaf;','sim;','spades;','sub;','sube;','sum;','sup1;',
  48. 'sup1','sup2;','sup2','sup3;','sup3','sup;','supe;','szlig;','szlig','tau;',
  49. 'there4;','theta;','thetasym;','thinsp;','thorn;','thorn','tilde;','times;',
  50. 'times','trade;','uArr;','uacute;','uacute','uarr;','ucirc;','ucirc',
  51. 'ugrave;','ugrave','uml;','uml','upsih;','upsilon;','uuml;','uuml','weierp;',
  52. 'xi;','yacute;','yacute','yen;','yen','yuml;','yuml','zeta;','zwj;','zwnj;');
  53. const PCDATA = 0;
  54. const RCDATA = 1;
  55. const CDATA = 2;
  56. const PLAINTEXT = 3;
  57. const DOCTYPE = 0;
  58. const STARTTAG = 1;
  59. const ENDTAG = 2;
  60. const COMMENT = 3;
  61. const CHARACTR = 4;
  62. const EOF = 5;
  63. public function __construct($data) {
  64. $data = str_replace("\r\n", "\n", $data);
  65. $date = str_replace("\r", null, $data);
  66. $this->data = $data;
  67. $this->char = -1;
  68. $this->EOF = strlen($data);
  69. $this->tree = new HTML5TreeConstructer;
  70. $this->content_model = self::PCDATA;
  71. $this->state = 'data';
  72. while($this->state !== null) {
  73. $this->{$this->state.'State'}();
  74. }
  75. }
  76. public function save() {
  77. return $this->tree->save();
  78. }
  79. private function char() {
  80. return ($this->char < $this->EOF)
  81. ? $this->data[$this->char]
  82. : false;
  83. }
  84. private function character($s, $l = 0) {
  85. if($s + $l < $this->EOF) {
  86. if($l === 0) {
  87. return $this->data[$s];
  88. } else {
  89. return substr($this->data, $s, $l);
  90. }
  91. }
  92. }
  93. private function characters($char_class, $start) {
  94. return preg_replace('#^(['.$char_class.']+).*#s', '\\1', substr($this->data, $start));
  95. }
  96. private function dataState() {
  97. // Consume the next input character
  98. $this->char++;
  99. $char = $this->char();
  100. if($char === '&' && ($this->content_model === self::PCDATA || $this->content_model === self::RCDATA)) {
  101. /* U+0026 AMPERSAND (&)
  102. When the content model flag is set to one of the PCDATA or RCDATA
  103. states: switch to the entity data state. Otherwise: treat it as per
  104. the "anything else" entry below. */
  105. $this->state = 'entityData';
  106. } elseif($char === '-') {
  107. /* If the content model flag is set to either the RCDATA state or
  108. the CDATA state, and the escape flag is false, and there are at
  109. least three characters before this one in the input stream, and the
  110. last four characters in the input stream, including this one, are
  111. U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS,
  112. and U+002D HYPHEN-MINUS ("<!--"), then set the escape flag to true. */
  113. if(($this->content_model === self::RCDATA || $this->content_model ===
  114. self::CDATA) && $this->escape === false &&
  115. $this->char >= 3 && $this->character($this->char - 4, 4) === '<!--') {
  116. $this->escape = true;
  117. }
  118. /* In any case, emit the input character as a character token. Stay
  119. in the data state. */
  120. $this->emitToken(array(
  121. 'type' => self::CHARACTR,
  122. 'data' => $char
  123. ));
  124. /* U+003C LESS-THAN SIGN (<) */
  125. } elseif($char === '<' && ($this->content_model === self::PCDATA ||
  126. (($this->content_model === self::RCDATA ||
  127. $this->content_model === self::CDATA) && $this->escape === false))) {
  128. /* When the content model flag is set to the PCDATA state: switch
  129. to the tag open state.
  130. When the content model flag is set to either the RCDATA state or
  131. the CDATA state and the escape flag is false: switch to the tag
  132. open state.
  133. Otherwise: treat it as per the "anything else" entry below. */
  134. $this->state = 'tagOpen';
  135. /* U+003E GREATER-THAN SIGN (>) */
  136. } elseif($char === '>') {
  137. /* If the content model flag is set to either the RCDATA state or
  138. the CDATA state, and the escape flag is true, and the last three
  139. characters in the input stream including this one are U+002D
  140. HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN ("-->"),
  141. set the escape flag to false. */
  142. if(($this->content_model === self::RCDATA ||
  143. $this->content_model === self::CDATA) && $this->escape === true &&
  144. $this->character($this->char, 3) === '-->') {
  145. $this->escape = false;
  146. }
  147. /* In any case, emit the input character as a character token.
  148. Stay in the data state. */
  149. $this->emitToken(array(
  150. 'type' => self::CHARACTR,
  151. 'data' => $char
  152. ));
  153. } elseif($this->char === $this->EOF) {
  154. /* EOF
  155. Emit an end-of-file token. */
  156. $this->EOF();
  157. } elseif($this->content_model === self::PLAINTEXT) {
  158. /* When the content model flag is set to the PLAINTEXT state
  159. THIS DIFFERS GREATLY FROM THE SPEC: Get the remaining characters of
  160. the text and emit it as a character token. */
  161. $this->emitToken(array(
  162. 'type' => self::CHARACTR,
  163. 'data' => substr($this->data, $this->char)
  164. ));
  165. $this->EOF();
  166. } else {
  167. /* Anything else
  168. THIS DIFFERS GREATLY FROM THE SPEC: Get as many character that
  169. otherwise would also be treated as a character token and emit it
  170. as a single character token. Stay in the data state. */
  171. $len = strcspn($this->data, '<&', $this->char);
  172. $char = substr($this->data, $this->char, $len);
  173. $this->char += $len - 1;
  174. $this->emitToken(array(
  175. 'type' => self::CHARACTR,
  176. 'data' => $char
  177. ));
  178. $this->state = 'data';
  179. }
  180. }
  181. private function entityDataState() {
  182. // Attempt to consume an entity.
  183. $entity = $this->entity();
  184. // If nothing is returned, emit a U+0026 AMPERSAND character token.
  185. // Otherwise, emit the character token that was returned.
  186. $char = (!$entity) ? '&' : $entity;
  187. $this->emitToken($char);
  188. // Finally, switch to the data state.
  189. $this->state = 'data';
  190. }
  191. private function tagOpenState() {
  192. switch($this->content_model) {
  193. case self::RCDATA:
  194. case self::CDATA:
  195. /* If the next input character is a U+002F SOLIDUS (/) character,
  196. consume it and switch to the close tag open state. If the next
  197. input character is not a U+002F SOLIDUS (/) character, emit a
  198. U+003C LESS-THAN SIGN character token and switch to the data
  199. state to process the next input character. */
  200. if($this->character($this->char + 1) === '/') {
  201. $this->char++;
  202. $this->state = 'closeTagOpen';
  203. } else {
  204. $this->emitToken(array(
  205. 'type' => self::CHARACTR,
  206. 'data' => '<'
  207. ));
  208. $this->state = 'data';
  209. }
  210. break;
  211. case self::PCDATA:
  212. // If the content model flag is set to the PCDATA state
  213. // Consume the next input character:
  214. $this->char++;
  215. $char = $this->char();
  216. if($char === '!') {
  217. /* U+0021 EXCLAMATION MARK (!)
  218. Switch to the markup declaration open state. */
  219. $this->state = 'markupDeclarationOpen';
  220. } elseif($char === '/') {
  221. /* U+002F SOLIDUS (/)
  222. Switch to the close tag open state. */
  223. $this->state = 'closeTagOpen';
  224. } elseif(preg_match('/^[A-Za-z]$/', $char)) {
  225. /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z
  226. Create a new start tag token, set its tag name to the lowercase
  227. version of the input character (add 0x0020 to the character's code
  228. point), then switch to the tag name state. (Don't emit the token
  229. yet; further details will be filled in before it is emitted.) */
  230. $this->token = array(
  231. 'name' => strtolower($char),
  232. 'type' => self::STARTTAG,
  233. 'attr' => array()
  234. );
  235. $this->state = 'tagName';
  236. } elseif($char === '>') {
  237. /* U+003E GREATER-THAN SIGN (>)
  238. Parse error. Emit a U+003C LESS-THAN SIGN character token and a
  239. U+003E GREATER-THAN SIGN character token. Switch to the data state. */
  240. $this->emitToken(array(
  241. 'type' => self::CHARACTR,
  242. 'data' => '<>'
  243. ));
  244. $this->state = 'data';
  245. } elseif($char === '?') {
  246. /* U+003F QUESTION MARK (?)
  247. Parse error. Switch to the bogus comment state. */
  248. $this->state = 'bogusComment';
  249. } else {
  250. /* Anything else
  251. Parse error. Emit a U+003C LESS-THAN SIGN character token and
  252. reconsume the current input character in the data state. */
  253. $this->emitToken(array(
  254. 'type' => self::CHARACTR,
  255. 'data' => '<'
  256. ));
  257. $this->char--;
  258. $this->state = 'data';
  259. }
  260. break;
  261. }
  262. }
  263. private function closeTagOpenState() {
  264. $next_node = strtolower($this->characters('A-Za-z', $this->char + 1));
  265. $the_same = count($this->tree->stack) > 0 && $next_node === end($this->tree->stack)->nodeName;
  266. if(($this->content_model === self::RCDATA || $this->content_model === self::CDATA) &&
  267. (!$the_same || ($the_same && (!preg_match('/[\t\n\x0b\x0c >\/]/',
  268. $this->character($this->char + 1 + strlen($next_node))) || $this->EOF === $this->char)))) {
  269. /* If the content model flag is set to the RCDATA or CDATA states then
  270. examine the next few characters. If they do not match the tag name of
  271. the last start tag token emitted (case insensitively), or if they do but
  272. they are not immediately followed by one of the following characters:
  273. * U+0009 CHARACTER TABULATION
  274. * U+000A LINE FEED (LF)
  275. * U+000B LINE TABULATION
  276. * U+000C FORM FEED (FF)
  277. * U+0020 SPACE
  278. * U+003E GREATER-THAN SIGN (>)
  279. * U+002F SOLIDUS (/)
  280. * EOF
  281. ...then there is a parse error. Emit a U+003C LESS-THAN SIGN character
  282. token, a U+002F SOLIDUS character token, and switch to the data state
  283. to process the next input character. */
  284. $this->emitToken(array(
  285. 'type' => self::CHARACTR,
  286. 'data' => '</'
  287. ));
  288. $this->state = 'data';
  289. } else {
  290. /* Otherwise, if the content model flag is set to the PCDATA state,
  291. or if the next few characters do match that tag name, consume the
  292. next input character: */
  293. $this->char++;
  294. $char = $this->char();
  295. if(preg_match('/^[A-Za-z]$/', $char)) {
  296. /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z
  297. Create a new end tag token, set its tag name to the lowercase version
  298. of the input character (add 0x0020 to the character's code point), then
  299. switch to the tag name state. (Don't emit the token yet; further details
  300. will be filled in before it is emitted.) */
  301. $this->token = array(
  302. 'name' => strtolower($char),
  303. 'type' => self::ENDTAG
  304. );
  305. $this->state = 'tagName';
  306. } elseif($char === '>') {
  307. /* U+003E GREATER-THAN SIGN (>)
  308. Parse error. Switch to the data state. */
  309. $this->state = 'data';
  310. } elseif($this->char === $this->EOF) {
  311. /* EOF
  312. Parse error. Emit a U+003C LESS-THAN SIGN character token and a U+002F
  313. SOLIDUS character token. Reconsume the EOF character in the data state. */
  314. $this->emitToken(array(
  315. 'type' => self::CHARACTR,
  316. 'data' => '</'
  317. ));
  318. $this->char--;
  319. $this->state = 'data';
  320. } else {
  321. /* Parse error. Switch to the bogus comment state. */
  322. $this->state = 'bogusComment';
  323. }
  324. }
  325. }
  326. private function tagNameState() {
  327. // Consume the next input character:
  328. $this->char++;
  329. $char = $this->character($this->char);
  330. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  331. /* U+0009 CHARACTER TABULATION
  332. U+000A LINE FEED (LF)
  333. U+000B LINE TABULATION
  334. U+000C FORM FEED (FF)
  335. U+0020 SPACE
  336. Switch to the before attribute name state. */
  337. $this->state = 'beforeAttributeName';
  338. } elseif($char === '>') {
  339. /* U+003E GREATER-THAN SIGN (>)
  340. Emit the current tag token. Switch to the data state. */
  341. $this->emitToken($this->token);
  342. $this->state = 'data';
  343. } elseif($this->char === $this->EOF) {
  344. /* EOF
  345. Parse error. Emit the current tag token. Reconsume the EOF
  346. character in the data state. */
  347. $this->emitToken($this->token);
  348. $this->char--;
  349. $this->state = 'data';
  350. } elseif($char === '/') {
  351. /* U+002F SOLIDUS (/)
  352. Parse error unless this is a permitted slash. Switch to the before
  353. attribute name state. */
  354. $this->state = 'beforeAttributeName';
  355. } else {
  356. /* Anything else
  357. Append the current input character to the current tag token's tag name.
  358. Stay in the tag name state. */
  359. $this->token['name'] .= strtolower($char);
  360. $this->state = 'tagName';
  361. }
  362. }
  363. private function beforeAttributeNameState() {
  364. // Consume the next input character:
  365. $this->char++;
  366. $char = $this->character($this->char);
  367. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  368. /* U+0009 CHARACTER TABULATION
  369. U+000A LINE FEED (LF)
  370. U+000B LINE TABULATION
  371. U+000C FORM FEED (FF)
  372. U+0020 SPACE
  373. Stay in the before attribute name state. */
  374. $this->state = 'beforeAttributeName';
  375. } elseif($char === '>') {
  376. /* U+003E GREATER-THAN SIGN (>)
  377. Emit the current tag token. Switch to the data state. */
  378. $this->emitToken($this->token);
  379. $this->state = 'data';
  380. } elseif($char === '/') {
  381. /* U+002F SOLIDUS (/)
  382. Parse error unless this is a permitted slash. Stay in the before
  383. attribute name state. */
  384. $this->state = 'beforeAttributeName';
  385. } elseif($this->char === $this->EOF) {
  386. /* EOF
  387. Parse error. Emit the current tag token. Reconsume the EOF
  388. character in the data state. */
  389. $this->emitToken($this->token);
  390. $this->char--;
  391. $this->state = 'data';
  392. } else {
  393. /* Anything else
  394. Start a new attribute in the current tag token. Set that attribute's
  395. name to the current input character, and its value to the empty string.
  396. Switch to the attribute name state. */
  397. $this->token['attr'][] = array(
  398. 'name' => strtolower($char),
  399. 'value' => null
  400. );
  401. $this->state = 'attributeName';
  402. }
  403. }
  404. private function attributeNameState() {
  405. // Consume the next input character:
  406. $this->char++;
  407. $char = $this->character($this->char);
  408. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  409. /* U+0009 CHARACTER TABULATION
  410. U+000A LINE FEED (LF)
  411. U+000B LINE TABULATION
  412. U+000C FORM FEED (FF)
  413. U+0020 SPACE
  414. Stay in the before attribute name state. */
  415. $this->state = 'afterAttributeName';
  416. } elseif($char === '=') {
  417. /* U+003D EQUALS SIGN (=)
  418. Switch to the before attribute value state. */
  419. $this->state = 'beforeAttributeValue';
  420. } elseif($char === '>') {
  421. /* U+003E GREATER-THAN SIGN (>)
  422. Emit the current tag token. Switch to the data state. */
  423. $this->emitToken($this->token);
  424. $this->state = 'data';
  425. } elseif($char === '/' && $this->character($this->char + 1) !== '>') {
  426. /* U+002F SOLIDUS (/)
  427. Parse error unless this is a permitted slash. Switch to the before
  428. attribute name state. */
  429. $this->state = 'beforeAttributeName';
  430. } elseif($this->char === $this->EOF) {
  431. /* EOF
  432. Parse error. Emit the current tag token. Reconsume the EOF
  433. character in the data state. */
  434. $this->emitToken($this->token);
  435. $this->char--;
  436. $this->state = 'data';
  437. } else {
  438. /* Anything else
  439. Append the current input character to the current attribute's name.
  440. Stay in the attribute name state. */
  441. $last = count($this->token['attr']) - 1;
  442. $this->token['attr'][$last]['name'] .= strtolower($char);
  443. $this->state = 'attributeName';
  444. }
  445. }
  446. private function afterAttributeNameState() {
  447. // Consume the next input character:
  448. $this->char++;
  449. $char = $this->character($this->char);
  450. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  451. /* U+0009 CHARACTER TABULATION
  452. U+000A LINE FEED (LF)
  453. U+000B LINE TABULATION
  454. U+000C FORM FEED (FF)
  455. U+0020 SPACE
  456. Stay in the after attribute name state. */
  457. $this->state = 'afterAttributeName';
  458. } elseif($char === '=') {
  459. /* U+003D EQUALS SIGN (=)
  460. Switch to the before attribute value state. */
  461. $this->state = 'beforeAttributeValue';
  462. } elseif($char === '>') {
  463. /* U+003E GREATER-THAN SIGN (>)
  464. Emit the current tag token. Switch to the data state. */
  465. $this->emitToken($this->token);
  466. $this->state = 'data';
  467. } elseif($char === '/' && $this->character($this->char + 1) !== '>') {
  468. /* U+002F SOLIDUS (/)
  469. Parse error unless this is a permitted slash. Switch to the
  470. before attribute name state. */
  471. $this->state = 'beforeAttributeName';
  472. } elseif($this->char === $this->EOF) {
  473. /* EOF
  474. Parse error. Emit the current tag token. Reconsume the EOF
  475. character in the data state. */
  476. $this->emitToken($this->token);
  477. $this->char--;
  478. $this->state = 'data';
  479. } else {
  480. /* Anything else
  481. Start a new attribute in the current tag token. Set that attribute's
  482. name to the current input character, and its value to the empty string.
  483. Switch to the attribute name state. */
  484. $this->token['attr'][] = array(
  485. 'name' => strtolower($char),
  486. 'value' => null
  487. );
  488. $this->state = 'attributeName';
  489. }
  490. }
  491. private function beforeAttributeValueState() {
  492. // Consume the next input character:
  493. $this->char++;
  494. $char = $this->character($this->char);
  495. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  496. /* U+0009 CHARACTER TABULATION
  497. U+000A LINE FEED (LF)
  498. U+000B LINE TABULATION
  499. U+000C FORM FEED (FF)
  500. U+0020 SPACE
  501. Stay in the before attribute value state. */
  502. $this->state = 'beforeAttributeValue';
  503. } elseif($char === '"') {
  504. /* U+0022 QUOTATION MARK (")
  505. Switch to the attribute value (double-quoted) state. */
  506. $this->state = 'attributeValueDoubleQuoted';
  507. } elseif($char === '&') {
  508. /* U+0026 AMPERSAND (&)
  509. Switch to the attribute value (unquoted) state and reconsume
  510. this input character. */
  511. $this->char--;
  512. $this->state = 'attributeValueUnquoted';
  513. } elseif($char === '\'') {
  514. /* U+0027 APOSTROPHE (')
  515. Switch to the attribute value (single-quoted) state. */
  516. $this->state = 'attributeValueSingleQuoted';
  517. } elseif($char === '>') {
  518. /* U+003E GREATER-THAN SIGN (>)
  519. Emit the current tag token. Switch to the data state. */
  520. $this->emitToken($this->token);
  521. $this->state = 'data';
  522. } else {
  523. /* Anything else
  524. Append the current input character to the current attribute's value.
  525. Switch to the attribute value (unquoted) state. */
  526. $last = count($this->token['attr']) - 1;
  527. $this->token['attr'][$last]['value'] .= $char;
  528. $this->state = 'attributeValueUnquoted';
  529. }
  530. }
  531. private function attributeValueDoubleQuotedState() {
  532. // Consume the next input character:
  533. $this->char++;
  534. $char = $this->character($this->char);
  535. if($char === '"') {
  536. /* U+0022 QUOTATION MARK (")
  537. Switch to the before attribute name state. */
  538. $this->state = 'beforeAttributeName';
  539. } elseif($char === '&') {
  540. /* U+0026 AMPERSAND (&)
  541. Switch to the entity in attribute value state. */
  542. $this->entityInAttributeValueState('double');
  543. } elseif($this->char === $this->EOF) {
  544. /* EOF
  545. Parse error. Emit the current tag token. Reconsume the character
  546. in the data state. */
  547. $this->emitToken($this->token);
  548. $this->char--;
  549. $this->state = 'data';
  550. } else {
  551. /* Anything else
  552. Append the current input character to the current attribute's value.
  553. Stay in the attribute value (double-quoted) state. */
  554. $last = count($this->token['attr']) - 1;
  555. $this->token['attr'][$last]['value'] .= $char;
  556. $this->state = 'attributeValueDoubleQuoted';
  557. }
  558. }
  559. private function attributeValueSingleQuotedState() {
  560. // Consume the next input character:
  561. $this->char++;
  562. $char = $this->character($this->char);
  563. if($char === '\'') {
  564. /* U+0022 QUOTATION MARK (')
  565. Switch to the before attribute name state. */
  566. $this->state = 'beforeAttributeName';
  567. } elseif($char === '&') {
  568. /* U+0026 AMPERSAND (&)
  569. Switch to the entity in attribute value state. */
  570. $this->entityInAttributeValueState('single');
  571. } elseif($this->char === $this->EOF) {
  572. /* EOF
  573. Parse error. Emit the current tag token. Reconsume the character
  574. in the data state. */
  575. $this->emitToken($this->token);
  576. $this->char--;
  577. $this->state = 'data';
  578. } else {
  579. /* Anything else
  580. Append the current input character to the current attribute's value.
  581. Stay in the attribute value (single-quoted) state. */
  582. $last = count($this->token['attr']) - 1;
  583. $this->token['attr'][$last]['value'] .= $char;
  584. $this->state = 'attributeValueSingleQuoted';
  585. }
  586. }
  587. private function attributeValueUnquotedState() {
  588. // Consume the next input character:
  589. $this->char++;
  590. $char = $this->character($this->char);
  591. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  592. /* U+0009 CHARACTER TABULATION
  593. U+000A LINE FEED (LF)
  594. U+000B LINE TABULATION
  595. U+000C FORM FEED (FF)
  596. U+0020 SPACE
  597. Switch to the before attribute name state. */
  598. $this->state = 'beforeAttributeName';
  599. } elseif($char === '&') {
  600. /* U+0026 AMPERSAND (&)
  601. Switch to the entity in attribute value state. */
  602. $this->entityInAttributeValueState('non');
  603. } elseif($char === '>') {
  604. /* U+003E GREATER-THAN SIGN (>)
  605. Emit the current tag token. Switch to the data state. */
  606. $this->emitToken($this->token);
  607. $this->state = 'data';
  608. } else {
  609. /* Anything else
  610. Append the current input character to the current attribute's value.
  611. Stay in the attribute value (unquoted) state. */
  612. $last = count($this->token['attr']) - 1;
  613. $this->token['attr'][$last]['value'] .= $char;
  614. $this->state = 'attributeValueUnquoted';
  615. }
  616. }
  617. private function entityInAttributeValueState() {
  618. // Attempt to consume an entity.
  619. $entity = $this->entity();
  620. // If nothing is returned, append a U+0026 AMPERSAND character to the
  621. // current attribute's value. Otherwise, emit the character token that
  622. // was returned.
  623. $char = (!$entity)
  624. ? '&'
  625. : $entity;
  626. $this->emitToken($char);
  627. }
  628. private function bogusCommentState() {
  629. /* Consume every character up to the first U+003E GREATER-THAN SIGN
  630. character (>) or the end of the file (EOF), whichever comes first. Emit
  631. a comment token whose data is the concatenation of all the characters
  632. starting from and including the character that caused the state machine
  633. to switch into the bogus comment state, up to and including the last
  634. consumed character before the U+003E character, if any, or up to the
  635. end of the file otherwise. (If the comment was started by the end of
  636. the file (EOF), the token is empty.) */
  637. $data = $this->characters('^>', $this->char);
  638. $this->emitToken(array(
  639. 'data' => $data,
  640. 'type' => self::COMMENT
  641. ));
  642. $this->char += strlen($data);
  643. /* Switch to the data state. */
  644. $this->state = 'data';
  645. /* If the end of the file was reached, reconsume the EOF character. */
  646. if($this->char === $this->EOF) {
  647. $this->char = $this->EOF - 1;
  648. }
  649. }
  650. private function markupDeclarationOpenState() {
  651. /* If the next two characters are both U+002D HYPHEN-MINUS (-)
  652. characters, consume those two characters, create a comment token whose
  653. data is the empty string, and switch to the comment state. */
  654. if($this->character($this->char + 1, 2) === '--') {
  655. $this->char += 2;
  656. $this->state = 'comment';
  657. $this->token = array(
  658. 'data' => null,
  659. 'type' => self::COMMENT
  660. );
  661. /* Otherwise if the next seven chacacters are a case-insensitive match
  662. for the word "DOCTYPE", then consume those characters and switch to the
  663. DOCTYPE state. */
  664. } elseif(strtolower($this->character($this->char + 1, 7)) === 'doctype') {
  665. $this->char += 7;
  666. $this->state = 'doctype';
  667. /* Otherwise, is is a parse error. Switch to the bogus comment state.
  668. The next character that is consumed, if any, is the first character
  669. that will be in the comment. */
  670. } else {
  671. $this->char++;
  672. $this->state = 'bogusComment';
  673. }
  674. }
  675. private function commentState() {
  676. /* Consume the next input character: */
  677. $this->char++;
  678. $char = $this->char();
  679. /* U+002D HYPHEN-MINUS (-) */
  680. if($char === '-') {
  681. /* Switch to the comment dash state */
  682. $this->state = 'commentDash';
  683. /* EOF */
  684. } elseif($this->char === $this->EOF) {
  685. /* Parse error. Emit the comment token. Reconsume the EOF character
  686. in the data state. */
  687. $this->emitToken($this->token);
  688. $this->char--;
  689. $this->state = 'data';
  690. /* Anything else */
  691. } else {
  692. /* Append the input character to the comment token's data. Stay in
  693. the comment state. */
  694. $this->token['data'] .= $char;
  695. }
  696. }
  697. private function commentDashState() {
  698. /* Consume the next input character: */
  699. $this->char++;
  700. $char = $this->char();
  701. /* U+002D HYPHEN-MINUS (-) */
  702. if($char === '-') {
  703. /* Switch to the comment end state */
  704. $this->state = 'commentEnd';
  705. /* EOF */
  706. } elseif($this->char === $this->EOF) {
  707. /* Parse error. Emit the comment token. Reconsume the EOF character
  708. in the data state. */
  709. $this->emitToken($this->token);
  710. $this->char--;
  711. $this->state = 'data';
  712. /* Anything else */
  713. } else {
  714. /* Append a U+002D HYPHEN-MINUS (-) character and the input
  715. character to the comment token's data. Switch to the comment state. */
  716. $this->token['data'] .= '-'.$char;
  717. $this->state = 'comment';
  718. }
  719. }
  720. private function commentEndState() {
  721. /* Consume the next input character: */
  722. $this->char++;
  723. $char = $this->char();
  724. if($char === '>') {
  725. $this->emitToken($this->token);
  726. $this->state = 'data';
  727. } elseif($char === '-') {
  728. $this->token['data'] .= '-';
  729. } elseif($this->char === $this->EOF) {
  730. $this->emitToken($this->token);
  731. $this->char--;
  732. $this->state = 'data';
  733. } else {
  734. $this->token['data'] .= '--'.$char;
  735. $this->state = 'comment';
  736. }
  737. }
  738. private function doctypeState() {
  739. /* Consume the next input character: */
  740. $this->char++;
  741. $char = $this->char();
  742. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  743. $this->state = 'beforeDoctypeName';
  744. } else {
  745. $this->char--;
  746. $this->state = 'beforeDoctypeName';
  747. }
  748. }
  749. private function beforeDoctypeNameState() {
  750. /* Consume the next input character: */
  751. $this->char++;
  752. $char = $this->char();
  753. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  754. // Stay in the before DOCTYPE name state.
  755. } elseif(preg_match('/^[a-z]$/', $char)) {
  756. $this->token = array(
  757. 'name' => strtoupper($char),
  758. 'type' => self::DOCTYPE,
  759. 'error' => true
  760. );
  761. $this->state = 'doctypeName';
  762. } elseif($char === '>') {
  763. $this->emitToken(array(
  764. 'name' => null,
  765. 'type' => self::DOCTYPE,
  766. 'error' => true
  767. ));
  768. $this->state = 'data';
  769. } elseif($this->char === $this->EOF) {
  770. $this->emitToken(array(
  771. 'name' => null,
  772. 'type' => self::DOCTYPE,
  773. 'error' => true
  774. ));
  775. $this->char--;
  776. $this->state = 'data';
  777. } else {
  778. $this->token = array(
  779. 'name' => $char,
  780. 'type' => self::DOCTYPE,
  781. 'error' => true
  782. );
  783. $this->state = 'doctypeName';
  784. }
  785. }
  786. private function doctypeNameState() {
  787. /* Consume the next input character: */
  788. $this->char++;
  789. $char = $this->char();
  790. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  791. $this->state = 'AfterDoctypeName';
  792. } elseif($char === '>') {
  793. $this->emitToken($this->token);
  794. $this->state = 'data';
  795. } elseif(preg_match('/^[a-z]$/', $char)) {
  796. $this->token['name'] .= strtoupper($char);
  797. } elseif($this->char === $this->EOF) {
  798. $this->emitToken($this->token);
  799. $this->char--;
  800. $this->state = 'data';
  801. } else {
  802. $this->token['name'] .= $char;
  803. }
  804. $this->token['error'] = ($this->token['name'] === 'HTML')
  805. ? false
  806. : true;
  807. }
  808. private function afterDoctypeNameState() {
  809. /* Consume the next input character: */
  810. $this->char++;
  811. $char = $this->char();
  812. if(preg_match('/^[\t\n\x0b\x0c ]$/', $char)) {
  813. // Stay in the DOCTYPE name state.
  814. } elseif($char === '>') {
  815. $this->emitToken($this->token);
  816. $this->state = 'data';
  817. } elseif($this->char === $this->EOF) {
  818. $this->emitToken($this->token);
  819. $this->char--;
  820. $this->state = 'data';
  821. } else {
  822. $this->token['error'] = true;
  823. $this->state = 'bogusDoctype';
  824. }
  825. }
  826. private function bogusDoctypeState() {
  827. /* Consume the next input character: */
  828. $this->char++;
  829. $char = $this->char();
  830. if($char === '>') {
  831. $this->emitToken($this->token);
  832. $this->state = 'data';
  833. } elseif($this->char === $this->EOF) {
  834. $this->emitToken($this->token);
  835. $this->char--;
  836. $this->state = 'data';
  837. } else {
  838. // Stay in the bogus DOCTYPE state.
  839. }
  840. }
  841. private function entity() {
  842. $start = $this->char;
  843. // This section defines how to consume an entity. This definition is
  844. // used when parsing entities in text and in attributes.
  845. // The behaviour depends on the identity of the next character (the
  846. // one immediately after the U+0026 AMPERSAND character):
  847. switch($this->character($this->char + 1)) {
  848. // U+0023 NUMBER SIGN (#)
  849. case '#':
  850. // The behaviour further depends on the character after the
  851. // U+0023 NUMBER SIGN:
  852. switch($this->character($this->char + 1)) {
  853. // U+0078 LATIN SMALL LETTER X
  854. // U+0058 LATIN CAPITAL LETTER X
  855. case 'x':
  856. case 'X':
  857. // Follow the steps below, but using the range of
  858. // characters U+0030 DIGIT ZERO through to U+0039 DIGIT
  859. // NINE, U+0061 LATIN SMALL LETTER A through to U+0066
  860. // LATIN SMALL LETTER F, and U+0041 LATIN CAPITAL LETTER
  861. // A, through to U+0046 LATIN CAPITAL LETTER F (in other
  862. // words, 0-9, A-F, a-f).
  863. $char = 1;
  864. $char_class = '0-9A-Fa-f';
  865. break;
  866. // Anything else
  867. default:
  868. // Follow the steps below, but using the range of
  869. // characters U+0030 DIGIT ZERO through to U+0039 DIGIT
  870. // NINE (i.e. just 0-9).
  871. $char = 0;
  872. $char_class = '0-9';
  873. break;
  874. }
  875. // Consume as many characters as match the range of characters
  876. // given above.
  877. $this->char++;
  878. $e_name = $this->characters($char_class, $this->char + $char + 1);
  879. $entity = $this->character($start, $this->char);
  880. $cond = strlen($e_name) > 0;
  881. // The rest of the parsing happens bellow.
  882. break;
  883. // Anything else
  884. default:
  885. // Consume the maximum number of characters possible, with the
  886. // consumed characters case-sensitively matching one of the
  887. // identifiers in the first column of the entities table.
  888. $e_name = $this->characters('0-9A-Za-z;', $this->char + 1);
  889. $len = strlen($e_name);
  890. for($c = 1; $c <= $len; $c++) {
  891. $id = substr($e_name, 0, $c);
  892. $this->char++;
  893. if(in_array($id, $this->entities)) {
  894. $entity = $id;
  895. break;
  896. }
  897. }
  898. $cond = isset($entity);
  899. // The rest of the parsing happens bellow.
  900. break;
  901. }
  902. if(!$cond) {
  903. // If no match can be made, then this is a parse error. No
  904. // characters are consumed, and nothing is returned.
  905. $this->char = $start;
  906. return false;
  907. }
  908. // Return a character token for the character corresponding to the
  909. // entity name (as given by the second column of the entities table).
  910. return html_entity_decode('&'.$entity.';', ENT_QUOTES, 'UTF-8');
  911. }
  912. private function emitToken($token) {
  913. $emit = $this->tree->emitToken($token);
  914. if(is_int($emit)) {
  915. $this->content_model = $emit;
  916. } elseif($token['type'] === self::ENDTAG) {
  917. $this->content_model = self::PCDATA;
  918. }
  919. }
  920. private function EOF() {
  921. $this->state = null;
  922. $this->tree->emitToken(array(
  923. 'type' => self::EOF
  924. ));
  925. }
  926. }
  927. class HTML5TreeConstructer {
  928. public $stack = array();
  929. private $phase;
  930. private $mode;
  931. private $dom;
  932. private $foster_parent = null;
  933. private $a_formatting = array();
  934. private $head_pointer = null;
  935. private $form_pointer = null;
  936. private $scoping = array('button','caption','html','marquee','object','table','td','th');
  937. private $formatting = array('a','b','big','em','font','i','nobr','s','small','strike','strong','tt','u');
  938. private $special = array('address','area','base','basefont','bgsound',
  939. 'blockquote','body','br','center','col','colgroup','dd','dir','div','dl',
  940. 'dt','embed','fieldset','form','frame','frameset','h1','h2','h3','h4','h5',
  941. 'h6','head','hr','iframe','image','img','input','isindex','li','link',
  942. 'listing','menu','meta','noembed','noframes','noscript','ol','optgroup',
  943. 'option','p','param','plaintext','pre','script','select','spacer','style',
  944. 'tbody','textarea','tfoot','thead','title','tr','ul','wbr');
  945. // The different phases.
  946. const INIT_PHASE = 0;
  947. const ROOT_PHASE = 1;
  948. const MAIN_PHASE = 2;
  949. const END_PHASE = 3;
  950. // The different insertion modes for the main phase.
  951. const BEFOR_HEAD = 0;
  952. const IN_HEAD = 1;
  953. const AFTER_HEAD = 2;
  954. const IN_BODY = 3;
  955. const IN_TABLE = 4;
  956. const IN_CAPTION = 5;
  957. const IN_CGROUP = 6;
  958. const IN_TBODY = 7;
  959. const IN_ROW = 8;
  960. const IN_CELL = 9;
  961. const IN_SELECT = 10;
  962. const AFTER_BODY = 11;
  963. const IN_FRAME = 12;
  964. const AFTR_FRAME = 13;
  965. // The different types of elements.
  966. const SPECIAL = 0;
  967. const SCOPING = 1;
  968. const FORMATTING = 2;
  969. const PHRASING = 3;
  970. const MARKER = 0;
  971. public function __construct() {
  972. $this->phase = self::INIT_PHASE;
  973. $this->mode = self::BEFOR_HEAD;
  974. $this->dom = new DOMDocument;
  975. $this->dom->encoding = 'UTF-8';
  976. $this->dom->preserveWhiteSpace = true;
  977. $this->dom->substituteEntities = true;
  978. $this->dom->strictErrorChecking = false;
  979. }
  980. // Process tag tokens
  981. public function emitToken($token) {
  982. switch($this->phase) {
  983. case self::INIT_PHASE: return $this->initPhase($token); break;
  984. case self::ROOT_PHASE: return $this->rootElementPhase($token); break;
  985. case self::MAIN_PHASE: return $this->mainPhase($token); break;
  986. case self::END_PHASE : return $this->trailingEndPhase($token); break;
  987. }
  988. }
  989. private function initPhase($token) {
  990. /* Initially, the tree construction stage must handle each token
  991. emitted from the tokenisation stage as follows: */
  992. /* A DOCTYPE token that is marked as being in error
  993. A comment token
  994. A start tag token
  995. An end tag token
  996. A character token that is not one of one of U+0009 CHARACTER TABULATION,
  997. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  998. or U+0020 SPACE
  999. An end-of-file token */
  1000. if((isset($token['error']) && $token['error']) ||
  1001. $token['type'] === HTML5::COMMENT ||
  1002. $token['type'] === HTML5::STARTTAG ||
  1003. $token['type'] === HTML5::ENDTAG ||
  1004. $token['type'] === HTML5::EOF ||
  1005. ($token['type'] === HTML5::CHARACTR && isset($token['data']) &&
  1006. !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']))) {
  1007. /* This specification does not define how to handle this case. In
  1008. particular, user agents may ignore the entirety of this specification
  1009. altogether for such documents, and instead invoke special parse modes
  1010. with a greater emphasis on backwards compatibility. */
  1011. $this->phase = self::ROOT_PHASE;
  1012. return $this->rootElementPhase($token);
  1013. /* A DOCTYPE token marked as being correct */
  1014. } elseif(isset($token['error']) && !$token['error']) {
  1015. /* Append a DocumentType node to the Document node, with the name
  1016. attribute set to the name given in the DOCTYPE token (which will be
  1017. "HTML"), and the other attributes specific to DocumentType objects
  1018. set to null, empty lists, or the empty string as appropriate. */
  1019. $doctype = new DOMDocumentType(null, null, 'HTML');
  1020. /* Then, switch to the root element phase of the tree construction
  1021. stage. */
  1022. $this->phase = self::ROOT_PHASE;
  1023. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  1024. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  1025. or U+0020 SPACE */
  1026. } elseif(isset($token['data']) && preg_match('/^[\t\n\x0b\x0c ]+$/',
  1027. $token['data'])) {
  1028. /* Append that character to the Document node. */
  1029. $text = $this->dom->createTextNode($token['data']);
  1030. $this->dom->appendChild($text);
  1031. }
  1032. }
  1033. private function rootElementPhase($token) {
  1034. /* After the initial phase, as each token is emitted from the tokenisation
  1035. stage, it must be processed as described in this section. */
  1036. /* A DOCTYPE token */
  1037. if($token['type'] === HTML5::DOCTYPE) {
  1038. // Parse error. Ignore the token.
  1039. /* A comment token */
  1040. } elseif($token['type'] === HTML5::COMMENT) {
  1041. /* Append a Comment node to the Document object with the data
  1042. attribute set to the data given in the comment token. */
  1043. $comment = $this->dom->createComment($token['data']);
  1044. $this->dom->appendChild($comment);
  1045. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  1046. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  1047. or U+0020 SPACE */
  1048. } elseif($token['type'] === HTML5::CHARACTR &&
  1049. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  1050. /* Append that character to the Document node. */
  1051. $text = $this->dom->createTextNode($token['data']);
  1052. $this->dom->appendChild($text);
  1053. /* A character token that is not one of U+0009 CHARACTER TABULATION,
  1054. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED
  1055. (FF), or U+0020 SPACE
  1056. A start tag token
  1057. An end tag token
  1058. An end-of-file token */
  1059. } elseif(($token['type'] === HTML5::CHARACTR &&
  1060. !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||
  1061. $token['type'] === HTML5::STARTTAG ||
  1062. $token['type'] === HTML5::ENDTAG ||
  1063. $token['type'] === HTML5::EOF) {
  1064. /* Create an HTMLElement node with the tag name html, in the HTML
  1065. namespace. Append it to the Document object. Switch to the main
  1066. phase and reprocess the current token. */
  1067. $html = $this->dom->createElement('html');
  1068. $this->dom->appendChild($html);
  1069. $this->stack[] = $html;
  1070. $this->phase = self::MAIN_PHASE;
  1071. return $this->mainPhase($token);
  1072. }
  1073. }
  1074. private function mainPhase($token) {
  1075. /* Tokens in the main phase must be handled as follows: */
  1076. /* A DOCTYPE token */
  1077. if($token['type'] === HTML5::DOCTYPE) {
  1078. // Parse error. Ignore the token.
  1079. /* A start tag token with the tag name "html" */
  1080. } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'html') {
  1081. /* If this start tag token was not the first start tag token, then
  1082. it is a parse error. */
  1083. /* For each attribute on the token, check to see if the attribute
  1084. is already present on the top element of the stack of open elements.
  1085. If it is not, add the attribute and its corresponding value to that
  1086. element. */
  1087. foreach($token['attr'] as $attr) {
  1088. if(!$this->stack[0]->hasAttribute($attr['name'])) {
  1089. $this->stack[0]->setAttribute($attr['name'], $attr['value']);
  1090. }
  1091. }
  1092. /* An end-of-file token */
  1093. } elseif($token['type'] === HTML5::EOF) {
  1094. /* Generate implied end tags. */
  1095. $this->generateImpliedEndTags();
  1096. /* Anything else. */
  1097. } else {
  1098. /* Depends on the insertion mode: */
  1099. switch($this->mode) {
  1100. case self::BEFOR_HEAD: return $this->beforeHead($token); break;
  1101. case self::IN_HEAD: return $this->inHead($token); break;
  1102. case self::AFTER_HEAD: return $this->afterHead($token); break;
  1103. case self::IN_BODY: return $this->inBody($token); break;
  1104. case self::IN_TABLE: return $this->inTable($token); break;
  1105. case self::IN_CAPTION: return $this->inCaption($token); break;
  1106. case self::IN_CGROUP: return $this->inColumnGroup($token); break;
  1107. case self::IN_TBODY: return $this->inTableBody($token); break;
  1108. case self::IN_ROW: return $this->inRow($token); break;
  1109. case self::IN_CELL: return $this->inCell($token); break;
  1110. case self::IN_SELECT: return $this->inSelect($token); break;
  1111. case self::AFTER_BODY: return $this->afterBody($token); break;
  1112. case self::IN_FRAME: return $this->inFrameset($token); break;
  1113. case self::AFTR_FRAME: return $this->afterFrameset($token); break;
  1114. case self::END_PHASE: return $this->trailingEndPhase($token); break;
  1115. }
  1116. }
  1117. }
  1118. private function beforeHead($token) {
  1119. /* Handle the token as follows: */
  1120. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  1121. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  1122. or U+0020 SPACE */
  1123. if($token['type'] === HTML5::CHARACTR &&
  1124. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  1125. /* Append the character to the current node. */
  1126. $this->insertText($token['data']);
  1127. /* A comment token */
  1128. } elseif($token['type'] === HTML5::COMMENT) {
  1129. /* Append a Comment node to the current node with the data attribute
  1130. set to the data given in the comment token. */
  1131. $this->insertComment($token['data']);
  1132. /* A start tag token with the tag name "head" */
  1133. } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') {
  1134. /* Create an element for the token, append the new element to the
  1135. current node and push it onto the stack of open elements. */
  1136. $element = $this->insertElement($token);
  1137. /* Set the head element pointer to this new element node. */
  1138. $this->head_pointer = $element;
  1139. /* Change the insertion mode to "in head". */
  1140. $this->mode = self::IN_HEAD;
  1141. /* A start tag token whose tag name is one of: "base", "link", "meta",
  1142. "script", "style", "title". Or an end tag with the tag name "html".
  1143. Or a character token that is not one of U+0009 CHARACTER TABULATION,
  1144. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  1145. or U+0020 SPACE. Or any other start tag token */
  1146. } elseif($token['type'] === HTML5::STARTTAG ||
  1147. ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') ||
  1148. ($token['type'] === HTML5::CHARACTR && !preg_match('/^[\t\n\x0b\x0c ]$/',
  1149. $token['data']))) {
  1150. /* Act as if a start tag token with the tag name "head" and no
  1151. attributes had been seen, then reprocess the current token. */
  1152. $this->beforeHead(array(
  1153. 'name' => 'head',
  1154. 'type' => HTML5::STARTTAG,
  1155. 'attr' => array()
  1156. ));
  1157. return $this->inHead($token);
  1158. /* Any other end tag */
  1159. } elseif($token['type'] === HTML5::ENDTAG) {
  1160. /* Parse error. Ignore the token. */
  1161. }
  1162. }
  1163. private function inHead($token) {
  1164. /* Handle the token as follows: */
  1165. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  1166. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  1167. or U+0020 SPACE.
  1168. THIS DIFFERS FROM THE SPEC: If the current node is either a title, style
  1169. or script element, append the character to the current node regardless
  1170. of its content. */
  1171. if(($token['type'] === HTML5::CHARACTR &&
  1172. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || (
  1173. $token['type'] === HTML5::CHARACTR && in_array(end($this->stack)->nodeName,
  1174. array('title', 'style', 'script')))) {
  1175. /* Append the character to the current node. */
  1176. $this->insertText($token['data']);
  1177. /* A comment token */
  1178. } elseif($token['type'] === HTML5::COMMENT) {
  1179. /* Append a Comment node to the current node with the data attribute
  1180. set to the data given in the comment token. */
  1181. $this->insertComment($token['data']);
  1182. } elseif($token['type'] === HTML5::ENDTAG &&
  1183. in_array($token['name'], array('title', 'style', 'script'))) {
  1184. array_pop($this->stack);
  1185. return HTML5::PCDATA;
  1186. /* A start tag with the tag name "title" */
  1187. } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'title') {
  1188. /* Create an element for the token and append the new element to the
  1189. node pointed to by the head element pointer, or, if that is null
  1190. (innerHTML case), to the current node. */
  1191. if($this->head_pointer !== null) {
  1192. $element = $this->insertElement($token, false);
  1193. $this->head_pointer->appendChild($element);
  1194. } else {
  1195. $element = $this->insertElement($token);
  1196. }
  1197. /* Switch the tokeniser's content model flag to the RCDATA state. */
  1198. return HTML5::RCDATA;
  1199. /* A start tag with the tag name "style" */
  1200. } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'style') {
  1201. /* Create an element for the token and append the new element to the
  1202. node pointed to by the head element pointer, or, if that is null
  1203. (innerHTML case), to the current node. */
  1204. if($this->head_pointer !== null) {
  1205. $element = $this->insertElement($token, false);
  1206. $this->head_pointer->appendChild($element);
  1207. } else {
  1208. $this->insertElement($token);
  1209. }
  1210. /* Switch the tokeniser's content model flag to the CDATA state. */
  1211. return HTML5::CDATA;
  1212. /* A start tag with the tag name "script" */
  1213. } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'script') {
  1214. /* Create an element for the token. */
  1215. $element = $this->insertElement($token, false);
  1216. $this->head_pointer->appendChild($element);
  1217. /* Switch the tokeniser's content model flag to the CDATA state. */
  1218. return HTML5::CDATA;
  1219. /* A start tag with the tag name "base", "link", or "meta" */
  1220. } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
  1221. array('base', 'link', 'meta'))) {
  1222. /* Create an element for the token and append the new element to the
  1223. node pointed to by the head element pointer, or, if that is null
  1224. (innerHTML case), to the current node. */
  1225. if($this->head_pointer !== null) {
  1226. $element = $this->insertElement($token, false);
  1227. $this->head_pointer->appendChild($element);
  1228. array_pop($this->stack);
  1229. } else {
  1230. $this->insertElement($token);
  1231. }
  1232. /* An end tag with the tag name "head" */
  1233. } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'head') {
  1234. /* If the current node is a head element, pop the current node off
  1235. the stack of open elements. */
  1236. if($this->head_pointer->isSameNode(end($this->stack))) {
  1237. array_pop($this->stack);
  1238. /* Otherwise, this is a parse error. */
  1239. } else {
  1240. // k
  1241. }
  1242. /* Change the insertion mode to "after head". */
  1243. $this->mode = self::AFTER_HEAD;
  1244. /* A start tag with the tag name "head" or an end tag except "html". */
  1245. } elseif(($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') ||
  1246. ($token['type'] === HTML5::ENDTAG && $token['name'] !== 'html')) {
  1247. // Parse error. Ignore the token.
  1248. /* Anything else */
  1249. } else {
  1250. /* If the current node is a head element, act as if an end tag
  1251. token with the tag name "head" had been seen. */
  1252. if($this->head_pointer->isSameNode(end($this->stack))) {
  1253. $this->inHead(array(
  1254. 'name' => 'head',
  1255. 'type' => HTML5::ENDTAG
  1256. ));
  1257. /* Otherwise, change the insertion mode to "after head". */
  1258. } else {
  1259. $this->mode = self::AFTER_HEAD;
  1260. }
  1261. /* Then, reprocess the current token. */
  1262. return $this->afterHead($token);
  1263. }
  1264. }
  1265. private function afterHead($token) {
  1266. /* Handle the token as follows: */
  1267. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  1268. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  1269. or U+0020 SPACE */
  1270. if($token['type'] === HTML5::CHARACTR &&
  1271. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  1272. /* Append the character to the current node. */
  1273. $this->insertText($token['data']);
  1274. /* A comment token */
  1275. } elseif($token['type'] === HTML5::COMMENT) {
  1276. /* Append a Comment node to the current node with the data attribute
  1277. set to the data given in the comment token. */
  1278. $this->insertComment($token['data']);
  1279. /* A start tag token with the tag name "body" */
  1280. } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'body') {
  1281. /* Insert a body element for the token. */
  1282. $this->insertElement($token);
  1283. /* Change the insertion mode to "in body". */
  1284. $this->mode = self::IN_BODY;
  1285. /* A start tag token with the tag name "frameset" */
  1286. } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'frameset') {
  1287. /* Insert a frameset element for the token. */
  1288. $this->insertElement($token);
  1289. /* Change the insertion mode to "in frameset". */
  1290. $this->mode = self::IN_FRAME;
  1291. /* A start tag token whose tag name is one of: "base", "link", "meta",
  1292. "script", "style", "title" */
  1293. } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
  1294. array('base', 'link', 'meta', 'script', 'style', 'title'))) {
  1295. /* Parse error. Switch the insertion mode back to "in head" and
  1296. reprocess the token. */
  1297. $this->mode = self::IN_HEAD;
  1298. return $this->inHead($token);
  1299. /* Anything else */
  1300. } else {
  1301. /* Act as if a start tag token with the tag name "body" and no
  1302. attributes had been seen, and then reprocess the current token. */
  1303. $this->afterHead(array(
  1304. 'name' => 'body',
  1305. 'type' => HTML5::STARTTAG,
  1306. 'attr' => array()
  1307. ));
  1308. return $this->inBody($token);
  1309. }
  1310. }
  1311. private function inBody($token) {
  1312. /* Handle the token as follows: */
  1313. switch($token['type']) {
  1314. /* A character token */
  1315. case HTML5::CHARACTR:
  1316. /* Reconstruct the active formatting elements, if any. */
  1317. $this->reconstructActiveFormattingElements();
  1318. /* Append the token's character to the current node. */
  1319. $this->insertText($token['data']);
  1320. break;
  1321. /* A comment token */
  1322. case HTML5::COMMENT:
  1323. /* Append a Comment node to the current node with the data
  1324. attribute set to the data given in the comment token. */
  1325. $this->insertComment($token['data']);
  1326. break;
  1327. case HTML5::STARTTAG:
  1328. switch($token['name']) {
  1329. /* A start tag token whose tag name is one of: "script",
  1330. "style" */
  1331. case 'script': case 'style':
  1332. /* Process the token as if the insertion mode had been "in
  1333. head". */
  1334. return $this->inHead($token);
  1335. break;
  1336. /* A start tag token whose tag name is one of: "base", "link",
  1337. "meta", "title" */
  1338. case 'base': case 'link': case 'meta': case 'title':
  1339. /* Parse error. Process the token as if the insertion mode
  1340. had been "in head". */
  1341. return $this->inHead($token);
  1342. break;
  1343. /* A start tag token with the tag name "body" */
  1344. case 'body':
  1345. /* Parse error. If the second element on the stack of open
  1346. elements is not a body element, or, if the stack of open
  1347. elements has only one node on it, then ignore the token.
  1348. (innerHTML case) */
  1349. if(count($this->stack) === 1 || $this->stack[1]->nodeName !== 'body') {
  1350. // Ignore
  1351. /* Otherwise, for each attribute on the token, check to see
  1352. if the attribute is already present on the body element (the
  1353. second element) on the stack of open elements. If it is not,
  1354. add the attribute and its corresponding value to that
  1355. element. */
  1356. } else {
  1357. foreach($token['attr'] as $attr) {
  1358. if(!$this->stack[1]->hasAttribute($attr['name'])) {
  1359. $this->stack[1]->setAttribute($attr['name'], $attr['value']);
  1360. }
  1361. }
  1362. }
  1363. break;
  1364. /* A start tag whose tag name is one of: "address",
  1365. "blockquote", "center", "dir", "div", "dl", "fieldset",
  1366. "listing", "menu", "ol", "p", "ul" */
  1367. case 'address': case 'blockquote': case 'center': case 'dir':
  1368. case 'div': case 'dl': case 'fieldset': case 'listing':
  1369. case 'menu': case 'ol': case 'p': case 'ul':
  1370. /* If the stack of open elements has a p element in scope,
  1371. then act as if an end tag with the tag name p had been
  1372. seen. */
  1373. if($this->elementInScope('p')) {
  1374. $this->emitToken(array(
  1375. 'name' => 'p',
  1376. 'type' => HTML5::ENDTAG
  1377. ));
  1378. }
  1379. /* Insert an HTML element for the token. */
  1380. $this->insertElement($token);
  1381. break;
  1382. /* A start tag whose tag name is "form" */
  1383. case 'form':
  1384. /* If the form element pointer is not null, ignore the
  1385. token with a parse error. */
  1386. if($this->form_pointer !== null) {
  1387. // Ignore.
  1388. /* Otherwise: */
  1389. } else {
  1390. /* If the stack of open elements has a p element in
  1391. scope, then act as if an end tag with the tag name p
  1392. had been seen. */
  1393. if($this->elementInScope('p')) {
  1394. $this->emitToken(array(
  1395. 'name' => 'p',
  1396. 'type' => HTML5::ENDTAG
  1397. ));
  1398. }
  1399. /* Insert an HTML element for the token, and set the
  1400. form element pointer to point to the element created. */
  1401. $element = $this->insertElement($token);
  1402. $this->form_pointer = $element;
  1403. }
  1404. break;
  1405. /* A start tag whose tag name is "li", "dd" or "dt" */
  1406. case 'li': case 'dd': case 'dt':
  1407. /* If the stack of open elements has a p element in scope,
  1408. then act as if an end tag with the tag name p had been
  1409. seen. */
  1410. if($this->elementInScope('p')) {
  1411. $this->emitToken(array(
  1412. 'name' => 'p',
  1413. 'type' => HTML5::ENDTAG
  1414. ));
  1415. }
  1416. $stack_length = count($this->stack) - 1;
  1417. for($n = $stack_length; 0 <= $n; $n--) {
  1418. /* 1. Initialise node to be the current node (the
  1419. bottommost node of the stack). */
  1420. $stop = false;
  1421. $node = $this->stack[$n];
  1422. $cat = $this->getElementCategory($node->tagName);
  1423. /* 2. If node is an li, dd or dt element, then pop all
  1424. the nodes from the current node up to node, including
  1425. node, then stop this algorithm. */
  1426. if($token['name'] === $node->tagName || ($token['name'] !== 'li'
  1427. && ($node->tagName === 'dd' || $node->tagName === 'dt'))) {
  1428. for($x = $stack_length; $x >= $n ; $x--) {
  1429. array_pop($this->stack);
  1430. }
  1431. break;
  1432. }
  1433. /* 3. If node is not in the formatting category, and is
  1434. not in the phrasing category, and is not an address or
  1435. div element, then stop this algorithm. */
  1436. if($cat !== self::FORMATTING && $cat !== self::PHRASING &&
  1437. $node->tagName !== 'address' && $node->tagName !== 'div') {
  1438. break;
  1439. }
  1440. }
  1441. /* Finally, insert an HTML element with the same tag
  1442. name as the token's. */
  1443. $this->insertElement($token);
  1444. break;
  1445. /* A start tag token whose tag name is "plaintext" */
  1446. case 'plaintext':
  1447. /* If the stack of open elements has a p element in scope,
  1448. then act as if an end tag with the tag name p had been
  1449. seen. */
  1450. if($this->elementInScope('p')) {
  1451. $this->emitToken(array(
  1452. 'name' => 'p',
  1453. 'type' => HTML5::ENDTAG
  1454. ));
  1455. }
  1456. /* Insert an HTML element for the token. */
  1457. $this->insertElement($token);
  1458. return HTML5::PLAINTEXT;
  1459. break;
  1460. /* A start tag whose tag name is one of: "h1", "h2", "h3", "h4",
  1461. "h5", "h6" */
  1462. case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':
  1463. /* If the stack of open elements has a p element in scope,
  1464. then act as if an end tag with the tag name p had been seen. */
  1465. if($this->elementInScope('p')) {
  1466. $this->emitToken(array(
  1467. 'name' => 'p',
  1468. 'type' => HTML5::ENDTAG
  1469. ));
  1470. }
  1471. /* If the stack of open elements has in scope an element whose
  1472. tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then
  1473. this is a parse error; pop elements from the stack until an
  1474. element with one of those tag names has been popped from the
  1475. stack. */
  1476. while($this->elementInScope(array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))) {
  1477. array_pop($this->stack);
  1478. }
  1479. /* Insert an HTML element for the token. */
  1480. $this->insertElement($token);
  1481. break;
  1482. /* A start tag whose tag name is "a" */
  1483. case 'a':
  1484. /* If the list of active formatting elements contains
  1485. an element whose tag name is "a" between the end of the
  1486. list and the last marker on the list (or the start of
  1487. the list if there is no marker on the list), then this
  1488. is a parse error; act as if an end tag with the tag name
  1489. "a" had been seen, then remove that element from the list
  1490. of active formatting elements and the stack of open
  1491. elements if the end tag didn't already remove it (it
  1492. might not have if the element is not in table scope). */
  1493. $leng = count($this->a_formatting);
  1494. for($n = $leng - 1; $n >= 0; $n--) {
  1495. if($this->a_formatting[$n] === self::MARKER) {
  1496. break;
  1497. } elseif($this->a_formatting[$n]->nodeName === 'a') {
  1498. $this->emitToken(array(
  1499. 'name' => 'a',
  1500. 'type' => HTML5::ENDTAG
  1501. ));
  1502. break;
  1503. }
  1504. }
  1505. /* Reconstruct the active formatting elements, if any. */
  1506. $this->reconstructActiveFormattingElements();
  1507. /* Insert an HTML element for the token. */
  1508. $el = $this->insertElement($token);
  1509. /* Add that element to the list of active formatting
  1510. elements. */
  1511. $this->a_formatting[] = $el;
  1512. break;
  1513. /* A start tag whose tag name is one of: "b", "big", "em", "font",
  1514. "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */
  1515. case 'b': case 'big': case 'em': case 'font': case 'i':
  1516. case 'nobr': case 's': case 'small': case 'strike':
  1517. case 'strong': case 'tt': case 'u':
  1518. /* Reconstruct the active formatting elements, if any. */
  1519. $this->reconstructActiveFormattingElements();
  1520. /* Insert an HTML element for the token. */
  1521. $el = $this->insertElement($token);
  1522. /* Add that element to the list of active formatting
  1523. elements. */
  1524. $this->a_formatting[] = $el;
  1525. break;
  1526. /* A start tag token whose tag name is "button" */
  1527. case 'button':
  1528. /* If the stack of open elements has a button element in scope,
  1529. then this is a parse error; act as if an end tag with the tag
  1530. name "button" had been seen, then reprocess the token. (We don't
  1531. do that. Unnecessary.) */
  1532. if($this->elementInScope('button')) {
  1533. $this->inBody(array(
  1534. 'name' => 'button',
  1535. 'type' => HTML5::ENDTAG
  1536. ));
  1537. }
  1538. /* Reconstruct the active formatting elements, if any. */
  1539. $this->reconstructActiveFormattingElements();
  1540. /* Insert an HTML element for the token. */
  1541. $this->insertElement($token);
  1542. /* Insert a marker at the end of the list of active
  1543. formatting elements. */
  1544. $this->a_formatting[] = self::MARKER;
  1545. break;
  1546. /* A start tag token whose tag name is one of: "marquee", "object" */
  1547. case 'marquee': case 'object':
  1548. /* Reconstruct the active formatting elements, if any. */
  1549. $this->reconstructActiveFormattingElements();
  1550. /* Insert an HTML element for the token. */
  1551. $this->insertElement($token);
  1552. /* Insert a marker at the end of the list of active
  1553. formatting elements. */
  1554. $this->a_formatting[] = self::MARKER;
  1555. break;
  1556. /* A start tag token whose tag name is "xmp" */
  1557. case 'xmp':
  1558. /* Reconstruct the active formatting elements, if any. */
  1559. $this->reconstructActiveFormattingElements();
  1560. /* Insert an HTML element for the token. */
  1561. $this->insertElement($token);
  1562. /* Switch the content model flag to the CDATA state. */
  1563. return HTML5::CDATA;
  1564. break;
  1565. /* A start tag whose tag name is "table" */
  1566. case 'table':
  1567. /* If the stack of open elements has a p element in scope,
  1568. then act as if an end tag with the tag name p had been seen. */
  1569. if($this->elementInScope('p')) {
  1570. $this->emitToken(array(
  1571. 'name' => 'p',
  1572. 'type' => HTML5::ENDTAG
  1573. ));
  1574. }
  1575. /* Insert an HTML element for the token. */
  1576. $this->insertElement($token);
  1577. /* Change the insertion mode to "in table". */
  1578. $this->mode = self::IN_TABLE;
  1579. break;
  1580. /* A start tag whose tag name is one of: "area", "basefont",
  1581. "bgsound", "br", "embed", "img", "param", "spacer", "wbr" */
  1582. case 'area': case 'basefont': case 'bgsound': case 'br':
  1583. case 'embed': case 'img': case 'param': case 'spacer':
  1584. case 'wbr':
  1585. /* Reconstruct the active formatting elements, if any. */
  1586. $this->reconstructActiveFormattingElements();
  1587. /* Insert an HTML element for the token. */
  1588. $this->insertElement($token);
  1589. /* Immediately pop the current node off the stack of open elements. */
  1590. array_pop($this->stack);
  1591. break;
  1592. /* A start tag whose tag name is "hr" */
  1593. case 'hr':
  1594. /* If the stack of open elements has a p element in scope,
  1595. then act as if an end tag with the tag name p had been seen. */
  1596. if($this->elementInScope('p')) {
  1597. $this->emitToken(array(
  1598. 'name' => 'p',
  1599. 'type' => HTML5::ENDTAG
  1600. ));
  1601. }
  1602. /* Insert an HTML element for the token. */
  1603. $this->insertElement($token);
  1604. /* Immediately pop the current node off the stack of open elements. */
  1605. array_pop($this->stack);
  1606. break;
  1607. /* A start tag whose tag name is "image" */
  1608. case 'image':
  1609. /* Parse error. Change the token's tag name to "img" and
  1610. reprocess it. (Don't ask.) */
  1611. $token['name'] = 'img';
  1612. return $this->inBody($token);
  1613. break;
  1614. /* A start tag whose tag name is "input" */
  1615. case 'input':
  1616. /* Reconstruct the active formatting elements, if any. */
  1617. $this->reconstructActiveFormattingElements();
  1618. /* Insert an input element for the token. */
  1619. $element = $this->insertElement($token, false);
  1620. /* If the form element pointer is not null, then associate the
  1621. input element with the form element pointed to by the form
  1622. element pointer. */
  1623. $this->form_pointer !== null
  1624. ? $this->form_pointer->appendChild($element)
  1625. : end($this->stack)->appendChild($element);
  1626. /* Pop that input element off the stack of open elements. */
  1627. array_pop($this->stack);
  1628. break;
  1629. /* A start tag whose tag name is "isindex" */
  1630. case 'isindex':
  1631. /* Parse error. */
  1632. // w/e
  1633. /* If the form element pointer is not null,
  1634. then ignore the token. */
  1635. if($this->form_pointer === null) {
  1636. /* Act as if a start tag token with the tag name "form" had
  1637. been seen. */
  1638. $this->inBody(array(
  1639. 'name' => 'body',
  1640. 'type' => HTML5::STARTTAG,
  1641. 'attr' => array()
  1642. ));
  1643. /* Act as if a start tag token with the tag name "hr" had
  1644. been seen. */
  1645. $this->inBody(array(
  1646. 'name' => 'hr',
  1647. 'type' => HTML5::STARTTAG,
  1648. 'attr' => array()
  1649. ));
  1650. /* Act as if a start tag token with the tag name "p" had
  1651. been seen. */
  1652. $this->inBody(array(
  1653. 'name' => 'p',
  1654. 'type' => HTML5::STARTTAG,
  1655. 'attr' => array()
  1656. ));
  1657. /* Act as if a start tag token with the tag name "label"
  1658. had been seen. */
  1659. $this->inBody(array(
  1660. 'name' => 'label',
  1661. 'type' => HTML5::STARTTAG,
  1662. 'attr' => array()
  1663. ));
  1664. /* Act as if a stream of character tokens had been seen. */
  1665. $this->insertText('This is a searchable index. '.
  1666. 'Insert your search keywords here: ');
  1667. /* Act as if a start tag token with the tag name "input"
  1668. had been seen, with all the attributes from the "isindex"
  1669. token, except with the "name" attribute set to the value
  1670. "isindex" (ignoring any explicit "name" attribute). */
  1671. $attr = $token['attr'];
  1672. $attr[] = array('name' => 'name', 'value' => 'isindex');
  1673. $this->inBody(array(
  1674. 'name' => 'input',
  1675. 'type' => HTML5::STARTTAG,
  1676. 'attr' => $attr
  1677. ));
  1678. /* Act as if a stream of character tokens had been seen
  1679. (see below for what they should say). */
  1680. $this->insertText('This is a searchable index. '.
  1681. 'Insert your search keywords here: ');
  1682. /* Act as if an end tag token with the tag name "label"
  1683. had been seen. */
  1684. $this->inBody(array(
  1685. 'name' => 'label',
  1686. 'type' => HTML5::ENDTAG
  1687. ));
  1688. /* Act as if an end tag token with the tag name "p" had
  1689. been seen. */
  1690. $this->inBody(array(
  1691. 'name' => 'p',
  1692. 'type' => HTML5::ENDTAG
  1693. ));
  1694. /* Act as if a start tag token with the tag name "hr" had
  1695. been seen. */
  1696. $this->inBody(array(
  1697. 'name' => 'hr',
  1698. 'type' => HTML5::ENDTAG
  1699. ));
  1700. /* Act as if an end tag token with the tag name "form" had
  1701. been seen. */
  1702. $this->inBody(array(
  1703. 'name' => 'form',
  1704. 'type' => HTML5::ENDTAG
  1705. ));
  1706. }
  1707. break;
  1708. /* A start tag whose tag name is "textarea" */
  1709. case 'textarea':
  1710. $this->insertElement($token);
  1711. /* Switch the tokeniser's content model flag to the
  1712. RCDATA state. */
  1713. return HTML5::RCDATA;
  1714. break;
  1715. /* A start tag whose tag name is one of: "iframe", "noembed",
  1716. "noframes" */
  1717. case 'iframe': case 'noembed': case 'noframes':
  1718. $this->insertElement($token);
  1719. /* Switch the tokeniser's content model flag to the CDATA state. */
  1720. return HTML5::CDATA;
  1721. break;
  1722. /* A start tag whose tag name is "select" */
  1723. case 'select':
  1724. /* Reconstruct the active formatting elements, if any. */
  1725. $this->reconstructActiveFormattingElements();
  1726. /* Insert an HTML element for the token. */
  1727. $this->insertElement($token);
  1728. /* Change the insertion mode to "in select". */
  1729. $this->mode = self::IN_SELECT;
  1730. break;
  1731. /* A start or end tag whose tag name is one of: "caption", "col",
  1732. "colgroup", "frame", "frameset", "head", "option", "optgroup",
  1733. "tbody", "td", "tfoot", "th", "thead", "tr". */
  1734. case 'caption': case 'col': case 'colgroup': case 'frame':
  1735. case 'frameset': case 'head': case 'option': case 'optgroup':
  1736. case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead':
  1737. case 'tr':
  1738. // Parse error. Ignore the token.
  1739. break;
  1740. /* A start or end tag whose tag name is one of: "event-source",
  1741. "section", "nav", "article", "aside", "header", "footer",
  1742. "datagrid", "command" */
  1743. case 'event-source': case 'section': case 'nav': case 'article':
  1744. case 'aside': case 'header': case 'footer': case 'datagrid':
  1745. case 'command':
  1746. // Work in progress!
  1747. break;
  1748. /* A start tag token not covered by the previous entries */
  1749. default:
  1750. /* Reconstruct the active formatting elements, if any. */
  1751. $this->reconstructActiveFormattingElements();
  1752. $this->insertElement($token);
  1753. break;
  1754. }
  1755. break;
  1756. case HTML5::ENDTAG:
  1757. switch($token['name']) {
  1758. /* An end tag with the tag name "body" */
  1759. case 'body':
  1760. /* If the second element in the stack of open elements is
  1761. not a body element, this is a parse error. Ignore the token.
  1762. (innerHTML case) */
  1763. if(count($this->stack) < 2 || $this->stack[1]->nodeName !== 'body') {
  1764. // Ignore.
  1765. /* If the current node is not the body element, then this
  1766. is a parse error. */
  1767. } elseif(end($this->stack)->nodeName !== 'body') {
  1768. // Parse error.
  1769. }
  1770. /* Change the insertion mode to "after body". */
  1771. $this->mode = self::AFTER_BODY;
  1772. break;
  1773. /* An end tag with the tag name "html" */
  1774. case 'html':
  1775. /* Act as if an end tag with tag name "body" had been seen,
  1776. then, if that token wasn't ignored, reprocess the current
  1777. token. */
  1778. $this->inBody(array(
  1779. 'name' => 'body',
  1780. 'type' => HTML5::ENDTAG
  1781. ));
  1782. return $this->afterBody($token);
  1783. break;
  1784. /* An end tag whose tag name is one of: "address", "blockquote",
  1785. "center", "dir", "div", "dl", "fieldset", "listing", "menu",
  1786. "ol", "pre", "ul" */
  1787. case 'address': case 'blockquote': case 'center': case 'dir':
  1788. case 'div': case 'dl': case 'fieldset': case 'listing':
  1789. case 'menu': case 'ol': case 'pre': case 'ul':
  1790. /* If the stack of open elements has an element in scope
  1791. with the same tag name as that of the token, then generate
  1792. implied end tags. */
  1793. if($this->elementInScope($token['name'])) {
  1794. $this->generateImpliedEndTags();
  1795. /* Now, if the current node is not an element with
  1796. the same tag name as that of the token, then this
  1797. is a parse error. */
  1798. // w/e
  1799. /* If the stack of open elements has an element in
  1800. scope with the same tag name as that of the token,
  1801. then pop elements from this stack until an element
  1802. with that tag name has been popped from the stack. */
  1803. for($n = count($this->stack) - 1; $n >= 0; $n--) {
  1804. if($this->stack[$n]->nodeName === $token['name']) {
  1805. $n = -1;
  1806. }
  1807. array_pop($this->stack);
  1808. }
  1809. }
  1810. break;
  1811. /* An end tag whose tag name is "form" */
  1812. case 'form':
  1813. /* If the stack of open elements has an element in scope
  1814. with the same tag name as that of the token, then generate
  1815. implied end tags. */
  1816. if($this->elementInScope($token['name'])) {
  1817. $this->generateImpliedEndTags();
  1818. }
  1819. if(end($this->stack)->nodeName !== $token['name']) {
  1820. /* Now, if the current node is not an element with the
  1821. same tag name as that of the token, then this is a parse
  1822. error. */
  1823. // w/e
  1824. } else {
  1825. /* Otherwise, if the current node is an element with
  1826. the same tag name as that of the token pop that element
  1827. from the stack. */
  1828. array_pop($this->stack);
  1829. }
  1830. /* In any case, set the form element pointer to null. */
  1831. $this->form_pointer = null;
  1832. break;
  1833. /* An end tag whose tag name is "p" */
  1834. case 'p':
  1835. /* If the stack of open elements has a p element in scope,
  1836. then generate implied end tags, except for p elements. */
  1837. if($this->elementInScope('p')) {
  1838. $this->generateImpliedEndTags(array('p'));
  1839. /* If the current node is not a p element, then this is
  1840. a parse error. */
  1841. // k
  1842. /* If the stack of open elements has a p element in
  1843. scope, then pop elements from this stack until the stack
  1844. no longer has a p element in scope. */
  1845. for($n = count($this->stack) - 1; $n >= 0; $n--) {
  1846. if($this->elementInScope('p')) {
  1847. array_pop($this->stack);
  1848. } else {
  1849. break;
  1850. }
  1851. }
  1852. }
  1853. break;
  1854. /* An end tag whose tag name is "dd", "dt", or "li" */
  1855. case 'dd': case 'dt': case 'li':
  1856. /* If the stack of open elements has an element in scope
  1857. whose tag name matches the tag name of the token, then
  1858. generate implied end tags, except for elements with the
  1859. same tag name as the token. */
  1860. if($this->elementInScope($token['name'])) {
  1861. $this->generateImpliedEndTags(array($token['name']));
  1862. /* If the current node is not an element with the same
  1863. tag name as the token, then this is a parse error. */
  1864. // w/e
  1865. /* If the stack of open elements has an element in scope
  1866. whose tag name matches the tag name of the token, then
  1867. pop elements from this stack until an element with that
  1868. tag name has been popped from the stack. */
  1869. for($n = count($this->stack) - 1; $n >= 0; $n--) {
  1870. if($this->stack[$n]->nodeName === $token['name']) {
  1871. $n = -1;
  1872. }
  1873. array_pop($this->stack);
  1874. }
  1875. }
  1876. break;
  1877. /* An end tag whose tag name is one of: "h1", "h2", "h3", "h4",
  1878. "h5", "h6" */
  1879. case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6':
  1880. $elements = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
  1881. /* If the stack of open elements has in scope an element whose
  1882. tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then
  1883. generate implied end tags. */
  1884. if($this->elementInScope($elements)) {
  1885. $this->generateImpliedEndTags();
  1886. /* Now, if the current node is not an element with the same
  1887. tag name as that of the token, then this is a parse error. */
  1888. // w/e
  1889. /* If the stack of open elements has in scope an element
  1890. whose tag name is one of "h1", "h2", "h3", "h4", "h5", or
  1891. "h6", then pop elements from the stack until an element
  1892. with one of those tag names has been popped from the stack. */
  1893. while($this->elementInScope($elements)) {
  1894. array_pop($this->stack);
  1895. }
  1896. }
  1897. break;
  1898. /* An end tag whose tag name is one of: "a", "b", "big", "em",
  1899. "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */
  1900. case 'a': case 'b': case 'big': case 'em': case 'font':
  1901. case 'i': case 'nobr': case 's': case 'small': case 'strike':
  1902. case 'strong': case 'tt': case 'u':
  1903. /* 1. Let the formatting element be the last element in
  1904. the list of active formatting elements that:
  1905. * is between the end of the list and the last scope
  1906. marker in the list, if any, or the start of the list
  1907. otherwise, and
  1908. * has the same tag name as the token.
  1909. */
  1910. while(true) {
  1911. for($a = count($this->a_formatting) - 1; $a >= 0; $a--) {
  1912. if($this->a_formatting[$a] === self::MARKER) {
  1913. break;
  1914. } elseif($this->a_formatting[$a]->tagName === $token['name']) {
  1915. $formatting_element = $this->a_formatting[$a];
  1916. $in_stack = in_array($formatting_element, $this->stack, true);
  1917. $fe_af_pos = $a;
  1918. break;
  1919. }
  1920. }
  1921. /* If there is no such node, or, if that node is
  1922. also in the stack of open elements but the element
  1923. is not in scope, then this is a parse error. Abort
  1924. these steps. The token is ignored. */
  1925. if(!isset($formatting_element) || ($in_stack &&
  1926. !$this->elementInScope($token['name']))) {
  1927. break;
  1928. /* Otherwise, if there is such a node, but that node
  1929. is not in the stack of open elements, then this is a
  1930. parse error; remove the element from the list, and
  1931. abort these steps. */
  1932. } elseif(isset($formatting_element) && !$in_stack) {
  1933. unset($this->a_formatting[$fe_af_pos]);
  1934. $this->a_formatting = array_merge($this->a_formatting);
  1935. break;
  1936. }
  1937. /* 2. Let the furthest block be the topmost node in the
  1938. stack of open elements that is lower in the stack
  1939. than the formatting element, and is not an element in
  1940. the phrasing or formatting categories. There might
  1941. not be one. */
  1942. $fe_s_pos = array_search($formatting_element, $this->stack, true);
  1943. $length = count($this->stack);
  1944. for($s = $fe_s_pos + 1; $s < $length; $s++) {
  1945. $category = $this->getElementCategory($this->stack[$s]->nodeName);
  1946. if($category !== self::PHRASING && $category !== self::FORMATTING) {
  1947. $furthest_block = $this->stack[$s];
  1948. }
  1949. }
  1950. /* 3. If there is no furthest block, then the UA must
  1951. skip the subsequent steps and instead just pop all
  1952. the nodes from the bottom of the stack of open
  1953. elements, from the current node up to the formatting
  1954. element, and remove the formatting element from the
  1955. list of active formatting elements. */
  1956. if(!isset($furthest_block)) {
  1957. for($n = $length - 1; $n >= $fe_s_pos; $n--) {
  1958. array_pop($this->stack);
  1959. }
  1960. unset($this->a_formatting[$fe_af_pos]);
  1961. $this->a_formatting = array_merge($this->a_formatting);
  1962. break;
  1963. }
  1964. /* 4. Let the common ancestor be the element
  1965. immediately above the formatting element in the stack
  1966. of open elements. */
  1967. $common_ancestor = $this->stack[$fe_s_pos - 1];
  1968. /* 5. If the furthest block has a parent node, then
  1969. remove the furthest block from its parent node. */
  1970. if($furthest_block->parentNode !== null) {
  1971. $furthest_block->parentNode->removeChild($furthest_block);
  1972. }
  1973. /* 6. Let a bookmark note the position of the
  1974. formatting element in the list of active formatting
  1975. elements relative to the elements on either side
  1976. of it in the list. */
  1977. $bookmark = $fe_af_pos;
  1978. /* 7. Let node and last node be the furthest block.
  1979. Follow these steps: */
  1980. $node = $furthest_block;
  1981. $last_node = $furthest_block;
  1982. while(true) {
  1983. for($n = array_search($node, $this->stack, true) - 1; $n >= 0; $n--) {
  1984. /* 7.1 Let node be the element immediately
  1985. prior to node in the stack of open elements. */
  1986. $node = $this->stack[$n];
  1987. /* 7.2 If node is not in the list of active
  1988. formatting elements, then remove node from
  1989. the stack of open elements and then go back
  1990. to step 1. */
  1991. if(!in_array($node, $this->a_formatting, true)) {
  1992. unset($this->stack[$n]);
  1993. $this->stack = array_merge($this->stack);
  1994. } else {
  1995. break;
  1996. }
  1997. }
  1998. /* 7.3 Otherwise, if node is the formatting
  1999. element, then go to the next step in the overall
  2000. algorithm. */
  2001. if($node === $formatting_element) {
  2002. break;
  2003. /* 7.4 Otherwise, if last node is the furthest
  2004. block, then move the aforementioned bookmark to
  2005. be immediately after the node in the list of
  2006. active formatting elements. */
  2007. } elseif($last_node === $furthest_block) {
  2008. $bookmark = array_search($node, $this->a_formatting, true) + 1;
  2009. }
  2010. /* 7.5 If node has any children, perform a
  2011. shallow clone of node, replace the entry for
  2012. node in the list of active formatting elements
  2013. with an entry for the clone, replace the entry
  2014. for node in the stack of open elements with an
  2015. entry for the clone, and let node be the clone. */
  2016. if($node->hasChildNodes()) {
  2017. $clone = $node->cloneNode();
  2018. $s_pos = array_search($node, $this->stack, true);
  2019. $a_pos = array_search($node, $this->a_formatting, true);
  2020. $this->stack[$s_pos] = $clone;
  2021. $this->a_formatting[$a_pos] = $clone;
  2022. $node = $clone;
  2023. }
  2024. /* 7.6 Insert last node into node, first removing
  2025. it from its previous parent node if any. */
  2026. if($last_node->parentNode !== null) {
  2027. $last_node->parentNode->removeChild($last_node);
  2028. }
  2029. $node->appendChild($last_node);
  2030. /* 7.7 Let last node be node. */
  2031. $last_node = $node;
  2032. }
  2033. /* 8. Insert whatever last node ended up being in
  2034. the previous step into the common ancestor node,
  2035. first removing it from its previous parent node if
  2036. any. */
  2037. if($last_node->parentNode !== null) {
  2038. $last_node->parentNode->removeChild($last_node);
  2039. }
  2040. $common_ancestor->appendChild($last_node);
  2041. /* 9. Perform a shallow clone of the formatting
  2042. element. */
  2043. $clone = $formatting_element->cloneNode();
  2044. /* 10. Take all of the child nodes of the furthest
  2045. block and append them to the clone created in the
  2046. last step. */
  2047. while($furthest_block->hasChildNodes()) {
  2048. $child = $furthest_block->firstChild;
  2049. $furthest_block->removeChild($child);
  2050. $clone->appendChild($child);
  2051. }
  2052. /* 11. Append that clone to the furthest block. */
  2053. $furthest_block->appendChild($clone);
  2054. /* 12. Remove the formatting element from the list
  2055. of active formatting elements, and insert the clone
  2056. into the list of active formatting elements at the
  2057. position of the aforementioned bookmark. */
  2058. $fe_af_pos = array_search($formatting_element, $this->a_formatting, true);
  2059. unset($this->a_formatting[$fe_af_pos]);
  2060. $this->a_formatting = array_merge($this->a_formatting);
  2061. $af_part1 = array_slice($this->a_formatting, 0, $bookmark - 1);
  2062. $af_part2 = array_slice($this->a_formatting, $bookmark, count($this->a_formatting));
  2063. $this->a_formatting = array_merge($af_part1, array($clone), $af_part2);
  2064. /* 13. Remove the formatting element from the stack
  2065. of open elements, and insert the clone into the stack
  2066. of open elements immediately after (i.e. in a more
  2067. deeply nested position than) the position of the
  2068. furthest block in that stack. */
  2069. $fe_s_pos = array_search($formatting_element, $this->stack, true);
  2070. $fb_s_pos = array_search($furthest_block, $this->stack, true);
  2071. unset($this->stack[$fe_s_pos]);
  2072. $s_part1 = array_slice($this->stack, 0, $fb_s_pos);
  2073. $s_part2 = array_slice($this->stack, $fb_s_pos + 1, count($this->stack));
  2074. $this->stack = array_merge($s_part1, array($clone), $s_part2);
  2075. /* 14. Jump back to step 1 in this series of steps. */
  2076. unset($formatting_element, $fe_af_pos, $fe_s_pos, $furthest_block);
  2077. }
  2078. break;
  2079. /* An end tag token whose tag name is one of: "button",
  2080. "marquee", "object" */
  2081. case 'button': case 'marquee': case 'object':
  2082. /* If the stack of open elements has an element in scope whose
  2083. tag name matches the tag name of the token, then generate implied
  2084. tags. */
  2085. if($this->elementInScope($token['name'])) {
  2086. $this->generateImpliedEndTags();
  2087. /* Now, if the current node is not an element with the same
  2088. tag name as the token, then this is a parse error. */
  2089. // k
  2090. /* Now, if the stack of open elements has an element in scope
  2091. whose tag name matches the tag name of the token, then pop
  2092. elements from the stack until that element has been popped from
  2093. the stack, and clear the list of active formatting elements up
  2094. to the last marker. */
  2095. for($n = count($this->stack) - 1; $n >= 0; $n--) {
  2096. if($this->stack[$n]->nodeName === $token['name']) {
  2097. $n = -1;
  2098. }
  2099. array_pop($this->stack);
  2100. }
  2101. $marker = end(array_keys($this->a_formatting, self::MARKER, true));
  2102. for($n = count($this->a_formatting) - 1; $n > $marker; $n--) {
  2103. array_pop($this->a_formatting);
  2104. }
  2105. }
  2106. break;
  2107. /* Or an end tag whose tag name is one of: "area", "basefont",
  2108. "bgsound", "br", "embed", "hr", "iframe", "image", "img",
  2109. "input", "isindex", "noembed", "noframes", "param", "select",
  2110. "spacer", "table", "textarea", "wbr" */
  2111. case 'area': case 'basefont': case 'bgsound': case 'br':
  2112. case 'embed': case 'hr': case 'iframe': case 'image':
  2113. case 'img': case 'input': case 'isindex': case 'noembed':
  2114. case 'noframes': case 'param': case 'select': case 'spacer':
  2115. case 'table': case 'textarea': case 'wbr':
  2116. // Parse error. Ignore the token.
  2117. break;
  2118. /* An end tag token not covered by the previous entries */
  2119. default:
  2120. for($n = count($this->stack) - 1; $n >= 0; $n--) {
  2121. /* Initialise node to be the current node (the bottommost
  2122. node of the stack). */
  2123. $node = end($this->stack);
  2124. /* If node has the same tag name as the end tag token,
  2125. then: */
  2126. if($token['name'] === $node->nodeName) {
  2127. /* Generate implied end tags. */
  2128. $this->generateImpliedEndTags();
  2129. /* If the tag name of the end tag token does not
  2130. match the tag name of the current node, this is a
  2131. parse error. */
  2132. // k
  2133. /* Pop all the nodes from the current node up to
  2134. node, including node, then stop this algorithm. */
  2135. for($x = count($this->stack) - $n; $x >= $n; $x--) {
  2136. array_pop($this->stack);
  2137. }
  2138. } else {
  2139. $category = $this->getElementCategory($node);
  2140. if($category !== self::SPECIAL && $category !== self::SCOPING) {
  2141. /* Otherwise, if node is in neither the formatting
  2142. category nor the phrasing category, then this is a
  2143. parse error. Stop this algorithm. The end tag token
  2144. is ignored. */
  2145. return false;
  2146. }
  2147. }
  2148. }
  2149. break;
  2150. }
  2151. break;
  2152. }
  2153. }
  2154. private function inTable($token) {
  2155. $clear = array('html', 'table');
  2156. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  2157. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  2158. or U+0020 SPACE */
  2159. if($token['type'] === HTML5::CHARACTR &&
  2160. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  2161. /* Append the character to the current node. */
  2162. $text = $this->dom->createTextNode($token['data']);
  2163. end($this->stack)->appendChild($text);
  2164. /* A comment token */
  2165. } elseif($token['type'] === HTML5::COMMENT) {
  2166. /* Append a Comment node to the current node with the data
  2167. attribute set to the data given in the comment token. */
  2168. $comment = $this->dom->createComment($token['data']);
  2169. end($this->stack)->appendChild($comment);
  2170. /* A start tag whose tag name is "caption" */
  2171. } elseif($token['type'] === HTML5::STARTTAG &&
  2172. $token['name'] === 'caption') {
  2173. /* Clear the stack back to a table context. */
  2174. $this->clearStackToTableContext($clear);
  2175. /* Insert a marker at the end of the list of active
  2176. formatting elements. */
  2177. $this->a_formatting[] = self::MARKER;
  2178. /* Insert an HTML element for the token, then switch the
  2179. insertion mode to "in caption". */
  2180. $this->insertElement($token);
  2181. $this->mode = self::IN_CAPTION;
  2182. /* A start tag whose tag name is "colgroup" */
  2183. } elseif($token['type'] === HTML5::STARTTAG &&
  2184. $token['name'] === 'colgroup') {
  2185. /* Clear the stack back to a table context. */
  2186. $this->clearStackToTableContext($clear);
  2187. /* Insert an HTML element for the token, then switch the
  2188. insertion mode to "in column group". */
  2189. $this->insertElement($token);
  2190. $this->mode = self::IN_CGROUP;
  2191. /* A start tag whose tag name is "col" */
  2192. } elseif($token['type'] === HTML5::STARTTAG &&
  2193. $token['name'] === 'col') {
  2194. $this->inTable(array(
  2195. 'name' => 'colgroup',
  2196. 'type' => HTML5::STARTTAG,
  2197. 'attr' => array()
  2198. ));
  2199. $this->inColumnGroup($token);
  2200. /* A start tag whose tag name is one of: "tbody", "tfoot", "thead" */
  2201. } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
  2202. array('tbody', 'tfoot', 'thead'))) {
  2203. /* Clear the stack back to a table context. */
  2204. $this->clearStackToTableContext($clear);
  2205. /* Insert an HTML element for the token, then switch the insertion
  2206. mode to "in table body". */
  2207. $this->insertElement($token);
  2208. $this->mode = self::IN_TBODY;
  2209. /* A start tag whose tag name is one of: "td", "th", "tr" */
  2210. } elseif($token['type'] === HTML5::STARTTAG &&
  2211. in_array($token['name'], array('td', 'th', 'tr'))) {
  2212. /* Act as if a start tag token with the tag name "tbody" had been
  2213. seen, then reprocess the current token. */
  2214. $this->inTable(array(
  2215. 'name' => 'tbody',
  2216. 'type' => HTML5::STARTTAG,
  2217. 'attr' => array()
  2218. ));
  2219. return $this->inTableBody($token);
  2220. /* A start tag whose tag name is "table" */
  2221. } elseif($token['type'] === HTML5::STARTTAG &&
  2222. $token['name'] === 'table') {
  2223. /* Parse error. Act as if an end tag token with the tag name "table"
  2224. had been seen, then, if that token wasn't ignored, reprocess the
  2225. current token. */
  2226. $this->inTable(array(
  2227. 'name' => 'table',
  2228. 'type' => HTML5::ENDTAG
  2229. ));
  2230. return $this->mainPhase($token);
  2231. /* An end tag whose tag name is "table" */
  2232. } elseif($token['type'] === HTML5::ENDTAG &&
  2233. $token['name'] === 'table') {
  2234. /* If the stack of open elements does not have an element in table
  2235. scope with the same tag name as the token, this is a parse error.
  2236. Ignore the token. (innerHTML case) */
  2237. if(!$this->elementInScope($token['name'], true)) {
  2238. return false;
  2239. /* Otherwise: */
  2240. } else {
  2241. /* Generate implied end tags. */
  2242. $this->generateImpliedEndTags();
  2243. /* Now, if the current node is not a table element, then this
  2244. is a parse error. */
  2245. // w/e
  2246. /* Pop elements from this stack until a table element has been
  2247. popped from the stack. */
  2248. while(true) {
  2249. $current = end($this->stack)->nodeName;
  2250. array_pop($this->stack);
  2251. if($current === 'table') {
  2252. break;
  2253. }
  2254. }
  2255. /* Reset the insertion mode appropriately. */
  2256. $this->resetInsertionMode();
  2257. }
  2258. /* An end tag whose tag name is one of: "body", "caption", "col",
  2259. "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr" */
  2260. } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
  2261. array('body', 'caption', 'col', 'colgroup', 'html', 'tbody', 'td',
  2262. 'tfoot', 'th', 'thead', 'tr'))) {
  2263. // Parse error. Ignore the token.
  2264. /* Anything else */
  2265. } else {
  2266. /* Parse error. Process the token as if the insertion mode was "in
  2267. body", with the following exception: */
  2268. /* If the current node is a table, tbody, tfoot, thead, or tr
  2269. element, then, whenever a node would be inserted into the current
  2270. node, it must instead be inserted into the foster parent element. */
  2271. if(in_array(end($this->stack)->nodeName,
  2272. array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {
  2273. /* The foster parent element is the parent element of the last
  2274. table element in the stack of open elements, if there is a
  2275. table element and it has such a parent element. If there is no
  2276. table element in the stack of open elements (innerHTML case),
  2277. then the foster parent element is the first element in the
  2278. stack of open elements (the html element). Otherwise, if there
  2279. is a table element in the stack of open elements, but the last
  2280. table element in the stack of open elements has no parent, or
  2281. its parent node is not an element, then the foster parent
  2282. element is the element before the last table element in the
  2283. stack of open elements. */
  2284. for($n = count($this->stack) - 1; $n >= 0; $n--) {
  2285. if($this->stack[$n]->nodeName === 'table') {
  2286. $table = $this->stack[$n];
  2287. break;
  2288. }
  2289. }
  2290. if(isset($table) && $table->parentNode !== null) {
  2291. $this->foster_parent = $table->parentNode;
  2292. } elseif(!isset($table)) {
  2293. $this->foster_parent = $this->stack[0];
  2294. } elseif(isset($table) && ($table->parentNode === null ||
  2295. $table->parentNode->nodeType !== XML_ELEMENT_NODE)) {
  2296. $this->foster_parent = $this->stack[$n - 1];
  2297. }
  2298. }
  2299. $this->inBody($token);
  2300. }
  2301. }
  2302. private function inCaption($token) {
  2303. /* An end tag whose tag name is "caption" */
  2304. if($token['type'] === HTML5::ENDTAG && $token['name'] === 'caption') {
  2305. /* If the stack of open elements does not have an element in table
  2306. scope with the same tag name as the token, this is a parse error.
  2307. Ignore the token. (innerHTML case) */
  2308. if(!$this->elementInScope($token['name'], true)) {
  2309. // Ignore
  2310. /* Otherwise: */
  2311. } else {
  2312. /* Generate implied end tags. */
  2313. $this->generateImpliedEndTags();
  2314. /* Now, if the current node is not a caption element, then this
  2315. is a parse error. */
  2316. // w/e
  2317. /* Pop elements from this stack until a caption element has
  2318. been popped from the stack. */
  2319. while(true) {
  2320. $node = end($this->stack)->nodeName;
  2321. array_pop($this->stack);
  2322. if($node === 'caption') {
  2323. break;
  2324. }
  2325. }
  2326. /* Clear the list of active formatting elements up to the last
  2327. marker. */
  2328. $this->clearTheActiveFormattingElementsUpToTheLastMarker();
  2329. /* Switch the insertion mode to "in table". */
  2330. $this->mode = self::IN_TABLE;
  2331. }
  2332. /* A start tag whose tag name is one of: "caption", "col", "colgroup",
  2333. "tbody", "td", "tfoot", "th", "thead", "tr", or an end tag whose tag
  2334. name is "table" */
  2335. } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],
  2336. array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
  2337. 'thead', 'tr'))) || ($token['type'] === HTML5::ENDTAG &&
  2338. $token['name'] === 'table')) {
  2339. /* Parse error. Act as if an end tag with the tag name "caption"
  2340. had been seen, then, if that token wasn't ignored, reprocess the
  2341. current token. */
  2342. $this->inCaption(array(
  2343. 'name' => 'caption',
  2344. 'type' => HTML5::ENDTAG
  2345. ));
  2346. return $this->inTable($token);
  2347. /* An end tag whose tag name is one of: "body", "col", "colgroup",
  2348. "html", "tbody", "td", "tfoot", "th", "thead", "tr" */
  2349. } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
  2350. array('body', 'col', 'colgroup', 'html', 'tbody', 'tfoot', 'th',
  2351. 'thead', 'tr'))) {
  2352. // Parse error. Ignore the token.
  2353. /* Anything else */
  2354. } else {
  2355. /* Process the token as if the insertion mode was "in body". */
  2356. $this->inBody($token);
  2357. }
  2358. }
  2359. private function inColumnGroup($token) {
  2360. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  2361. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  2362. or U+0020 SPACE */
  2363. if($token['type'] === HTML5::CHARACTR &&
  2364. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  2365. /* Append the character to the current node. */
  2366. $text = $this->dom->createTextNode($token['data']);
  2367. end($this->stack)->appendChild($text);
  2368. /* A comment token */
  2369. } elseif($token['type'] === HTML5::COMMENT) {
  2370. /* Append a Comment node to the current node with the data
  2371. attribute set to the data given in the comment token. */
  2372. $comment = $this->dom->createComment($token['data']);
  2373. end($this->stack)->appendChild($comment);
  2374. /* A start tag whose tag name is "col" */
  2375. } elseif($token['type'] === HTML5::STARTTAG && $token['name'] === 'col') {
  2376. /* Insert a col element for the token. Immediately pop the current
  2377. node off the stack of open elements. */
  2378. $this->insertElement($token);
  2379. array_pop($this->stack);
  2380. /* An end tag whose tag name is "colgroup" */
  2381. } elseif($token['type'] === HTML5::ENDTAG &&
  2382. $token['name'] === 'colgroup') {
  2383. /* If the current node is the root html element, then this is a
  2384. parse error, ignore the token. (innerHTML case) */
  2385. if(end($this->stack)->nodeName === 'html') {
  2386. // Ignore
  2387. /* Otherwise, pop the current node (which will be a colgroup
  2388. element) from the stack of open elements. Switch the insertion
  2389. mode to "in table". */
  2390. } else {
  2391. array_pop($this->stack);
  2392. $this->mode = self::IN_TABLE;
  2393. }
  2394. /* An end tag whose tag name is "col" */
  2395. } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'col') {
  2396. /* Parse error. Ignore the token. */
  2397. /* Anything else */
  2398. } else {
  2399. /* Act as if an end tag with the tag name "colgroup" had been seen,
  2400. and then, if that token wasn't ignored, reprocess the current token. */
  2401. $this->inColumnGroup(array(
  2402. 'name' => 'colgroup',
  2403. 'type' => HTML5::ENDTAG
  2404. ));
  2405. return $this->inTable($token);
  2406. }
  2407. }
  2408. private function inTableBody($token) {
  2409. $clear = array('tbody', 'tfoot', 'thead', 'html');
  2410. /* A start tag whose tag name is "tr" */
  2411. if($token['type'] === HTML5::STARTTAG && $token['name'] === 'tr') {
  2412. /* Clear the stack back to a table body context. */
  2413. $this->clearStackToTableContext($clear);
  2414. /* Insert a tr element for the token, then switch the insertion
  2415. mode to "in row". */
  2416. $this->insertElement($token);
  2417. $this->mode = self::IN_ROW;
  2418. /* A start tag whose tag name is one of: "th", "td" */
  2419. } elseif($token['type'] === HTML5::STARTTAG &&
  2420. ($token['name'] === 'th' || $token['name'] === 'td')) {
  2421. /* Parse error. Act as if a start tag with the tag name "tr" had
  2422. been seen, then reprocess the current token. */
  2423. $this->inTableBody(array(
  2424. 'name' => 'tr',
  2425. 'type' => HTML5::STARTTAG,
  2426. 'attr' => array()
  2427. ));
  2428. return $this->inRow($token);
  2429. /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */
  2430. } elseif($token['type'] === HTML5::ENDTAG &&
  2431. in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {
  2432. /* If the stack of open elements does not have an element in table
  2433. scope with the same tag name as the token, this is a parse error.
  2434. Ignore the token. */
  2435. if(!$this->elementInScope($token['name'], true)) {
  2436. // Ignore
  2437. /* Otherwise: */
  2438. } else {
  2439. /* Clear the stack back to a table body context. */
  2440. $this->clearStackToTableContext($clear);
  2441. /* Pop the current node from the stack of open elements. Switch
  2442. the insertion mode to "in table". */
  2443. array_pop($this->stack);
  2444. $this->mode = self::IN_TABLE;
  2445. }
  2446. /* A start tag whose tag name is one of: "caption", "col", "colgroup",
  2447. "tbody", "tfoot", "thead", or an end tag whose tag name is "table" */
  2448. } elseif(($token['type'] === HTML5::STARTTAG && in_array($token['name'],
  2449. array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead'))) ||
  2450. ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table')) {
  2451. /* If the stack of open elements does not have a tbody, thead, or
  2452. tfoot element in table scope, this is a parse error. Ignore the
  2453. token. (innerHTML case) */
  2454. if(!$this->elementInScope(array('tbody', 'thead', 'tfoot'), true)) {
  2455. // Ignore.
  2456. /* Otherwise: */
  2457. } else {
  2458. /* Clear the stack back to a table body context. */
  2459. $this->clearStackToTableContext($clear);
  2460. /* Act as if an end tag with the same tag name as the current
  2461. node ("tbody", "tfoot", or "thead") had been seen, then
  2462. reprocess the current token. */
  2463. $this->inTableBody(array(
  2464. 'name' => end($this->stack)->nodeName,
  2465. 'type' => HTML5::ENDTAG
  2466. ));
  2467. return $this->mainPhase($token);
  2468. }
  2469. /* An end tag whose tag name is one of: "body", "caption", "col",
  2470. "colgroup", "html", "td", "th", "tr" */
  2471. } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
  2472. array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {
  2473. /* Parse error. Ignore the token. */
  2474. /* Anything else */
  2475. } else {
  2476. /* Process the token as if the insertion mode was "in table". */
  2477. $this->inTable($token);
  2478. }
  2479. }
  2480. private function inRow($token) {
  2481. $clear = array('tr', 'html');
  2482. /* A start tag whose tag name is one of: "th", "td" */
  2483. if($token['type'] === HTML5::STARTTAG &&
  2484. ($token['name'] === 'th' || $token['name'] === 'td')) {
  2485. /* Clear the stack back to a table row context. */
  2486. $this->clearStackToTableContext($clear);
  2487. /* Insert an HTML element for the token, then switch the insertion
  2488. mode to "in cell". */
  2489. $this->insertElement($token);
  2490. $this->mode = self::IN_CELL;
  2491. /* Insert a marker at the end of the list of active formatting
  2492. elements. */
  2493. $this->a_formatting[] = self::MARKER;
  2494. /* An end tag whose tag name is "tr" */
  2495. } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'tr') {
  2496. /* If the stack of open elements does not have an element in table
  2497. scope with the same tag name as the token, this is a parse error.
  2498. Ignore the token. (innerHTML case) */
  2499. if(!$this->elementInScope($token['name'], true)) {
  2500. // Ignore.
  2501. /* Otherwise: */
  2502. } else {
  2503. /* Clear the stack back to a table row context. */
  2504. $this->clearStackToTableContext($clear);
  2505. /* Pop the current node (which will be a tr element) from the
  2506. stack of open elements. Switch the insertion mode to "in table
  2507. body". */
  2508. array_pop($this->stack);
  2509. $this->mode = self::IN_TBODY;
  2510. }
  2511. /* A start tag whose tag name is one of: "caption", "col", "colgroup",
  2512. "tbody", "tfoot", "thead", "tr" or an end tag whose tag name is "table" */
  2513. } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
  2514. array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr'))) {
  2515. /* Act as if an end tag with the tag name "tr" had been seen, then,
  2516. if that token wasn't ignored, reprocess the current token. */
  2517. $this->inRow(array(
  2518. 'name' => 'tr',
  2519. 'type' => HTML5::ENDTAG
  2520. ));
  2521. return $this->inCell($token);
  2522. /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */
  2523. } elseif($token['type'] === HTML5::ENDTAG &&
  2524. in_array($token['name'], array('tbody', 'tfoot', 'thead'))) {
  2525. /* If the stack of open elements does not have an element in table
  2526. scope with the same tag name as the token, this is a parse error.
  2527. Ignore the token. */
  2528. if(!$this->elementInScope($token['name'], true)) {
  2529. // Ignore.
  2530. /* Otherwise: */
  2531. } else {
  2532. /* Otherwise, act as if an end tag with the tag name "tr" had
  2533. been seen, then reprocess the current token. */
  2534. $this->inRow(array(
  2535. 'name' => 'tr',
  2536. 'type' => HTML5::ENDTAG
  2537. ));
  2538. return $this->inCell($token);
  2539. }
  2540. /* An end tag whose tag name is one of: "body", "caption", "col",
  2541. "colgroup", "html", "td", "th" */
  2542. } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
  2543. array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr'))) {
  2544. /* Parse error. Ignore the token. */
  2545. /* Anything else */
  2546. } else {
  2547. /* Process the token as if the insertion mode was "in table". */
  2548. $this->inTable($token);
  2549. }
  2550. }
  2551. private function inCell($token) {
  2552. /* An end tag whose tag name is one of: "td", "th" */
  2553. if($token['type'] === HTML5::ENDTAG &&
  2554. ($token['name'] === 'td' || $token['name'] === 'th')) {
  2555. /* If the stack of open elements does not have an element in table
  2556. scope with the same tag name as that of the token, then this is a
  2557. parse error and the token must be ignored. */
  2558. if(!$this->elementInScope($token['name'], true)) {
  2559. // Ignore.
  2560. /* Otherwise: */
  2561. } else {
  2562. /* Generate implied end tags, except for elements with the same
  2563. tag name as the token. */
  2564. $this->generateImpliedEndTags(array($token['name']));
  2565. /* Now, if the current node is not an element with the same tag
  2566. name as the token, then this is a parse error. */
  2567. // k
  2568. /* Pop elements from this stack until an element with the same
  2569. tag name as the token has been popped from the stack. */
  2570. while(true) {
  2571. $node = end($this->stack)->nodeName;
  2572. array_pop($this->stack);
  2573. if($node === $token['name']) {
  2574. break;
  2575. }
  2576. }
  2577. /* Clear the list of active formatting elements up to the last
  2578. marker. */
  2579. $this->clearTheActiveFormattingElementsUpToTheLastMarker();
  2580. /* Switch the insertion mode to "in row". (The current node
  2581. will be a tr element at this point.) */
  2582. $this->mode = self::IN_ROW;
  2583. }
  2584. /* A start tag whose tag name is one of: "caption", "col", "colgroup",
  2585. "tbody", "td", "tfoot", "th", "thead", "tr" */
  2586. } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
  2587. array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
  2588. 'thead', 'tr'))) {
  2589. /* If the stack of open elements does not have a td or th element
  2590. in table scope, then this is a parse error; ignore the token.
  2591. (innerHTML case) */
  2592. if(!$this->elementInScope(array('td', 'th'), true)) {
  2593. // Ignore.
  2594. /* Otherwise, close the cell (see below) and reprocess the current
  2595. token. */
  2596. } else {
  2597. $this->closeCell();
  2598. return $this->inRow($token);
  2599. }
  2600. /* A start tag whose tag name is one of: "caption", "col", "colgroup",
  2601. "tbody", "td", "tfoot", "th", "thead", "tr" */
  2602. } elseif($token['type'] === HTML5::STARTTAG && in_array($token['name'],
  2603. array('caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th',
  2604. 'thead', 'tr'))) {
  2605. /* If the stack of open elements does not have a td or th element
  2606. in table scope, then this is a parse error; ignore the token.
  2607. (innerHTML case) */
  2608. if(!$this->elementInScope(array('td', 'th'), true)) {
  2609. // Ignore.
  2610. /* Otherwise, close the cell (see below) and reprocess the current
  2611. token. */
  2612. } else {
  2613. $this->closeCell();
  2614. return $this->inRow($token);
  2615. }
  2616. /* An end tag whose tag name is one of: "body", "caption", "col",
  2617. "colgroup", "html" */
  2618. } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
  2619. array('body', 'caption', 'col', 'colgroup', 'html'))) {
  2620. /* Parse error. Ignore the token. */
  2621. /* An end tag whose tag name is one of: "table", "tbody", "tfoot",
  2622. "thead", "tr" */
  2623. } elseif($token['type'] === HTML5::ENDTAG && in_array($token['name'],
  2624. array('table', 'tbody', 'tfoot', 'thead', 'tr'))) {
  2625. /* If the stack of open elements does not have an element in table
  2626. scope with the same tag name as that of the token (which can only
  2627. happen for "tbody", "tfoot" and "thead", or, in the innerHTML case),
  2628. then this is a parse error and the token must be ignored. */
  2629. if(!$this->elementInScope($token['name'], true)) {
  2630. // Ignore.
  2631. /* Otherwise, close the cell (see below) and reprocess the current
  2632. token. */
  2633. } else {
  2634. $this->closeCell();
  2635. return $this->inRow($token);
  2636. }
  2637. /* Anything else */
  2638. } else {
  2639. /* Process the token as if the insertion mode was "in body". */
  2640. $this->inBody($token);
  2641. }
  2642. }
  2643. private function inSelect($token) {
  2644. /* Handle the token as follows: */
  2645. /* A character token */
  2646. if($token['type'] === HTML5::CHARACTR) {
  2647. /* Append the token's character to the current node. */
  2648. $this->insertText($token['data']);
  2649. /* A comment token */
  2650. } elseif($token['type'] === HTML5::COMMENT) {
  2651. /* Append a Comment node to the current node with the data
  2652. attribute set to the data given in the comment token. */
  2653. $this->insertComment($token['data']);
  2654. /* A start tag token whose tag name is "option" */
  2655. } elseif($token['type'] === HTML5::STARTTAG &&
  2656. $token['name'] === 'option') {
  2657. /* If the current node is an option element, act as if an end tag
  2658. with the tag name "option" had been seen. */
  2659. if(end($this->stack)->nodeName === 'option') {
  2660. $this->inSelect(array(
  2661. 'name' => 'option',
  2662. 'type' => HTML5::ENDTAG
  2663. ));
  2664. }
  2665. /* Insert an HTML element for the token. */
  2666. $this->insertElement($token);
  2667. /* A start tag token whose tag name is "optgroup" */
  2668. } elseif($token['type'] === HTML5::STARTTAG &&
  2669. $token['name'] === 'optgroup') {
  2670. /* If the current node is an option element, act as if an end tag
  2671. with the tag name "option" had been seen. */
  2672. if(end($this->stack)->nodeName === 'option') {
  2673. $this->inSelect(array(
  2674. 'name' => 'option',
  2675. 'type' => HTML5::ENDTAG
  2676. ));
  2677. }
  2678. /* If the current node is an optgroup element, act as if an end tag
  2679. with the tag name "optgroup" had been seen. */
  2680. if(end($this->stack)->nodeName === 'optgroup') {
  2681. $this->inSelect(array(
  2682. 'name' => 'optgroup',
  2683. 'type' => HTML5::ENDTAG
  2684. ));
  2685. }
  2686. /* Insert an HTML element for the token. */
  2687. $this->insertElement($token);
  2688. /* An end tag token whose tag name is "optgroup" */
  2689. } elseif($token['type'] === HTML5::ENDTAG &&
  2690. $token['name'] === 'optgroup') {
  2691. /* First, if the current node is an option element, and the node
  2692. immediately before it in the stack of open elements is an optgroup
  2693. element, then act as if an end tag with the tag name "option" had
  2694. been seen. */
  2695. $elements_in_stack = count($this->stack);
  2696. if($this->stack[$elements_in_stack - 1]->nodeName === 'option' &&
  2697. $this->stack[$elements_in_stack - 2]->nodeName === 'optgroup') {
  2698. $this->inSelect(array(
  2699. 'name' => 'option',
  2700. 'type' => HTML5::ENDTAG
  2701. ));
  2702. }
  2703. /* If the current node is an optgroup element, then pop that node
  2704. from the stack of open elements. Otherwise, this is a parse error,
  2705. ignore the token. */
  2706. if($this->stack[$elements_in_stack - 1] === 'optgroup') {
  2707. array_pop($this->stack);
  2708. }
  2709. /* An end tag token whose tag name is "option" */
  2710. } elseif($token['type'] === HTML5::ENDTAG &&
  2711. $token['name'] === 'option') {
  2712. /* If the current node is an option element, then pop that node
  2713. from the stack of open elements. Otherwise, this is a parse error,
  2714. ignore the token. */
  2715. if(end($this->stack)->nodeName === 'option') {
  2716. array_pop($this->stack);
  2717. }
  2718. /* An end tag whose tag name is "select" */
  2719. } elseif($token['type'] === HTML5::ENDTAG &&
  2720. $token['name'] === 'select') {
  2721. /* If the stack of open elements does not have an element in table
  2722. scope with the same tag name as the token, this is a parse error.
  2723. Ignore the token. (innerHTML case) */
  2724. if(!$this->elementInScope($token['name'], true)) {
  2725. // w/e
  2726. /* Otherwise: */
  2727. } else {
  2728. /* Pop elements from the stack of open elements until a select
  2729. element has been popped from the stack. */
  2730. while(true) {
  2731. $current = end($this->stack)->nodeName;
  2732. array_pop($this->stack);
  2733. if($current === 'select') {
  2734. break;
  2735. }
  2736. }
  2737. /* Reset the insertion mode appropriately. */
  2738. $this->resetInsertionMode();
  2739. }
  2740. /* A start tag whose tag name is "select" */
  2741. } elseif($token['name'] === 'select' &&
  2742. $token['type'] === HTML5::STARTTAG) {
  2743. /* Parse error. Act as if the token had been an end tag with the
  2744. tag name "select" instead. */
  2745. $this->inSelect(array(
  2746. 'name' => 'select',
  2747. 'type' => HTML5::ENDTAG
  2748. ));
  2749. /* An end tag whose tag name is one of: "caption", "table", "tbody",
  2750. "tfoot", "thead", "tr", "td", "th" */
  2751. } elseif(in_array($token['name'], array('caption', 'table', 'tbody',
  2752. 'tfoot', 'thead', 'tr', 'td', 'th')) && $token['type'] === HTML5::ENDTAG) {
  2753. /* Parse error. */
  2754. // w/e
  2755. /* If the stack of open elements has an element in table scope with
  2756. the same tag name as that of the token, then act as if an end tag
  2757. with the tag name "select" had been seen, and reprocess the token.
  2758. Otherwise, ignore the token. */
  2759. if($this->elementInScope($token['name'], true)) {
  2760. $this->inSelect(array(
  2761. 'name' => 'select',
  2762. 'type' => HTML5::ENDTAG
  2763. ));
  2764. $this->mainPhase($token);
  2765. }
  2766. /* Anything else */
  2767. } else {
  2768. /* Parse error. Ignore the token. */
  2769. }
  2770. }
  2771. private function afterBody($token) {
  2772. /* Handle the token as follows: */
  2773. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  2774. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  2775. or U+0020 SPACE */
  2776. if($token['type'] === HTML5::CHARACTR &&
  2777. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  2778. /* Process the token as it would be processed if the insertion mode
  2779. was "in body". */
  2780. $this->inBody($token);
  2781. /* A comment token */
  2782. } elseif($token['type'] === HTML5::COMMENT) {
  2783. /* Append a Comment node to the first element in the stack of open
  2784. elements (the html element), with the data attribute set to the
  2785. data given in the comment token. */
  2786. $comment = $this->dom->createComment($token['data']);
  2787. $this->stack[0]->appendChild($comment);
  2788. /* An end tag with the tag name "html" */
  2789. } elseif($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') {
  2790. /* If the parser was originally created in order to handle the
  2791. setting of an element's innerHTML attribute, this is a parse error;
  2792. ignore the token. (The element will be an html element in this
  2793. case.) (innerHTML case) */
  2794. /* Otherwise, switch to the trailing end phase. */
  2795. $this->phase = self::END_PHASE;
  2796. /* Anything else */
  2797. } else {
  2798. /* Parse error. Set the insertion mode to "in body" and reprocess
  2799. the token. */
  2800. $this->mode = self::IN_BODY;
  2801. return $this->inBody($token);
  2802. }
  2803. }
  2804. private function inFrameset($token) {
  2805. /* Handle the token as follows: */
  2806. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  2807. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  2808. U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */
  2809. if($token['type'] === HTML5::CHARACTR &&
  2810. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  2811. /* Append the character to the current node. */
  2812. $this->insertText($token['data']);
  2813. /* A comment token */
  2814. } elseif($token['type'] === HTML5::COMMENT) {
  2815. /* Append a Comment node to the current node with the data
  2816. attribute set to the data given in the comment token. */
  2817. $this->insertComment($token['data']);
  2818. /* A start tag with the tag name "frameset" */
  2819. } elseif($token['name'] === 'frameset' &&
  2820. $token['type'] === HTML5::STARTTAG) {
  2821. $this->insertElement($token);
  2822. /* An end tag with the tag name "frameset" */
  2823. } elseif($token['name'] === 'frameset' &&
  2824. $token['type'] === HTML5::ENDTAG) {
  2825. /* If the current node is the root html element, then this is a
  2826. parse error; ignore the token. (innerHTML case) */
  2827. if(end($this->stack)->nodeName === 'html') {
  2828. // Ignore
  2829. } else {
  2830. /* Otherwise, pop the current node from the stack of open
  2831. elements. */
  2832. array_pop($this->stack);
  2833. /* If the parser was not originally created in order to handle
  2834. the setting of an element's innerHTML attribute (innerHTML case),
  2835. and the current node is no longer a frameset element, then change
  2836. the insertion mode to "after frameset". */
  2837. $this->mode = self::AFTR_FRAME;
  2838. }
  2839. /* A start tag with the tag name "frame" */
  2840. } elseif($token['name'] === 'frame' &&
  2841. $token['type'] === HTML5::STARTTAG) {
  2842. /* Insert an HTML element for the token. */
  2843. $this->insertElement($token);
  2844. /* Immediately pop the current node off the stack of open elements. */
  2845. array_pop($this->stack);
  2846. /* A start tag with the tag name "noframes" */
  2847. } elseif($token['name'] === 'noframes' &&
  2848. $token['type'] === HTML5::STARTTAG) {
  2849. /* Process the token as if the insertion mode had been "in body". */
  2850. $this->inBody($token);
  2851. /* Anything else */
  2852. } else {
  2853. /* Parse error. Ignore the token. */
  2854. }
  2855. }
  2856. private function afterFrameset($token) {
  2857. /* Handle the token as follows: */
  2858. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  2859. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  2860. U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */
  2861. if($token['type'] === HTML5::CHARACTR &&
  2862. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  2863. /* Append the character to the current node. */
  2864. $this->insertText($token['data']);
  2865. /* A comment token */
  2866. } elseif($token['type'] === HTML5::COMMENT) {
  2867. /* Append a Comment node to the current node with the data
  2868. attribute set to the data given in the comment token. */
  2869. $this->insertComment($token['data']);
  2870. /* An end tag with the tag name "html" */
  2871. } elseif($token['name'] === 'html' &&
  2872. $token['type'] === HTML5::ENDTAG) {
  2873. /* Switch to the trailing end phase. */
  2874. $this->phase = self::END_PHASE;
  2875. /* A start tag with the tag name "noframes" */
  2876. } elseif($token['name'] === 'noframes' &&
  2877. $token['type'] === HTML5::STARTTAG) {
  2878. /* Process the token as if the insertion mode had been "in body". */
  2879. $this->inBody($token);
  2880. /* Anything else */
  2881. } else {
  2882. /* Parse error. Ignore the token. */
  2883. }
  2884. }
  2885. private function trailingEndPhase($token) {
  2886. /* After the main phase, as each token is emitted from the tokenisation
  2887. stage, it must be processed as described in this section. */
  2888. /* A DOCTYPE token */
  2889. if($token['type'] === HTML5::DOCTYPE) {
  2890. // Parse error. Ignore the token.
  2891. /* A comment token */
  2892. } elseif($token['type'] === HTML5::COMMENT) {
  2893. /* Append a Comment node to the Document object with the data
  2894. attribute set to the data given in the comment token. */
  2895. $comment = $this->dom->createComment($token['data']);
  2896. $this->dom->appendChild($comment);
  2897. /* A character token that is one of one of U+0009 CHARACTER TABULATION,
  2898. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  2899. or U+0020 SPACE */
  2900. } elseif($token['type'] === HTML5::CHARACTR &&
  2901. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) {
  2902. /* Process the token as it would be processed in the main phase. */
  2903. $this->mainPhase($token);
  2904. /* A character token that is not one of U+0009 CHARACTER TABULATION,
  2905. U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF),
  2906. or U+0020 SPACE. Or a start tag token. Or an end tag token. */
  2907. } elseif(($token['type'] === HTML5::CHARACTR &&
  2908. preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) ||
  2909. $token['type'] === HTML5::STARTTAG || $token['type'] === HTML5::ENDTAG) {
  2910. /* Parse error. Switch back to the main phase and reprocess the
  2911. token. */
  2912. $this->phase = self::MAIN_PHASE;
  2913. return $this->mainPhase($token);
  2914. /* An end-of-file token */
  2915. } elseif($token['type'] === HTML5::EOF) {
  2916. /* OMG DONE!! */
  2917. }
  2918. }
  2919. private function insertElement($token, $append = true) {
  2920. $el = $this->dom->createElement($token['name']);
  2921. foreach($token['attr'] as $attr) {
  2922. if(!$el->hasAttribute($attr['name'])) {
  2923. $el->setAttribute($attr['name'], $attr['value']);
  2924. }
  2925. }
  2926. $this->appendToRealParent($el);
  2927. $this->stack[] = $el;
  2928. return $el;
  2929. }
  2930. private function insertText($data) {
  2931. $text = $this->dom->createTextNode($data);
  2932. $this->appendToRealParent($text);
  2933. }
  2934. private function insertComment($data) {
  2935. $comment = $this->dom->createComment($data);
  2936. $this->appendToRealParent($comment);
  2937. }
  2938. private function appendToRealParent($node) {
  2939. if($this->foster_parent === null) {
  2940. end($this->stack)->appendChild($node);
  2941. } elseif($this->foster_parent !== null) {
  2942. /* If the foster parent element is the parent element of the
  2943. last table element in the stack of open elements, then the new
  2944. node must be inserted immediately before the last table element
  2945. in the stack of open elements in the foster parent element;
  2946. otherwise, the new node must be appended to the foster parent
  2947. element. */
  2948. for($n = count($this->stack) - 1; $n >= 0; $n--) {
  2949. if($this->stack[$n]->nodeName === 'table' &&
  2950. $this->stack[$n]->parentNode !== null) {
  2951. $table = $this->stack[$n];
  2952. break;
  2953. }
  2954. }
  2955. if(isset($table) && $this->foster_parent->isSameNode($table->parentNode))
  2956. $this->foster_parent->insertBefore($node, $table);
  2957. else
  2958. $this->foster_parent->appendChild($node);
  2959. $this->foster_parent = null;
  2960. }
  2961. }
  2962. private function elementInScope($el, $table = false) {
  2963. if(is_array($el)) {
  2964. foreach($el as $element) {
  2965. if($this->elementInScope($element, $table)) {
  2966. return true;
  2967. }
  2968. }
  2969. return false;
  2970. }
  2971. $leng = count($this->stack);
  2972. for($n = 0; $n < $leng; $n++) {
  2973. /* 1. Initialise node to be the current node (the bottommost node of
  2974. the stack). */
  2975. $node = $this->stack[$leng - 1 - $n];
  2976. if($node->tagName === $el) {
  2977. /* 2. If node is the target node, terminate in a match state. */
  2978. return true;
  2979. } elseif($node->tagName === 'table') {
  2980. /* 3. Otherwise, if node is a table element, terminate in a failure
  2981. state. */
  2982. return false;
  2983. } elseif($table === true && in_array($node->tagName, array('caption', 'td',
  2984. 'th', 'button', 'marquee', 'object'))) {
  2985. /* 4. Otherwise, if the algorithm is the "has an element in scope"
  2986. variant (rather than the "has an element in table scope" variant),
  2987. and node is one of the following, terminate in a failure state. */
  2988. return false;
  2989. } elseif($node === $node->ownerDocument->documentElement) {
  2990. /* 5. Otherwise, if node is an html element (root element), terminate
  2991. in a failure state. (This can only happen if the node is the topmost
  2992. node of the stack of open elements, and prevents the next step from
  2993. being invoked if there are no more elements in the stack.) */
  2994. return false;
  2995. }
  2996. /* Otherwise, set node to the previous entry in the stack of open
  2997. elements and return to step 2. (This will never fail, since the loop
  2998. will always terminate in the previous step if the top of the stack
  2999. is reached.) */
  3000. }
  3001. }
  3002. private function reconstructActiveFormattingElements() {
  3003. /* 1. If there are no entries in the list of active formatting elements,
  3004. then there is nothing to reconstruct; stop this algorithm. */
  3005. $formatting_elements = count($this->a_formatting);
  3006. if($formatting_elements === 0) {
  3007. return false;
  3008. }
  3009. /* 3. Let entry be the last (most recently added) element in the list
  3010. of active formatting elements. */
  3011. $entry = end($this->a_formatting);
  3012. /* 2. If the last (most recently added) entry in the list of active
  3013. formatting elements is a marker, or if it is an element that is in the
  3014. stack of open elements, then there is nothing to reconstruct; stop this
  3015. algorithm. */
  3016. if($entry === self::MARKER || in_array($entry, $this->stack, true)) {
  3017. return false;
  3018. }
  3019. for($a = $formatting_elements - 1; $a >= 0; true) {
  3020. /* 4. If there are no entries before entry in the list of active
  3021. formatting elements, then jump to step 8. */
  3022. if($a === 0) {
  3023. $step_seven = false;
  3024. break;
  3025. }
  3026. /* 5. Let entry be the entry one earlier than entry in the list of
  3027. active formatting elements. */
  3028. $a--;
  3029. $entry = $this->a_formatting[$a];
  3030. /* 6. If entry is neither a marker nor an element that is also in
  3031. thetack of open elements, go to step 4. */
  3032. if($entry === self::MARKER || in_array($entry, $this->stack, true)) {
  3033. break;
  3034. }
  3035. }
  3036. while(true) {
  3037. /* 7. Let entry be the element one later than entry in the list of
  3038. active formatting elements. */
  3039. if(isset($step_seven) && $step_seven === true) {
  3040. $a++;
  3041. $entry = $this->a_formatting[$a];
  3042. }
  3043. /* 8. Perform a shallow clone of the element entry to obtain clone. */
  3044. $clone = $entry->cloneNode();
  3045. /* 9. Append clone to the current node and push it onto the stack
  3046. of open elements so that it is the new current node. */
  3047. end($this->stack)->appendChild($clone);
  3048. $this->stack[] = $clone;
  3049. /* 10. Replace the entry for entry in the list with an entry for
  3050. clone. */
  3051. $this->a_formatting[$a] = $clone;
  3052. /* 11. If the entry for clone in the list of active formatting
  3053. elements is not the last entry in the list, return to step 7. */
  3054. if(end($this->a_formatting) !== $clone) {
  3055. $step_seven = true;
  3056. } else {
  3057. break;
  3058. }
  3059. }
  3060. }
  3061. private function clearTheActiveFormattingElementsUpToTheLastMarker() {
  3062. /* When the steps below require the UA to clear the list of active
  3063. formatting elements up to the last marker, the UA must perform the
  3064. following steps: */
  3065. while(true) {
  3066. /* 1. Let entry be the last (most recently added) entry in the list
  3067. of active formatting elements. */
  3068. $entry = end($this->a_formatting);
  3069. /* 2. Remove entry from the list of active formatting elements. */
  3070. array_pop($this->a_formatting);
  3071. /* 3. If entry was a marker, then stop the algorithm at this point.
  3072. The list has been cleared up to the last marker. */
  3073. if($entry === self::MARKER) {
  3074. break;
  3075. }
  3076. }
  3077. }
  3078. private function generateImpliedEndTags(array $exclude = array()) {
  3079. /* When the steps below require the UA to generate implied end tags,
  3080. then, if the current node is a dd element, a dt element, an li element,
  3081. a p element, a td element, a th element, or a tr element, the UA must
  3082. act as if an end tag with the respective tag name had been seen and
  3083. then generate implied end tags again. */
  3084. $node = end($this->stack);
  3085. $elements = array_diff(array('dd', 'dt', 'li', 'p', 'td', 'th', 'tr'), $exclude);
  3086. while(in_array(end($this->stack)->nodeName, $elements)) {
  3087. array_pop($this->stack);
  3088. }
  3089. }
  3090. private function getElementCategory($name) {
  3091. if(in_array($name, $this->special))
  3092. return self::SPECIAL;
  3093. elseif(in_array($name, $this->scoping))
  3094. return self::SCOPING;
  3095. elseif(in_array($name, $this->formatting))
  3096. return self::FORMATTING;
  3097. else
  3098. return self::PHRASING;
  3099. }
  3100. private function clearStackToTableContext($elements) {
  3101. /* When the steps above require the UA to clear the stack back to a
  3102. table context, it means that the UA must, while the current node is not
  3103. a table element or an html element, pop elements from the stack of open
  3104. elements. If this causes any elements to be popped from the stack, then
  3105. this is a parse error. */
  3106. while(true) {
  3107. $node = end($this->stack)->nodeName;
  3108. if(in_array($node, $elements)) {
  3109. break;
  3110. } else {
  3111. array_pop($this->stack);
  3112. }
  3113. }
  3114. }
  3115. private function resetInsertionMode() {
  3116. /* 1. Let last be false. */
  3117. $last = false;
  3118. $leng = count($this->stack);
  3119. for($n = $leng - 1; $n >= 0; $n--) {
  3120. /* 2. Let node be the last node in the stack of open elements. */
  3121. $node = $this->stack[$n];
  3122. /* 3. If node is the first node in the stack of open elements, then
  3123. set last to true. If the element whose innerHTML attribute is being
  3124. set is neither a td element nor a th element, then set node to the
  3125. element whose innerHTML attribute is being set. (innerHTML case) */
  3126. if($this->stack[0]->isSameNode($node)) {
  3127. $last = true;
  3128. }
  3129. /* 4. If node is a select element, then switch the insertion mode to
  3130. "in select" and abort these steps. (innerHTML case) */
  3131. if($node->nodeName === 'select') {
  3132. $this->mode = self::IN_SELECT;
  3133. break;
  3134. /* 5. If node is a td or th element, then switch the insertion mode
  3135. to "in cell" and abort these steps. */
  3136. } elseif($node->nodeName === 'td' || $node->nodeName === 'th') {
  3137. $this->mode = self::IN_CELL;
  3138. break;
  3139. /* 6. If node is a tr element, then switch the insertion mode to
  3140. "in row" and abort these steps. */
  3141. } elseif($node->nodeName === 'tr') {
  3142. $this->mode = self::IN_ROW;
  3143. break;
  3144. /* 7. If node is a tbody, thead, or tfoot element, then switch the
  3145. insertion mode to "in table body" and abort these steps. */
  3146. } elseif(in_array($node->nodeName, array('tbody', 'thead', 'tfoot'))) {
  3147. $this->mode = self::IN_TBODY;
  3148. break;
  3149. /* 8. If node is a caption element, then switch the insertion mode
  3150. to "in caption" and abort these steps. */
  3151. } elseif($node->nodeName === 'caption') {
  3152. $this->mode = self::IN_CAPTION;
  3153. break;
  3154. /* 9. If node is a colgroup element, then switch the insertion mode
  3155. to "in column group" and abort these steps. (innerHTML case) */
  3156. } elseif($node->nodeName === 'colgroup') {
  3157. $this->mode = self::IN_CGROUP;
  3158. break;
  3159. /* 10. If node is a table element, then switch the insertion mode
  3160. to "in table" and abort these steps. */
  3161. } elseif($node->nodeName === 'table') {
  3162. $this->mode = self::IN_TABLE;
  3163. break;
  3164. /* 11. If node is a head element, then switch the insertion mode
  3165. to "in body" ("in body"! not "in head"!) and abort these steps.
  3166. (innerHTML case) */
  3167. } elseif($node->nodeName === 'head') {
  3168. $this->mode = self::IN_BODY;
  3169. break;
  3170. /* 12. If node is a body element, then switch the insertion mode to
  3171. "in body" and abort these steps. */
  3172. } elseif($node->nodeName === 'body') {
  3173. $this->mode = self::IN_BODY;
  3174. break;
  3175. /* 13. If node is a frameset element, then switch the insertion
  3176. mode to "in frameset" and abort these steps. (innerHTML case) */
  3177. } elseif($node->nodeName === 'frameset') {
  3178. $this->mode = self::IN_FRAME;
  3179. break;
  3180. /* 14. If node is an html element, then: if the head element
  3181. pointer is null, switch the insertion mode to "before head",
  3182. otherwise, switch the insertion mode to "after head". In either
  3183. case, abort these steps. (innerHTML case) */
  3184. } elseif($node->nodeName === 'html') {
  3185. $this->mode = ($this->head_pointer === null)
  3186. ? self::BEFOR_HEAD
  3187. : self::AFTER_HEAD;
  3188. break;
  3189. /* 15. If last is true, then set the insertion mode to "in body"
  3190. and abort these steps. (innerHTML case) */
  3191. } elseif($last) {
  3192. $this->mode = self::IN_BODY;
  3193. break;
  3194. }
  3195. }
  3196. }
  3197. private function closeCell() {
  3198. /* If the stack of open elements has a td or th element in table scope,
  3199. then act as if an end tag token with that tag name had been seen. */
  3200. foreach(array('td', 'th') as $cell) {
  3201. if($this->elementInScope($cell, true)) {
  3202. $this->inCell(array(
  3203. 'name' => $cell,
  3204. 'type' => HTML5::ENDTAG
  3205. ));
  3206. break;
  3207. }
  3208. }
  3209. }
  3210. public function save() {
  3211. return $this->dom;
  3212. }
  3213. }
  3214. ?>