Balancer.php 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585
  1. <?php
  2. /**
  3. * An implementation of the tree building portion of the HTML5 parsing
  4. * spec.
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. * http://www.gnu.org/copyleft/gpl.html
  20. *
  21. * @file
  22. * @ingroup Parser
  23. * @since 1.27
  24. * @author C. Scott Ananian, 2016
  25. */
  26. namespace MediaWiki\Tidy;
  27. use ExplodeIterator;
  28. use IteratorAggregate;
  29. use ReverseArrayIterator;
  30. use Sanitizer;
  31. use Wikimedia\Assert\Assert;
  32. use Wikimedia\Assert\ParameterAssertionException;
  33. // A note for future librarization[1] -- this file is a good candidate
  34. // for splitting into an independent library, except that it is currently
  35. // highly optimized for MediaWiki use. It only implements the portions
  36. // of the HTML5 tree builder used by tags supported by MediaWiki, and
  37. // does not contain a true tokenizer pass, instead relying on
  38. // comment stripping, attribute normalization, and escaping done by
  39. // the MediaWiki Sanitizer. It also deliberately avoids building
  40. // a true DOM in memory, instead serializing elements to an output string
  41. // as soon as possible (usually as soon as the tag is closed) to reduce
  42. // its memory footprint.
  43. // We've been gradually lifting some of these restrictions to handle
  44. // non-sanitized output generated by extensions, but we shortcut the tokenizer
  45. // for speed (primarily by splitting on `<`) and so rely on syntactic
  46. // well-formedness.
  47. // On the other hand, I've been pretty careful to note with comments in the
  48. // code the places where this implementation omits features of the spec or
  49. // depends on the MediaWiki Sanitizer. Perhaps in the future we'll want to
  50. // implement the missing pieces and make this a standalone PHP HTML5 parser.
  51. // In order to do so, some sort of MediaWiki-specific API will need
  52. // to be added to (a) allow the Balancer to bypass the tokenizer,
  53. // and (b) support on-the-fly flattening instead of DOM node creation.
  54. // [1]: https://www.mediawiki.org/wiki/Library_infrastructure_for_MediaWiki
  55. /**
  56. * Utility constants and sets for the HTML5 tree building algorithm.
  57. * Sets are associative arrays indexed first by namespace and then by
  58. * lower-cased tag name.
  59. *
  60. * @ingroup Parser
  61. * @since 1.27
  62. */
  63. class BalanceSets {
  64. const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  65. const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  66. const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  67. public static $unsupportedSet = [
  68. self::HTML_NAMESPACE => [
  69. 'html' => true, 'head' => true, 'body' => true, 'frameset' => true,
  70. 'frame' => true,
  71. 'plaintext' => true,
  72. 'xmp' => true, 'iframe' => true, 'noembed' => true,
  73. 'noscript' => true, 'script' => true,
  74. 'title' => true
  75. ]
  76. ];
  77. public static $emptyElementSet = [
  78. self::HTML_NAMESPACE => [
  79. 'area' => true, 'base' => true, 'basefont' => true,
  80. 'bgsound' => true, 'br' => true, 'col' => true, 'command' => true,
  81. 'embed' => true, 'frame' => true, 'hr' => true, 'img' => true,
  82. 'input' => true, 'keygen' => true, 'link' => true, 'meta' => true,
  83. 'param' => true, 'source' => true, 'track' => true, 'wbr' => true
  84. ]
  85. ];
  86. public static $extraLinefeedSet = [
  87. self::HTML_NAMESPACE => [
  88. 'pre' => true, 'textarea' => true, 'listing' => true,
  89. ]
  90. ];
  91. public static $headingSet = [
  92. self::HTML_NAMESPACE => [
  93. 'h1' => true, 'h2' => true, 'h3' => true,
  94. 'h4' => true, 'h5' => true, 'h6' => true
  95. ]
  96. ];
  97. public static $specialSet = [
  98. self::HTML_NAMESPACE => [
  99. 'address' => true, 'applet' => true, 'area' => true,
  100. 'article' => true, 'aside' => true, 'base' => true,
  101. 'basefont' => true, 'bgsound' => true, 'blockquote' => true,
  102. 'body' => true, 'br' => true, 'button' => true, 'caption' => true,
  103. 'center' => true, 'col' => true, 'colgroup' => true, 'dd' => true,
  104. 'details' => true, 'dir' => true, 'div' => true, 'dl' => true,
  105. 'dt' => true, 'embed' => true, 'fieldset' => true,
  106. 'figcaption' => true, 'figure' => true, 'footer' => true,
  107. 'form' => true, 'frame' => true, 'frameset' => true, 'h1' => true,
  108. 'h2' => true, 'h3' => true, 'h4' => true, 'h5' => true,
  109. 'h6' => true, 'head' => true, 'header' => true, 'hgroup' => true,
  110. 'hr' => true, 'html' => true, 'iframe' => true, 'img' => true,
  111. 'input' => true, 'li' => true, 'link' => true,
  112. 'listing' => true, 'main' => true, 'marquee' => true,
  113. 'menu' => true, 'meta' => true, 'nav' => true,
  114. 'noembed' => true, 'noframes' => true, 'noscript' => true,
  115. 'object' => true, 'ol' => true, 'p' => true, 'param' => true,
  116. 'plaintext' => true, 'pre' => true, 'script' => true,
  117. 'section' => true, 'select' => true, 'source' => true,
  118. 'style' => true, 'summary' => true, 'table' => true,
  119. 'tbody' => true, 'td' => true, 'template' => true,
  120. 'textarea' => true, 'tfoot' => true, 'th' => true, 'thead' => true,
  121. 'title' => true, 'tr' => true, 'track' => true, 'ul' => true,
  122. 'wbr' => true, 'xmp' => true
  123. ],
  124. self::SVG_NAMESPACE => [
  125. 'foreignobject' => true, 'desc' => true, 'title' => true
  126. ],
  127. self::MATHML_NAMESPACE => [
  128. 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
  129. 'mtext' => true, 'annotation-xml' => true
  130. ]
  131. ];
  132. public static $addressDivPSet = [
  133. self::HTML_NAMESPACE => [
  134. 'address' => true, 'div' => true, 'p' => true
  135. ]
  136. ];
  137. public static $tableSectionRowSet = [
  138. self::HTML_NAMESPACE => [
  139. 'table' => true, 'thead' => true, 'tbody' => true,
  140. 'tfoot' => true, 'tr' => true
  141. ]
  142. ];
  143. public static $impliedEndTagsSet = [
  144. self::HTML_NAMESPACE => [
  145. 'dd' => true, 'dt' => true, 'li' => true,
  146. 'menuitem' => true, 'optgroup' => true,
  147. 'option' => true, 'p' => true, 'rb' => true, 'rp' => true,
  148. 'rt' => true, 'rtc' => true
  149. ]
  150. ];
  151. public static $thoroughImpliedEndTagsSet = [
  152. self::HTML_NAMESPACE => [
  153. 'caption' => true, 'colgroup' => true, 'dd' => true, 'dt' => true,
  154. 'li' => true, 'optgroup' => true, 'option' => true, 'p' => true,
  155. 'rb' => true, 'rp' => true, 'rt' => true, 'rtc' => true,
  156. 'tbody' => true, 'td' => true, 'tfoot' => true, 'th' => true,
  157. 'thead' => true, 'tr' => true
  158. ]
  159. ];
  160. public static $tableCellSet = [
  161. self::HTML_NAMESPACE => [
  162. 'td' => true, 'th' => true
  163. ]
  164. ];
  165. public static $tableContextSet = [
  166. self::HTML_NAMESPACE => [
  167. 'table' => true, 'template' => true, 'html' => true
  168. ]
  169. ];
  170. public static $tableBodyContextSet = [
  171. self::HTML_NAMESPACE => [
  172. 'tbody' => true, 'tfoot' => true, 'thead' => true,
  173. 'template' => true, 'html' => true
  174. ]
  175. ];
  176. public static $tableRowContextSet = [
  177. self::HTML_NAMESPACE => [
  178. 'tr' => true, 'template' => true, 'html' => true
  179. ]
  180. ];
  181. // See https://html.spec.whatwg.org/multipage/forms.html#form-associated-element
  182. public static $formAssociatedSet = [
  183. self::HTML_NAMESPACE => [
  184. 'button' => true, 'fieldset' => true, 'input' => true,
  185. 'keygen' => true, 'object' => true, 'output' => true,
  186. 'select' => true, 'textarea' => true, 'img' => true
  187. ]
  188. ];
  189. public static $inScopeSet = [
  190. self::HTML_NAMESPACE => [
  191. 'applet' => true, 'caption' => true, 'html' => true,
  192. 'marquee' => true, 'object' => true,
  193. 'table' => true, 'td' => true, 'template' => true,
  194. 'th' => true
  195. ],
  196. self::SVG_NAMESPACE => [
  197. 'foreignobject' => true, 'desc' => true, 'title' => true
  198. ],
  199. self::MATHML_NAMESPACE => [
  200. 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
  201. 'mtext' => true, 'annotation-xml' => true
  202. ]
  203. ];
  204. private static $inListItemScopeSet = null;
  205. public static function inListItemScopeSet() {
  206. if ( self::$inListItemScopeSet === null ) {
  207. self::$inListItemScopeSet = self::$inScopeSet;
  208. self::$inListItemScopeSet[self::HTML_NAMESPACE]['ol'] = true;
  209. self::$inListItemScopeSet[self::HTML_NAMESPACE]['ul'] = true;
  210. }
  211. return self::$inListItemScopeSet;
  212. }
  213. private static $inButtonScopeSet = null;
  214. public static function inButtonScopeSet() {
  215. if ( self::$inButtonScopeSet === null ) {
  216. self::$inButtonScopeSet = self::$inScopeSet;
  217. self::$inButtonScopeSet[self::HTML_NAMESPACE]['button'] = true;
  218. }
  219. return self::$inButtonScopeSet;
  220. }
  221. public static $inTableScopeSet = [
  222. self::HTML_NAMESPACE => [
  223. 'html' => true, 'table' => true, 'template' => true
  224. ]
  225. ];
  226. public static $inInvertedSelectScopeSet = [
  227. self::HTML_NAMESPACE => [
  228. 'option' => true, 'optgroup' => true
  229. ]
  230. ];
  231. public static $mathmlTextIntegrationPointSet = [
  232. self::MATHML_NAMESPACE => [
  233. 'mi' => true, 'mo' => true, 'mn' => true, 'ms' => true,
  234. 'mtext' => true
  235. ]
  236. ];
  237. public static $htmlIntegrationPointSet = [
  238. self::SVG_NAMESPACE => [
  239. 'foreignobject' => true,
  240. 'desc' => true,
  241. 'title' => true
  242. ]
  243. ];
  244. // For tidy compatibility.
  245. public static $tidyPWrapSet = [
  246. self::HTML_NAMESPACE => [
  247. 'body' => true, 'blockquote' => true,
  248. // We parse with <body> as the fragment context, but the top-level
  249. // element on the stack is actually <html>. We could use the
  250. // "adjusted current node" everywhere to work around this, but it's
  251. // easier just to add <html> to the p-wrap set.
  252. 'html' => true,
  253. ],
  254. ];
  255. public static $tidyInlineSet = [
  256. self::HTML_NAMESPACE => [
  257. 'a' => true, 'abbr' => true, 'acronym' => true, 'applet' => true,
  258. 'b' => true, 'basefont' => true, 'bdo' => true, 'big' => true,
  259. 'br' => true, 'button' => true, 'cite' => true, 'code' => true,
  260. 'dfn' => true, 'em' => true, 'font' => true, 'i' => true,
  261. 'iframe' => true, 'img' => true, 'input' => true, 'kbd' => true,
  262. 'label' => true, 'legend' => true, 'map' => true, 'object' => true,
  263. 'param' => true, 'q' => true, 'rb' => true, 'rbc' => true,
  264. 'rp' => true, 'rt' => true, 'rtc' => true, 'ruby' => true,
  265. 's' => true, 'samp' => true, 'select' => true, 'small' => true,
  266. 'span' => true, 'strike' => true, 'strong' => true, 'sub' => true,
  267. 'sup' => true, 'textarea' => true, 'tt' => true, 'u' => true,
  268. 'var' => true,
  269. // Those defined in tidy.conf
  270. 'video' => true, 'audio' => true, 'bdi' => true, 'data' => true,
  271. 'time' => true, 'mark' => true,
  272. ],
  273. ];
  274. }
  275. /**
  276. * A BalanceElement is a simplified version of a DOM Node. The main
  277. * difference is that we only keep BalanceElements around for nodes
  278. * currently on the BalanceStack of open elements. As soon as an
  279. * element is closed, with some minor exceptions relating to the
  280. * tree builder "adoption agency algorithm", the element and all its
  281. * children are serialized to a string using the flatten() method.
  282. * This keeps our memory usage low.
  283. *
  284. * @ingroup Parser
  285. * @since 1.27
  286. */
  287. class BalanceElement {
  288. /**
  289. * The namespace of the element.
  290. * @var string $namespaceURI
  291. */
  292. public $namespaceURI;
  293. /**
  294. * The lower-cased name of the element.
  295. * @var string $localName
  296. */
  297. public $localName;
  298. /**
  299. * Attributes for the element, in array form
  300. * @var array $attribs
  301. */
  302. public $attribs;
  303. /**
  304. * Parent of this element, or the string "flat" if this element has
  305. * already been flattened into its parent.
  306. * @var BalanceElement|string|null $parent
  307. */
  308. public $parent;
  309. /**
  310. * An array of children of this element. Typically only the last
  311. * child will be an actual BalanceElement object; the rest will
  312. * be strings, representing either text nodes or flattened
  313. * BalanceElement objects.
  314. * @var BalanceElement[]|string[] $children
  315. */
  316. public $children;
  317. /**
  318. * A unique string identifier for Noah's Ark purposes, lazy initialized
  319. */
  320. private $noahKey;
  321. /**
  322. * The next active formatting element in the list, or null if this is the
  323. * end of the AFE list or if the element is not in the AFE list.
  324. */
  325. public $nextAFE;
  326. /**
  327. * The previous active formatting element in the list, or null if this is
  328. * the start of the list or if the element is not in the AFE list.
  329. */
  330. public $prevAFE;
  331. /**
  332. * The next element in the Noah's Ark species bucket.
  333. */
  334. public $nextNoah;
  335. /**
  336. * Make a new BalanceElement corresponding to the HTML DOM Element
  337. * with the given localname, namespace, and attributes.
  338. *
  339. * @param string $namespaceURI The namespace of the element.
  340. * @param string $localName The lowercased name of the tag.
  341. * @param array $attribs Attributes of the element
  342. */
  343. public function __construct( $namespaceURI, $localName, array $attribs ) {
  344. $this->localName = $localName;
  345. $this->namespaceURI = $namespaceURI;
  346. $this->attribs = $attribs;
  347. $this->contents = '';
  348. $this->parent = null;
  349. $this->children = [];
  350. }
  351. /**
  352. * Remove the given child from this element.
  353. * @param BalanceElement $elt
  354. */
  355. private function removeChild( BalanceElement $elt ) {
  356. Assert::precondition(
  357. $this->parent !== 'flat', "Can't removeChild after flattening $this"
  358. );
  359. Assert::parameter(
  360. $elt->parent === $this, 'elt', 'must have $this as a parent'
  361. );
  362. $idx = array_search( $elt, $this->children, true );
  363. Assert::parameter( $idx !== false, '$elt', 'must be a child of $this' );
  364. $elt->parent = null;
  365. array_splice( $this->children, $idx, 1 );
  366. }
  367. /**
  368. * Find $a in the list of children and insert $b before it.
  369. * @param BalanceElement $a
  370. * @param BalanceElement|string $b
  371. */
  372. public function insertBefore( BalanceElement $a, $b ) {
  373. Assert::precondition(
  374. $this->parent !== 'flat', "Can't insertBefore after flattening."
  375. );
  376. $idx = array_search( $a, $this->children, true );
  377. Assert::parameter( $idx !== false, '$a', 'must be a child of $this' );
  378. if ( is_string( $b ) ) {
  379. array_splice( $this->children, $idx, 0, [ $b ] );
  380. } else {
  381. Assert::parameter( $b->parent !== 'flat', '$b', "Can't be flat" );
  382. if ( $b->parent !== null ) {
  383. $b->parent->removeChild( $b );
  384. }
  385. array_splice( $this->children, $idx, 0, [ $b ] );
  386. $b->parent = $this;
  387. }
  388. }
  389. /**
  390. * Append $elt to the end of the list of children.
  391. * @param BalanceElement|string $elt
  392. */
  393. public function appendChild( $elt ) {
  394. Assert::precondition(
  395. $this->parent !== 'flat', "Can't appendChild after flattening."
  396. );
  397. if ( is_string( $elt ) ) {
  398. array_push( $this->children, $elt );
  399. return;
  400. }
  401. // Remove $elt from parent, if it had one.
  402. if ( $elt->parent !== null ) {
  403. $elt->parent->removeChild( $elt );
  404. }
  405. array_push( $this->children, $elt );
  406. $elt->parent = $this;
  407. }
  408. /**
  409. * Transfer all of the children of $elt to $this.
  410. * @param BalanceElement $elt
  411. */
  412. public function adoptChildren( BalanceElement $elt ) {
  413. Assert::precondition(
  414. $elt->parent !== 'flat', "Can't adoptChildren after flattening."
  415. );
  416. foreach ( $elt->children as $child ) {
  417. if ( !is_string( $child ) ) {
  418. // This is an optimization which avoids an O(n^2) set of
  419. // array_splice operations.
  420. $child->parent = null;
  421. }
  422. $this->appendChild( $child );
  423. }
  424. $elt->children = [];
  425. }
  426. /**
  427. * Flatten this node and all of its children into a string, as specified
  428. * by the HTML serialization specification, and replace this node
  429. * in its parent by that string.
  430. *
  431. * @param array $config Balancer configuration; see Balancer::__construct().
  432. * @return string
  433. *
  434. * @see __toString()
  435. */
  436. public function flatten( array $config ) {
  437. Assert::parameter( $this->parent !== null, '$this', 'must be a child' );
  438. Assert::parameter( $this->parent !== 'flat', '$this', 'already flat' );
  439. $idx = array_search( $this, $this->parent->children, true );
  440. Assert::parameter(
  441. $idx !== false, '$this', 'must be a child of its parent'
  442. );
  443. $tidyCompat = $config['tidyCompat'];
  444. if ( $tidyCompat ) {
  445. $blank = true;
  446. foreach ( $this->children as $elt ) {
  447. if ( !is_string( $elt ) ) {
  448. $elt = $elt->flatten( $config );
  449. }
  450. if ( $blank && preg_match( '/[^\t\n\f\r ]/', $elt ) ) {
  451. $blank = false;
  452. }
  453. }
  454. if ( $this->isHtmlNamed( 'mw:p-wrap' ) ) {
  455. $this->localName = 'p';
  456. } elseif ( $blank ) {
  457. // Add 'mw-empty-elt' class so elements can be hidden via CSS
  458. // for compatibility with legacy tidy.
  459. if ( !count( $this->attribs ) &&
  460. ( $this->localName === 'tr' || $this->localName === 'li' )
  461. ) {
  462. $this->attribs = [ 'class' => "mw-empty-elt" ];
  463. }
  464. $blank = false;
  465. } elseif (
  466. $this->isA( BalanceSets::$extraLinefeedSet ) &&
  467. count( $this->children ) > 0 &&
  468. substr( $this->children[0], 0, 1 ) == "\n"
  469. ) {
  470. // Double the linefeed after pre/listing/textarea
  471. // according to the (old) HTML5 fragment serialization
  472. // algorithm (see https://github.com/whatwg/html/issues/944)
  473. // to ensure this will round-trip.
  474. array_unshift( $this->children, "\n" );
  475. }
  476. $flat = $blank ? '' : "{$this}";
  477. } else {
  478. $flat = "{$this}";
  479. }
  480. $this->parent->children[$idx] = $flat;
  481. $this->parent = 'flat'; // for assertion checking
  482. return $flat;
  483. }
  484. /**
  485. * Serialize this node and all of its children to a string, as specified
  486. * by the HTML serialization specification.
  487. *
  488. * @return string The serialization of the BalanceElement
  489. * @see https://html.spec.whatwg.org/multipage/syntax.html#serialising-html-fragments
  490. */
  491. public function __toString() {
  492. $encAttribs = '';
  493. foreach ( $this->attribs as $name => $value ) {
  494. $encValue = Sanitizer::encodeAttribute( $value );
  495. $encAttribs .= " $name=\"$encValue\"";
  496. }
  497. if ( !$this->isA( BalanceSets::$emptyElementSet ) ) {
  498. $out = "<{$this->localName}{$encAttribs}>";
  499. $len = strlen( $out );
  500. // flatten children
  501. foreach ( $this->children as $elt ) {
  502. $out .= "{$elt}";
  503. }
  504. $out .= "</{$this->localName}>";
  505. } else {
  506. $out = "<{$this->localName}{$encAttribs} />";
  507. Assert::invariant(
  508. count( $this->children ) === 0,
  509. "Empty elements shouldn't have children."
  510. );
  511. }
  512. return $out;
  513. }
  514. // Utility functions on BalanceElements.
  515. /**
  516. * Determine if $this represents a specific HTML tag, is a member of
  517. * a tag set, or is equal to another BalanceElement.
  518. *
  519. * @param BalanceElement|array|string $set The target BalanceElement,
  520. * set (from the BalanceSets class), or string (HTML tag name).
  521. * @return bool
  522. */
  523. public function isA( $set ) {
  524. if ( $set instanceof BalanceElement ) {
  525. return $this === $set;
  526. } elseif ( is_array( $set ) ) {
  527. return isset( $set[$this->namespaceURI] ) &&
  528. isset( $set[$this->namespaceURI][$this->localName] );
  529. } else {
  530. // assume this is an HTML element name.
  531. return $this->isHtml() && $this->localName === $set;
  532. }
  533. }
  534. /**
  535. * Determine if this element is an HTML element with the specified name
  536. * @param string $tagName
  537. * @return bool
  538. */
  539. public function isHtmlNamed( $tagName ) {
  540. return $this->namespaceURI === BalanceSets::HTML_NAMESPACE
  541. && $this->localName === $tagName;
  542. }
  543. /**
  544. * Determine if $this represents an element in the HTML namespace.
  545. *
  546. * @return bool
  547. */
  548. public function isHtml() {
  549. return $this->namespaceURI === BalanceSets::HTML_NAMESPACE;
  550. }
  551. /**
  552. * Determine if $this represents a MathML text integration point,
  553. * as defined in the HTML5 specification.
  554. *
  555. * @return bool
  556. * @see https://html.spec.whatwg.org/multipage/syntax.html#mathml-text-integration-point
  557. */
  558. public function isMathmlTextIntegrationPoint() {
  559. return $this->isA( BalanceSets::$mathmlTextIntegrationPointSet );
  560. }
  561. /**
  562. * Determine if $this represents an HTML integration point,
  563. * as defined in the HTML5 specification.
  564. *
  565. * @return bool
  566. * @see https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
  567. */
  568. public function isHtmlIntegrationPoint() {
  569. if ( $this->isA( BalanceSets::$htmlIntegrationPointSet ) ) {
  570. return true;
  571. }
  572. if (
  573. $this->namespaceURI === BalanceSets::MATHML_NAMESPACE &&
  574. $this->localName === 'annotation-xml' &&
  575. isset( $this->attribs['encoding'] ) &&
  576. ( strcasecmp( $this->attribs['encoding'], 'text/html' ) == 0 ||
  577. strcasecmp( $this->attribs['encoding'], 'application/xhtml+xml' ) == 0 )
  578. ) {
  579. return true;
  580. }
  581. return false;
  582. }
  583. /**
  584. * Get a string key for the Noah's Ark algorithm
  585. * @return string
  586. */
  587. public function getNoahKey() {
  588. if ( $this->noahKey === null ) {
  589. $attribs = $this->attribs;
  590. ksort( $attribs );
  591. $this->noahKey = serialize( [ $this->namespaceURI, $this->localName, $attribs ] );
  592. }
  593. return $this->noahKey;
  594. }
  595. }
  596. /**
  597. * The "stack of open elements" as defined in the HTML5 tree builder
  598. * spec. This contains methods to ensure that content (start tags, text)
  599. * are inserted at the correct place in the output string, and to
  600. * flatten BalanceElements are they are closed to avoid holding onto
  601. * a complete DOM tree for the document in memory.
  602. *
  603. * The stack defines a PHP iterator to traverse it in "reverse order",
  604. * that is, the most-recently-added element is visited first in a
  605. * foreach loop.
  606. *
  607. * @ingroup Parser
  608. * @since 1.27
  609. * @see https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements
  610. */
  611. class BalanceStack implements IteratorAggregate {
  612. /**
  613. * Backing storage for the stack.
  614. * @var BalanceElement[] $elements
  615. */
  616. private $elements = [];
  617. /**
  618. * Foster parent mode determines how nodes are inserted into the
  619. * stack.
  620. * @var bool $fosterParentMode
  621. * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
  622. */
  623. public $fosterParentMode = false;
  624. /**
  625. * Configuration options governing flattening.
  626. * @var array $config
  627. * @see Balancer::__construct()
  628. */
  629. private $config;
  630. /**
  631. * Reference to the current element
  632. */
  633. public $currentNode;
  634. /**
  635. * Create a new BalanceStack with a single BalanceElement on it,
  636. * representing the root &lt;html&gt; node.
  637. * @param array $config Balancer configuration; see Balancer::_construct().
  638. */
  639. public function __construct( array $config ) {
  640. // always a root <html> element on the stack
  641. array_push(
  642. $this->elements,
  643. new BalanceElement( BalanceSets::HTML_NAMESPACE, 'html', [] )
  644. );
  645. $this->currentNode = $this->elements[0];
  646. $this->config = $config;
  647. }
  648. /**
  649. * Return a string representing the output of the tree builder:
  650. * all the children of the root &lt;html&gt; node.
  651. * @return string
  652. */
  653. public function getOutput() {
  654. // Don't include the outer '<html>....</html>'
  655. $out = '';
  656. foreach ( $this->elements[0]->children as $elt ) {
  657. $out .= is_string( $elt ) ? $elt :
  658. $elt->flatten( $this->config );
  659. }
  660. return $out;
  661. }
  662. /**
  663. * Insert a comment at the appropriate place for inserting a node.
  664. * @param string $value Content of the comment.
  665. * @return string
  666. * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-comment
  667. */
  668. public function insertComment( $value ) {
  669. // Just another type of text node, except for tidy p-wrapping.
  670. return $this->insertText( '<!--' . $value . '-->', true );
  671. }
  672. /**
  673. * Insert text at the appropriate place for inserting a node.
  674. * @param string $value
  675. * @param bool $isComment
  676. * @return string
  677. * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
  678. */
  679. public function insertText( $value, $isComment = false ) {
  680. if (
  681. $this->fosterParentMode &&
  682. $this->currentNode->isA( BalanceSets::$tableSectionRowSet )
  683. ) {
  684. $this->fosterParent( $value );
  685. } elseif (
  686. $this->config['tidyCompat'] && !$isComment &&
  687. $this->currentNode->isA( BalanceSets::$tidyPWrapSet )
  688. ) {
  689. $this->insertHTMLElement( 'mw:p-wrap', [] );
  690. return $this->insertText( $value );
  691. } else {
  692. $this->currentNode->appendChild( $value );
  693. }
  694. }
  695. /**
  696. * Insert a BalanceElement at the appropriate place, pushing it
  697. * on to the open elements stack.
  698. * @param string $namespaceURI The element namespace
  699. * @param string $tag The tag name
  700. * @param string $attribs Normalized attributes, as a string.
  701. * @return BalanceElement
  702. * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-a-foreign-element
  703. */
  704. public function insertForeignElement( $namespaceURI, $tag, $attribs ) {
  705. return $this->insertElement(
  706. new BalanceElement( $namespaceURI, $tag, $attribs )
  707. );
  708. }
  709. /**
  710. * Insert an HTML element at the appropriate place, pushing it on to
  711. * the open elements stack.
  712. * @param string $tag The tag name
  713. * @param string $attribs Normalized attributes, as a string.
  714. * @return BalanceElement
  715. * @see https://html.spec.whatwg.org/multipage/syntax.html#insert-an-html-element
  716. */
  717. public function insertHTMLElement( $tag, $attribs ) {
  718. return $this->insertForeignElement(
  719. BalanceSets::HTML_NAMESPACE, $tag, $attribs
  720. );
  721. }
  722. /**
  723. * Insert an element at the appropriate place and push it on to the
  724. * open elements stack.
  725. * @param BalanceElement $elt
  726. * @return BalanceElement
  727. * @see https://html.spec.whatwg.org/multipage/syntax.html#appropriate-place-for-inserting-a-node
  728. */
  729. public function insertElement( BalanceElement $elt ) {
  730. if (
  731. $this->currentNode->isHtmlNamed( 'mw:p-wrap' ) &&
  732. !$elt->isA( BalanceSets::$tidyInlineSet )
  733. ) {
  734. // Tidy compatibility.
  735. $this->pop();
  736. }
  737. if (
  738. $this->fosterParentMode &&
  739. $this->currentNode->isA( BalanceSets::$tableSectionRowSet )
  740. ) {
  741. $elt = $this->fosterParent( $elt );
  742. } else {
  743. $this->currentNode->appendChild( $elt );
  744. }
  745. Assert::invariant( $elt->parent !== null, "$elt must be in tree" );
  746. Assert::invariant( $elt->parent !== 'flat', "$elt must not have been previous flattened" );
  747. array_push( $this->elements, $elt );
  748. $this->currentNode = $elt;
  749. return $elt;
  750. }
  751. /**
  752. * Determine if the stack has $tag in scope.
  753. * @param BalanceElement|array|string $tag
  754. * @return bool
  755. * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
  756. */
  757. public function inScope( $tag ) {
  758. return $this->inSpecificScope( $tag, BalanceSets::$inScopeSet );
  759. }
  760. /**
  761. * Determine if the stack has $tag in button scope.
  762. * @param BalanceElement|array|string $tag
  763. * @return bool
  764. * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
  765. */
  766. public function inButtonScope( $tag ) {
  767. return $this->inSpecificScope( $tag, BalanceSets::inButtonScopeSet() );
  768. }
  769. /**
  770. * Determine if the stack has $tag in list item scope.
  771. * @param BalanceElement|array|string $tag
  772. * @return bool
  773. * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-list-item-scope
  774. */
  775. public function inListItemScope( $tag ) {
  776. return $this->inSpecificScope( $tag, BalanceSets::inListItemScopeSet() );
  777. }
  778. /**
  779. * Determine if the stack has $tag in table scope.
  780. * @param BalanceElement|array|string $tag
  781. * @return bool
  782. * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-table-scope
  783. */
  784. public function inTableScope( $tag ) {
  785. return $this->inSpecificScope( $tag, BalanceSets::$inTableScopeSet );
  786. }
  787. /**
  788. * Determine if the stack has $tag in select scope.
  789. * @param BalanceElement|array|string $tag
  790. * @return bool
  791. * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-select-scope
  792. */
  793. public function inSelectScope( $tag ) {
  794. // Can't use inSpecificScope to implement this, since it involves
  795. // *inverting* a set of tags. Implement manually.
  796. foreach ( $this as $elt ) {
  797. if ( $elt->isA( $tag ) ) {
  798. return true;
  799. }
  800. if ( !$elt->isA( BalanceSets::$inInvertedSelectScopeSet ) ) {
  801. return false;
  802. }
  803. }
  804. return false;
  805. }
  806. /**
  807. * Determine if the stack has $tag in a specific scope, $set.
  808. * @param BalanceElement|array|string $tag
  809. * @param BalanceElement|array|string $set
  810. * @return bool
  811. * @see https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope
  812. */
  813. public function inSpecificScope( $tag, $set ) {
  814. foreach ( $this as $elt ) {
  815. if ( $elt->isA( $tag ) ) {
  816. return true;
  817. }
  818. if ( $elt->isA( $set ) ) {
  819. return false;
  820. }
  821. }
  822. return false;
  823. }
  824. /**
  825. * Generate implied end tags.
  826. * @param string $butnot
  827. * @param bool $thorough True if we should generate end tags thoroughly.
  828. * @see https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
  829. */
  830. public function generateImpliedEndTags( $butnot = null, $thorough = false ) {
  831. $endTagSet = $thorough ?
  832. BalanceSets::$thoroughImpliedEndTagsSet :
  833. BalanceSets::$impliedEndTagsSet;
  834. while ( $this->currentNode ) {
  835. if ( $butnot !== null && $this->currentNode->isHtmlNamed( $butnot ) ) {
  836. break;
  837. }
  838. if ( !$this->currentNode->isA( $endTagSet ) ) {
  839. break;
  840. }
  841. $this->pop();
  842. }
  843. }
  844. /**
  845. * Return the adjusted current node.
  846. * @param string $fragmentContext
  847. * @return string
  848. */
  849. public function adjustedCurrentNode( $fragmentContext ) {
  850. return ( $fragmentContext && count( $this->elements ) === 1 ) ?
  851. $fragmentContext : $this->currentNode;
  852. }
  853. /**
  854. * Return an iterator over this stack which visits the current node
  855. * first, and the root node last.
  856. * @return \Iterator
  857. */
  858. public function getIterator() {
  859. return new ReverseArrayIterator( $this->elements );
  860. }
  861. /**
  862. * Return the BalanceElement at the given position $idx, where
  863. * position 0 represents the root element.
  864. * @param int $idx
  865. * @return BalanceElement
  866. */
  867. public function node( $idx ) {
  868. return $this->elements[ $idx ];
  869. }
  870. /**
  871. * Replace the element at position $idx in the BalanceStack with $elt.
  872. * @param int $idx
  873. * @param BalanceElement $elt
  874. */
  875. public function replaceAt( $idx, BalanceElement $elt ) {
  876. Assert::precondition(
  877. $this->elements[$idx]->parent !== 'flat',
  878. 'Replaced element should not have already been flattened.'
  879. );
  880. Assert::precondition(
  881. $elt->parent !== 'flat',
  882. 'New element should not have already been flattened.'
  883. );
  884. $this->elements[$idx] = $elt;
  885. if ( $idx === count( $this->elements ) - 1 ) {
  886. $this->currentNode = $elt;
  887. }
  888. }
  889. /**
  890. * Return the position of the given BalanceElement, set, or
  891. * HTML tag name string in the BalanceStack.
  892. * @param BalanceElement|array|string $tag
  893. * @return int
  894. */
  895. public function indexOf( $tag ) {
  896. for ( $i = count( $this->elements ) - 1; $i >= 0; $i-- ) {
  897. if ( $this->elements[$i]->isA( $tag ) ) {
  898. return $i;
  899. }
  900. }
  901. return -1;
  902. }
  903. /**
  904. * Return the number of elements currently in the BalanceStack.
  905. * @return int
  906. */
  907. public function length() {
  908. return count( $this->elements );
  909. }
  910. /**
  911. * Remove the current node from the BalanceStack, flattening it
  912. * in the process.
  913. */
  914. public function pop() {
  915. $elt = array_pop( $this->elements );
  916. if ( count( $this->elements ) ) {
  917. $this->currentNode = $this->elements[ count( $this->elements ) - 1 ];
  918. } else {
  919. $this->currentNode = null;
  920. }
  921. if ( !$elt->isHtmlNamed( 'mw:p-wrap' ) ) {
  922. $elt->flatten( $this->config );
  923. }
  924. }
  925. /**
  926. * Remove all nodes up to and including position $idx from the
  927. * BalanceStack, flattening them in the process.
  928. * @param int $idx
  929. */
  930. public function popTo( $idx ) {
  931. for ( $length = count( $this->elements ); $length > $idx; $length-- ) {
  932. $this->pop();
  933. }
  934. }
  935. /**
  936. * Pop elements off the stack up to and including the first
  937. * element with the specified HTML tagname (or matching the given
  938. * set).
  939. * @param BalanceElement|array|string $tag
  940. */
  941. public function popTag( $tag ) {
  942. while ( $this->currentNode ) {
  943. if ( $this->currentNode->isA( $tag ) ) {
  944. $this->pop();
  945. break;
  946. }
  947. $this->pop();
  948. }
  949. }
  950. /**
  951. * Pop elements off the stack *not including* the first element
  952. * in the specified set.
  953. * @param BalanceElement|array|string $set
  954. */
  955. public function clearToContext( $set ) {
  956. // Note that we don't loop to 0. Never pop the <html> elt off.
  957. for ( $length = count( $this->elements ); $length > 1; $length-- ) {
  958. if ( $this->currentNode->isA( $set ) ) {
  959. break;
  960. }
  961. $this->pop();
  962. }
  963. }
  964. /**
  965. * Remove the given $elt from the BalanceStack, optionally
  966. * flattening it in the process.
  967. * @param BalanceElement $elt The element to remove.
  968. * @param bool $flatten Whether to flatten the removed element.
  969. */
  970. public function removeElement( BalanceElement $elt, $flatten = true ) {
  971. Assert::parameter(
  972. $elt->parent !== 'flat',
  973. '$elt',
  974. '$elt should not already have been flattened.'
  975. );
  976. Assert::parameter(
  977. $elt->parent->parent !== 'flat',
  978. '$elt',
  979. 'The parent of $elt should not already have been flattened.'
  980. );
  981. $idx = array_search( $elt, $this->elements, true );
  982. Assert::parameter( $idx !== false, '$elt', 'must be in stack' );
  983. array_splice( $this->elements, $idx, 1 );
  984. if ( $idx === count( $this->elements ) ) {
  985. $this->currentNode = $this->elements[$idx - 1];
  986. }
  987. if ( $flatten ) {
  988. // serialize $elt into its parent
  989. // otherwise, it will eventually serialize when the parent
  990. // is serialized, we just hold onto the memory for its
  991. // tree of objects a little longer.
  992. $elt->flatten( $this->config );
  993. }
  994. Assert::postcondition(
  995. array_search( $elt, $this->elements, true ) === false,
  996. '$elt should no longer be in open elements stack'
  997. );
  998. }
  999. /**
  1000. * Find $a in the BalanceStack and insert $b after it.
  1001. * @param BalanceElement $a
  1002. * @param BalanceElement $b
  1003. */
  1004. public function insertAfter( BalanceElement $a, BalanceElement $b ) {
  1005. $idx = $this->indexOf( $a );
  1006. Assert::parameter( $idx !== false, '$a', 'must be in stack' );
  1007. if ( $idx === count( $this->elements ) - 1 ) {
  1008. array_push( $this->elements, $b );
  1009. $this->currentNode = $b;
  1010. } else {
  1011. array_splice( $this->elements, $idx + 1, 0, [ $b ] );
  1012. }
  1013. }
  1014. // Fostering and adoption.
  1015. /**
  1016. * Foster parent the given $elt in the stack of open elements.
  1017. * @param BalanceElement|string $elt
  1018. * @return BalanceElement|string
  1019. *
  1020. * @see https://html.spec.whatwg.org/multipage/syntax.html#foster-parent
  1021. */
  1022. private function fosterParent( $elt ) {
  1023. $lastTable = $this->indexOf( 'table' );
  1024. $lastTemplate = $this->indexOf( 'template' );
  1025. $parent = null;
  1026. $before = null;
  1027. if ( $lastTemplate >= 0 && ( $lastTable < 0 || $lastTemplate > $lastTable ) ) {
  1028. $parent = $this->elements[$lastTemplate];
  1029. } elseif ( $lastTable >= 0 ) {
  1030. $parent = $this->elements[$lastTable]->parent;
  1031. // Assume all tables have parents, since we're not running scripts!
  1032. Assert::invariant(
  1033. $parent !== null, "All tables should have parents"
  1034. );
  1035. $before = $this->elements[$lastTable];
  1036. } else {
  1037. $parent = $this->elements[0]; // the `html` element.
  1038. }
  1039. if ( $this->config['tidyCompat'] ) {
  1040. if ( is_string( $elt ) ) {
  1041. // We're fostering text: do we need a p-wrapper?
  1042. if ( $parent->isA( BalanceSets::$tidyPWrapSet ) ) {
  1043. $this->insertHTMLElement( 'mw:p-wrap', [] );
  1044. $this->insertText( $elt );
  1045. return $elt;
  1046. }
  1047. } else {
  1048. // We're fostering an element; do we need to merge p-wrappers?
  1049. if ( $elt->isHtmlNamed( 'mw:p-wrap' ) ) {
  1050. $idx = $before ?
  1051. array_search( $before, $parent->children, true ) :
  1052. count( $parent->children );
  1053. $after = $idx > 0 ? $parent->children[$idx - 1] : '';
  1054. if (
  1055. $after instanceof BalanceElement &&
  1056. $after->isHtmlNamed( 'mw:p-wrap' )
  1057. ) {
  1058. return $after; // Re-use existing p-wrapper.
  1059. }
  1060. }
  1061. }
  1062. }
  1063. if ( $before ) {
  1064. $parent->insertBefore( $before, $elt );
  1065. } else {
  1066. $parent->appendChild( $elt );
  1067. }
  1068. return $elt;
  1069. }
  1070. /**
  1071. * Run the "adoption agency algoritm" (AAA) for the given subject
  1072. * tag name.
  1073. * @param string $tag The subject tag name.
  1074. * @param BalanceActiveFormattingElements $afe The current
  1075. * active formatting elements list.
  1076. * @return true if the adoption agency algorithm "did something", false
  1077. * if more processing is required by the caller.
  1078. * @see https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm
  1079. */
  1080. public function adoptionAgency( $tag, $afe ) {
  1081. // If the current node is an HTML element whose tag name is subject,
  1082. // and the current node is not in the list of active formatting
  1083. // elements, then pop the current node off the stack of open
  1084. // elements and abort these steps.
  1085. if (
  1086. $this->currentNode->isHtmlNamed( $tag ) &&
  1087. !$afe->isInList( $this->currentNode )
  1088. ) {
  1089. $this->pop();
  1090. return true; // no more handling required
  1091. }
  1092. // Outer loop: If outer loop counter is greater than or
  1093. // equal to eight, then abort these steps.
  1094. for ( $outer = 0; $outer < 8; $outer++ ) {
  1095. // Let the formatting element be the last element in the list
  1096. // of active formatting elements that: is between the end of
  1097. // the list and the last scope marker in the list, if any, or
  1098. // the start of the list otherwise, and has the same tag name
  1099. // as the token.
  1100. $fmtElt = $afe->findElementByTag( $tag );
  1101. // If there is no such node, then abort these steps and instead
  1102. // act as described in the "any other end tag" entry below.
  1103. if ( !$fmtElt ) {
  1104. return false; // false means handle by the default case
  1105. }
  1106. // Otherwise, if there is such a node, but that node is not in
  1107. // the stack of open elements, then this is a parse error;
  1108. // remove the element from the list, and abort these steps.
  1109. $index = $this->indexOf( $fmtElt );
  1110. if ( $index < 0 ) {
  1111. $afe->remove( $fmtElt );
  1112. return true; // true means no more handling required
  1113. }
  1114. // Otherwise, if there is such a node, and that node is also in
  1115. // the stack of open elements, but the element is not in scope,
  1116. // then this is a parse error; ignore the token, and abort
  1117. // these steps.
  1118. if ( !$this->inScope( $fmtElt ) ) {
  1119. return true;
  1120. }
  1121. // Let the furthest block be the topmost node in the stack of
  1122. // open elements that is lower in the stack than the formatting
  1123. // element, and is an element in the special category. There
  1124. // might not be one.
  1125. $furthestBlock = null;
  1126. $furthestBlockIndex = -1;
  1127. $stackLength = $this->length();
  1128. for ( $i = $index + 1; $i < $stackLength; $i++ ) {
  1129. if ( $this->node( $i )->isA( BalanceSets::$specialSet ) ) {
  1130. $furthestBlock = $this->node( $i );
  1131. $furthestBlockIndex = $i;
  1132. break;
  1133. }
  1134. }
  1135. // If there is no furthest block, then the UA must skip the
  1136. // subsequent steps and instead just pop all the nodes from the
  1137. // bottom of the stack of open elements, from the current node
  1138. // up to and including the formatting element, and remove the
  1139. // formatting element from the list of active formatting
  1140. // elements.
  1141. if ( !$furthestBlock ) {
  1142. $this->popTag( $fmtElt );
  1143. $afe->remove( $fmtElt );
  1144. return true;
  1145. }
  1146. // Let the common ancestor be the element immediately above
  1147. // the formatting element in the stack of open elements.
  1148. $ancestor = $this->node( $index - 1 );
  1149. // Let a bookmark note the position of the formatting
  1150. // element in the list of active formatting elements
  1151. // relative to the elements on either side of it in the
  1152. // list.
  1153. $BOOKMARK = new BalanceElement( '[bookmark]', '[bookmark]', [] );
  1154. $afe->insertAfter( $fmtElt, $BOOKMARK );
  1155. // Let node and last node be the furthest block.
  1156. $node = $furthestBlock;
  1157. $lastNode = $furthestBlock;
  1158. $nodeIndex = $furthestBlockIndex;
  1159. $isAFE = false;
  1160. // Inner loop
  1161. for ( $inner = 1; true; $inner++ ) {
  1162. // Let node be the element immediately above node in
  1163. // the stack of open elements, or if node is no longer
  1164. // in the stack of open elements (e.g. because it got
  1165. // removed by this algorithm), the element that was
  1166. // immediately above node in the stack of open elements
  1167. // before node was removed.
  1168. $node = $this->node( --$nodeIndex );
  1169. // If node is the formatting element, then go
  1170. // to the next step in the overall algorithm.
  1171. if ( $node === $fmtElt ) break;
  1172. // If the inner loop counter is greater than three and node
  1173. // is in the list of active formatting elements, then remove
  1174. // node from the list of active formatting elements.
  1175. $isAFE = $afe->isInList( $node );
  1176. if ( $inner > 3 && $isAFE ) {
  1177. $afe->remove( $node );
  1178. $isAFE = false;
  1179. }
  1180. // If node is not in the list of active formatting
  1181. // elements, then remove node from the stack of open
  1182. // elements and then go back to the step labeled inner
  1183. // loop.
  1184. if ( !$isAFE ) {
  1185. // Don't flatten here, since we're about to relocate
  1186. // parts of this $node.
  1187. $this->removeElement( $node, false );
  1188. continue;
  1189. }
  1190. // Create an element for the token for which the
  1191. // element node was created with common ancestor as
  1192. // the intended parent, replace the entry for node
  1193. // in the list of active formatting elements with an
  1194. // entry for the new element, replace the entry for
  1195. // node in the stack of open elements with an entry for
  1196. // the new element, and let node be the new element.
  1197. $newElt = new BalanceElement(
  1198. $node->namespaceURI, $node->localName, $node->attribs );
  1199. $afe->replace( $node, $newElt );
  1200. $this->replaceAt( $nodeIndex, $newElt );
  1201. $node = $newElt;
  1202. // If last node is the furthest block, then move the
  1203. // aforementioned bookmark to be immediately after the
  1204. // new node in the list of active formatting elements.
  1205. if ( $lastNode === $furthestBlock ) {
  1206. $afe->remove( $BOOKMARK );
  1207. $afe->insertAfter( $newElt, $BOOKMARK );
  1208. }
  1209. // Insert last node into node, first removing it from
  1210. // its previous parent node if any.
  1211. $node->appendChild( $lastNode );
  1212. // Let last node be node.
  1213. $lastNode = $node;
  1214. }
  1215. // If the common ancestor node is a table, tbody, tfoot,
  1216. // thead, or tr element, then, foster parent whatever last
  1217. // node ended up being in the previous step, first removing
  1218. // it from its previous parent node if any.
  1219. if (
  1220. $this->fosterParentMode &&
  1221. $ancestor->isA( BalanceSets::$tableSectionRowSet )
  1222. ) {
  1223. $this->fosterParent( $lastNode );
  1224. } else {
  1225. // Otherwise, append whatever last node ended up being in
  1226. // the previous step to the common ancestor node, first
  1227. // removing it from its previous parent node if any.
  1228. $ancestor->appendChild( $lastNode );
  1229. }
  1230. // Create an element for the token for which the
  1231. // formatting element was created, with furthest block
  1232. // as the intended parent.
  1233. $newElt2 = new BalanceElement(
  1234. $fmtElt->namespaceURI, $fmtElt->localName, $fmtElt->attribs );
  1235. // Take all of the child nodes of the furthest block and
  1236. // append them to the element created in the last step.
  1237. $newElt2->adoptChildren( $furthestBlock );
  1238. // Append that new element to the furthest block.
  1239. $furthestBlock->appendChild( $newElt2 );
  1240. // Remove the formatting element from the list of active
  1241. // formatting elements, and insert the new element into the
  1242. // list of active formatting elements at the position of
  1243. // the aforementioned bookmark.
  1244. $afe->remove( $fmtElt );
  1245. $afe->replace( $BOOKMARK, $newElt2 );
  1246. // Remove the formatting element from the stack of open
  1247. // elements, and insert the new element into the stack of
  1248. // open elements immediately below the position of the
  1249. // furthest block in that stack.
  1250. $this->removeElement( $fmtElt );
  1251. $this->insertAfter( $furthestBlock, $newElt2 );
  1252. }
  1253. return true;
  1254. }
  1255. /**
  1256. * Return the contents of the open elements stack as a string for
  1257. * debugging.
  1258. * @return string
  1259. */
  1260. public function __toString() {
  1261. $r = [];
  1262. foreach ( $this->elements as $elt ) {
  1263. array_push( $r, $elt->localName );
  1264. }
  1265. return implode( ' ', $r );
  1266. }
  1267. }
  1268. /**
  1269. * A pseudo-element used as a marker in the list of active formatting elements
  1270. *
  1271. * @ingroup Parser
  1272. * @since 1.27
  1273. */
  1274. class BalanceMarker {
  1275. public $nextAFE;
  1276. public $prevAFE;
  1277. }
  1278. /**
  1279. * The list of active formatting elements, which is used to handle
  1280. * mis-nested formatting element tags in the HTML5 tree builder
  1281. * specification.
  1282. *
  1283. * @ingroup Parser
  1284. * @since 1.27
  1285. * @see https://html.spec.whatwg.org/multipage/syntax.html#list-of-active-formatting-elements
  1286. */
  1287. class BalanceActiveFormattingElements {
  1288. /** The last (most recent) element in the list */
  1289. private $tail;
  1290. /** The first (least recent) element in the list */
  1291. private $head;
  1292. /**
  1293. * An array of arrays representing the population of elements in each bucket
  1294. * according to the Noah's Ark clause. The outer array is stack-like, with each
  1295. * integer-indexed element representing a segment of the list, bounded by
  1296. * markers. The first element represents the segment of the list before the
  1297. * first marker.
  1298. *
  1299. * The inner arrays are indexed by "Noah key", which is a string which uniquely
  1300. * identifies each bucket according to the rules in the spec. The value in
  1301. * the inner array is the first (least recently inserted) element in the bucket,
  1302. * and subsequent members of the bucket can be found by iterating through the
  1303. * singly-linked list via $node->nextNoah.
  1304. *
  1305. * This is optimised for the most common case of inserting into a bucket
  1306. * with zero members, and deleting a bucket containing one member. In the
  1307. * worst case, iteration through the list is still O(1) in the document
  1308. * size, since each bucket can have at most 3 members.
  1309. */
  1310. private $noahTableStack = [ [] ];
  1311. public function __destruct() {
  1312. $next = null;
  1313. for ( $node = $this->head; $node; $node = $next ) {
  1314. $next = $node->nextAFE;
  1315. $node->prevAFE = $node->nextAFE = $node->nextNoah = null;
  1316. }
  1317. $this->head = $this->tail = $this->noahTableStack = null;
  1318. }
  1319. public function insertMarker() {
  1320. $elt = new BalanceMarker;
  1321. if ( $this->tail ) {
  1322. $this->tail->nextAFE = $elt;
  1323. $elt->prevAFE = $this->tail;
  1324. } else {
  1325. $this->head = $elt;
  1326. }
  1327. $this->tail = $elt;
  1328. $this->noahTableStack[] = [];
  1329. }
  1330. /**
  1331. * Follow the steps required when the spec requires us to "push onto the
  1332. * list of active formatting elements".
  1333. * @param BalanceElement $elt
  1334. */
  1335. public function push( BalanceElement $elt ) {
  1336. // Must not be in the list already
  1337. if ( $elt->prevAFE !== null || $this->head === $elt ) {
  1338. throw new ParameterAssertionException( '$elt',
  1339. 'Cannot insert a node into the AFE list twice' );
  1340. }
  1341. // "Noah's Ark clause" -- if there are already three copies of
  1342. // this element before we encounter a marker, then drop the last
  1343. // one.
  1344. $noahKey = $elt->getNoahKey();
  1345. $table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
  1346. if ( !isset( $table[$noahKey] ) ) {
  1347. $table[$noahKey] = $elt;
  1348. } else {
  1349. $count = 1;
  1350. $head = $tail = $table[$noahKey];
  1351. while ( $tail->nextNoah ) {
  1352. $tail = $tail->nextNoah;
  1353. $count++;
  1354. }
  1355. if ( $count >= 3 ) {
  1356. $this->remove( $head );
  1357. }
  1358. $tail->nextNoah = $elt;
  1359. }
  1360. // Add to the main AFE list
  1361. if ( $this->tail ) {
  1362. $this->tail->nextAFE = $elt;
  1363. $elt->prevAFE = $this->tail;
  1364. } else {
  1365. $this->head = $elt;
  1366. }
  1367. $this->tail = $elt;
  1368. }
  1369. /**
  1370. * Follow the steps required when the spec asks us to "clear the list of
  1371. * active formatting elements up to the last marker".
  1372. */
  1373. public function clearToMarker() {
  1374. // Iterate back through the list starting from the tail
  1375. $tail = $this->tail;
  1376. while ( $tail && !( $tail instanceof BalanceMarker ) ) {
  1377. // Unlink the element
  1378. $prev = $tail->prevAFE;
  1379. $tail->prevAFE = null;
  1380. if ( $prev ) {
  1381. $prev->nextAFE = null;
  1382. }
  1383. $tail->nextNoah = null;
  1384. $tail = $prev;
  1385. }
  1386. // If we finished on a marker, unlink it and pop it off the Noah table stack
  1387. if ( $tail ) {
  1388. $prev = $tail->prevAFE;
  1389. if ( $prev ) {
  1390. $prev->nextAFE = null;
  1391. }
  1392. $tail = $prev;
  1393. array_pop( $this->noahTableStack );
  1394. } else {
  1395. // No marker: wipe the top-level Noah table (which is the only one)
  1396. $this->noahTableStack[0] = [];
  1397. }
  1398. // If we removed all the elements, clear the head pointer
  1399. if ( !$tail ) {
  1400. $this->head = null;
  1401. }
  1402. $this->tail = $tail;
  1403. }
  1404. /**
  1405. * Find and return the last element with the specified tag between the
  1406. * end of the list and the last marker on the list.
  1407. * Used when parsing &lt;a&gt; "in body mode".
  1408. * @param string $tag
  1409. * @return null|Node
  1410. */
  1411. public function findElementByTag( $tag ) {
  1412. $elt = $this->tail;
  1413. while ( $elt && !( $elt instanceof BalanceMarker ) ) {
  1414. if ( $elt->localName === $tag ) {
  1415. return $elt;
  1416. }
  1417. $elt = $elt->prevAFE;
  1418. }
  1419. return null;
  1420. }
  1421. /**
  1422. * Determine whether an element is in the list of formatting elements.
  1423. * @param BalanceElement $elt
  1424. * @return bool
  1425. */
  1426. public function isInList( BalanceElement $elt ) {
  1427. return $this->head === $elt || $elt->prevAFE;
  1428. }
  1429. /**
  1430. * Find the element $elt in the list and remove it.
  1431. * Used when parsing &lt;a&gt; in body mode.
  1432. *
  1433. * @param BalanceElement $elt
  1434. */
  1435. public function remove( BalanceElement $elt ) {
  1436. if ( $this->head !== $elt && !$elt->prevAFE ) {
  1437. throw new ParameterAssertionException( '$elt',
  1438. "Attempted to remove an element which is not in the AFE list" );
  1439. }
  1440. // Update head and tail pointers
  1441. if ( $this->head === $elt ) {
  1442. $this->head = $elt->nextAFE;
  1443. }
  1444. if ( $this->tail === $elt ) {
  1445. $this->tail = $elt->prevAFE;
  1446. }
  1447. // Update previous element
  1448. if ( $elt->prevAFE ) {
  1449. $elt->prevAFE->nextAFE = $elt->nextAFE;
  1450. }
  1451. // Update next element
  1452. if ( $elt->nextAFE ) {
  1453. $elt->nextAFE->prevAFE = $elt->prevAFE;
  1454. }
  1455. // Clear pointers so that isInList() etc. will work
  1456. $elt->prevAFE = $elt->nextAFE = null;
  1457. // Update Noah list
  1458. $this->removeFromNoahList( $elt );
  1459. }
  1460. private function addToNoahList( BalanceElement $elt ) {
  1461. $noahKey = $elt->getNoahKey();
  1462. $table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
  1463. if ( !isset( $table[$noahKey] ) ) {
  1464. $table[$noahKey] = $elt;
  1465. } else {
  1466. $tail = $table[$noahKey];
  1467. while ( $tail->nextNoah ) {
  1468. $tail = $tail->nextNoah;
  1469. }
  1470. $tail->nextNoah = $elt;
  1471. }
  1472. }
  1473. private function removeFromNoahList( BalanceElement $elt ) {
  1474. $table =& $this->noahTableStack[ count( $this->noahTableStack ) - 1 ];
  1475. $key = $elt->getNoahKey();
  1476. $noahElt = $table[$key];
  1477. if ( $noahElt === $elt ) {
  1478. if ( $noahElt->nextNoah ) {
  1479. $table[$key] = $noahElt->nextNoah;
  1480. $noahElt->nextNoah = null;
  1481. } else {
  1482. unset( $table[$key] );
  1483. }
  1484. } else {
  1485. do {
  1486. $prevNoahElt = $noahElt;
  1487. $noahElt = $prevNoahElt->nextNoah;
  1488. if ( $noahElt === $elt ) {
  1489. // Found it, unlink
  1490. $prevNoahElt->nextNoah = $elt->nextNoah;
  1491. $elt->nextNoah = null;
  1492. break;
  1493. }
  1494. } while ( $noahElt );
  1495. }
  1496. }
  1497. /**
  1498. * Find element $a in the list and replace it with element $b
  1499. *
  1500. * @param BalanceElement $a
  1501. * @param BalanceElement $b
  1502. */
  1503. public function replace( BalanceElement $a, BalanceElement $b ) {
  1504. if ( $this->head !== $a && !$a->prevAFE ) {
  1505. throw new ParameterAssertionException( '$a',
  1506. "Attempted to replace an element which is not in the AFE list" );
  1507. }
  1508. // Update head and tail pointers
  1509. if ( $this->head === $a ) {
  1510. $this->head = $b;
  1511. }
  1512. if ( $this->tail === $a ) {
  1513. $this->tail = $b;
  1514. }
  1515. // Update previous element
  1516. if ( $a->prevAFE ) {
  1517. $a->prevAFE->nextAFE = $b;
  1518. }
  1519. // Update next element
  1520. if ( $a->nextAFE ) {
  1521. $a->nextAFE->prevAFE = $b;
  1522. }
  1523. $b->prevAFE = $a->prevAFE;
  1524. $b->nextAFE = $a->nextAFE;
  1525. $a->nextAFE = $a->prevAFE = null;
  1526. // Update Noah list
  1527. $this->removeFromNoahList( $a );
  1528. $this->addToNoahList( $b );
  1529. }
  1530. /**
  1531. * Find $a in the list and insert $b after it.
  1532. * @param BalanceElement $a
  1533. * @param BalanceElement $b
  1534. */
  1535. public function insertAfter( BalanceElement $a, BalanceElement $b ) {
  1536. if ( $this->head !== $a && !$a->prevAFE ) {
  1537. throw new ParameterAssertionException( '$a',
  1538. "Attempted to insert after an element which is not in the AFE list" );
  1539. }
  1540. if ( $this->tail === $a ) {
  1541. $this->tail = $b;
  1542. }
  1543. if ( $a->nextAFE ) {
  1544. $a->nextAFE->prevAFE = $b;
  1545. }
  1546. $b->nextAFE = $a->nextAFE;
  1547. $b->prevAFE = $a;
  1548. $a->nextAFE = $b;
  1549. $this->addToNoahList( $b );
  1550. }
  1551. /**
  1552. * Reconstruct the active formatting elements.
  1553. * @param BalanceStack $stack The open elements stack
  1554. * @see https://html.spec.whatwg.org/multipage/syntax.html#reconstruct-the-active-formatting-elements
  1555. */
  1556. public function reconstruct( $stack ) {
  1557. $entry = $this->tail;
  1558. // If there are no entries in the list of active formatting elements,
  1559. // then there is nothing to reconstruct
  1560. if ( !$entry ) {
  1561. return;
  1562. }
  1563. // If the last is a marker, do nothing.
  1564. if ( $entry instanceof BalanceMarker ) {
  1565. return;
  1566. }
  1567. // Or if it is an open element, do nothing.
  1568. if ( $stack->indexOf( $entry ) >= 0 ) {
  1569. return;
  1570. }
  1571. // Loop backward through the list until we find a marker or an
  1572. // open element
  1573. $foundIt = false;
  1574. while ( $entry->prevAFE ) {
  1575. $entry = $entry->prevAFE;
  1576. if ( $entry instanceof BalanceMarker || $stack->indexOf( $entry ) >= 0 ) {
  1577. $foundIt = true;
  1578. break;
  1579. }
  1580. }
  1581. // Now loop forward, starting from the element after the current one (or
  1582. // the first element if we didn't find a marker or open element),
  1583. // recreating formatting elements and pushing them back onto the list
  1584. // of open elements.
  1585. if ( $foundIt ) {
  1586. $entry = $entry->nextAFE;
  1587. }
  1588. do {
  1589. $newElement = $stack->insertHTMLElement(
  1590. $entry->localName,
  1591. $entry->attribs );
  1592. $this->replace( $entry, $newElement );
  1593. $entry = $newElement->nextAFE;
  1594. } while ( $entry );
  1595. }
  1596. /**
  1597. * Get a string representation of the AFE list, for debugging
  1598. */
  1599. public function __toString() {
  1600. $prev = null;
  1601. $s = '';
  1602. for ( $node = $this->head; $node; $prev = $node, $node = $node->nextAFE ) {
  1603. if ( $node instanceof BalanceMarker ) {
  1604. $s .= "MARKER\n";
  1605. continue;
  1606. }
  1607. $s .= $node->localName . '#' . substr( md5( spl_object_hash( $node ) ), 0, 8 );
  1608. if ( $node->nextNoah ) {
  1609. $s .= " (noah sibling: {$node->nextNoah->localName}#" .
  1610. substr( md5( spl_object_hash( $node->nextNoah ) ), 0, 8 ) .
  1611. ')';
  1612. }
  1613. if ( $node->nextAFE && $node->nextAFE->prevAFE !== $node ) {
  1614. $s .= " (reverse link is wrong!)";
  1615. }
  1616. $s .= "\n";
  1617. }
  1618. if ( $prev !== $this->tail ) {
  1619. $s .= "(tail pointer is wrong!)\n";
  1620. }
  1621. return $s;
  1622. }
  1623. }
  1624. /**
  1625. * An implementation of the tree building portion of the HTML5 parsing
  1626. * spec.
  1627. *
  1628. * This is used to balance and tidy output so that the result can
  1629. * always be cleanly serialized/deserialized by an HTML5 parser. It
  1630. * does *not* guarantee "conforming" output -- the HTML5 spec contains
  1631. * a number of constraints which are not enforced by the HTML5 parsing
  1632. * process. But the result will be free of gross errors: misnested or
  1633. * unclosed tags, for example, and will be unchanged by spec-complient
  1634. * parsing followed by serialization.
  1635. *
  1636. * The tree building stage is structured as a state machine.
  1637. * When comparing the implementation to
  1638. * https://www.w3.org/TR/html5/syntax.html#tree-construction
  1639. * note that each state is implemented as a function with a
  1640. * name ending in `Mode` (because the HTML spec refers to them
  1641. * as insertion modes). The current insertion mode is held by
  1642. * the $parseMode property.
  1643. *
  1644. * The following simplifications have been made:
  1645. * - We handle body content only (ie, we start `in body`.)
  1646. * - The document is never in "quirks mode".
  1647. * - All occurrences of < and > have been entity escaped, so we
  1648. * can parse tags by simply splitting on those two characters.
  1649. * (This also simplifies the handling of < inside <textarea>.)
  1650. * The character < must not appear inside comments.
  1651. * Similarly, all attributes have been "cleaned" and are double-quoted
  1652. * and escaped.
  1653. * - All null characters are assumed to have been removed.
  1654. * - The following elements are disallowed: <html>, <head>, <body>, <frameset>,
  1655. * <frame>, <plaintext>, <xmp>, <iframe>,
  1656. * <noembed>, <noscript>, <script>, <title>. As a result,
  1657. * further simplifications can be made:
  1658. * - `frameset-ok` is not tracked.
  1659. * - `head element pointer` is not tracked (but presumed non-null)
  1660. * - Tokenizer has only a single mode. (<textarea> wants RCDATA and
  1661. * <style>/<noframes> want RAWTEXT modes which we only loosely emulate.)
  1662. *
  1663. * We generally mark places where we omit cases from the spec due to
  1664. * disallowed elements with a comment: `// OMITTED: <element-name>`.
  1665. *
  1666. * The HTML spec keeps a flag during the parsing process to track
  1667. * whether or not a "parse error" has been encountered. We don't
  1668. * bother to track that flag, we just implement the error-handling
  1669. * process as specified.
  1670. *
  1671. * @ingroup Parser
  1672. * @since 1.27
  1673. * @see https://html.spec.whatwg.org/multipage/syntax.html#tree-construction
  1674. */
  1675. class Balancer {
  1676. private $parseMode;
  1677. /** @var \Iterator */
  1678. private $bitsIterator;
  1679. private $allowedHtmlElements;
  1680. /** @var BalanceActiveFormattingElements */
  1681. private $afe;
  1682. /** @var BalanceStack */
  1683. private $stack;
  1684. private $strict;
  1685. private $allowComments;
  1686. private $config;
  1687. private $textIntegrationMode;
  1688. private $pendingTableText;
  1689. private $originalInsertionMode;
  1690. private $fragmentContext;
  1691. private $formElementPointer;
  1692. private $ignoreLinefeed;
  1693. private $inRCDATA;
  1694. private $inRAWTEXT;
  1695. /** @var callable|null */
  1696. private $processingCallback;
  1697. /** @var array */
  1698. private $processingArgs;
  1699. /**
  1700. * Valid HTML5 comments.
  1701. * Regex borrowed from Tim Starling's "remex-html" project.
  1702. */
  1703. const VALID_COMMENT_REGEX = "~ !--
  1704. ( # 1. Comment match detector
  1705. > | -> | # Invalid short close
  1706. ( # 2. Comment contents
  1707. (?:
  1708. (?! --> )
  1709. (?! --!> )
  1710. (?! --! \z )
  1711. (?! -- \z )
  1712. (?! - \z )
  1713. .
  1714. )*+
  1715. )
  1716. ( # 3. Comment close
  1717. --> | # Normal close
  1718. --!> | # Comment end bang
  1719. ( # 4. Indicate matches requiring EOF
  1720. --! | # EOF in comment end bang state
  1721. -- | # EOF in comment end state
  1722. - | # EOF in comment end dash state
  1723. (?#nothing) # EOF in comment state
  1724. )
  1725. )
  1726. )
  1727. ([^<]*) \z # 5. Non-tag text after the comment
  1728. ~xs";
  1729. /**
  1730. * Create a new Balancer.
  1731. * @param array $config Balancer configuration. Includes:
  1732. * 'strict' : boolean, defaults to false.
  1733. * When true, enforces syntactic constraints on input:
  1734. * all non-tag '<' must be escaped, all attributes must be
  1735. * separated by a single space and double-quoted. This is
  1736. * consistent with the output of the Sanitizer.
  1737. * 'allowedHtmlElements' : array, defaults to null.
  1738. * When present, the keys of this associative array give
  1739. * the acceptable HTML tag names. When not present, no
  1740. * tag sanitization is done.
  1741. * 'tidyCompat' : boolean, defaults to false.
  1742. * When true, the serialization algorithm is tweaked to
  1743. * provide historical compatibility with the old "tidy"
  1744. * program: <p>-wrapping is done to the children of
  1745. * <body> and <blockquote> elements, and empty elements
  1746. * are removed. The <pre>/<listing>/<textarea> serialization
  1747. * is also tweaked to allow lossless round trips.
  1748. * (See: https://github.com/whatwg/html/issues/944)
  1749. * 'allowComments': boolean, defaults to true.
  1750. * When true, allows HTML comments in the input.
  1751. * The Sanitizer generally strips all comments, so if you
  1752. * are running on sanitized output you can set this to
  1753. * false to get a bit more performance.
  1754. */
  1755. public function __construct( array $config = [] ) {
  1756. $this->config = $config = $config + [
  1757. 'strict' => false,
  1758. 'allowedHtmlElements' => null,
  1759. 'tidyCompat' => false,
  1760. 'allowComments' => true,
  1761. ];
  1762. $this->allowedHtmlElements = $config['allowedHtmlElements'];
  1763. $this->strict = $config['strict'];
  1764. $this->allowComments = $config['allowComments'];
  1765. if ( $this->allowedHtmlElements !== null ) {
  1766. // Sanity check!
  1767. $bad = array_uintersect_assoc(
  1768. $this->allowedHtmlElements,
  1769. BalanceSets::$unsupportedSet[BalanceSets::HTML_NAMESPACE],
  1770. function ( $a, $b ) {
  1771. // Ignore the values (just intersect the keys) by saying
  1772. // all values are equal to each other.
  1773. return 0;
  1774. }
  1775. );
  1776. if ( count( $bad ) > 0 ) {
  1777. $badstr = implode( ',', array_keys( $bad ) );
  1778. throw new ParameterAssertionException(
  1779. '$config',
  1780. 'Balance attempted with sanitization including ' .
  1781. "unsupported elements: {$badstr}"
  1782. );
  1783. }
  1784. }
  1785. }
  1786. /**
  1787. * Return a balanced HTML string for the HTML fragment given by $text,
  1788. * subject to the caveats listed in the class description. The result
  1789. * will typically be idempotent -- that is, rebalancing the output
  1790. * would result in no change.
  1791. *
  1792. * @param string $text The markup to be balanced
  1793. * @param callable $processingCallback Callback to do any variable or
  1794. * parameter replacements in HTML attributes values
  1795. * @param array|bool $processingArgs Arguments for the processing callback
  1796. * @return string The balanced markup
  1797. */
  1798. public function balance( $text, $processingCallback = null, $processingArgs = [] ) {
  1799. $this->parseMode = 'inBodyMode';
  1800. $this->bitsIterator = new ExplodeIterator( '<', $text );
  1801. $this->afe = new BalanceActiveFormattingElements();
  1802. $this->stack = new BalanceStack( $this->config );
  1803. $this->processingCallback = $processingCallback;
  1804. $this->processingArgs = $processingArgs;
  1805. $this->textIntegrationMode =
  1806. $this->ignoreLinefeed =
  1807. $this->inRCDATA =
  1808. $this->inRAWTEXT = false;
  1809. // The stack is constructed with an <html> element already on it.
  1810. // Set this up as a fragment parsed with <body> as the context.
  1811. $this->fragmentContext =
  1812. new BalanceElement( BalanceSets::HTML_NAMESPACE, 'body', [] );
  1813. $this->resetInsertionMode();
  1814. $this->formElementPointer = null;
  1815. for ( $e = $this->fragmentContext; $e != null; $e = $e->parent ) {
  1816. if ( $e->isHtmlNamed( 'form' ) ) {
  1817. $this->formElementPointer = $e;
  1818. break;
  1819. }
  1820. }
  1821. // First element is text not tag
  1822. $x = $this->bitsIterator->current();
  1823. $this->bitsIterator->next();
  1824. $this->insertToken( 'text', str_replace( '>', '&gt;', $x ) );
  1825. // Now process each tag.
  1826. while ( $this->bitsIterator->valid() ) {
  1827. $this->advance();
  1828. }
  1829. $this->insertToken( 'eof', null );
  1830. $result = $this->stack->getOutput();
  1831. // Free memory before returning.
  1832. $this->bitsIterator = null;
  1833. $this->afe = null;
  1834. $this->stack = null;
  1835. $this->fragmentContext = null;
  1836. $this->formElementPointer = null;
  1837. return $result;
  1838. }
  1839. /**
  1840. * Pass a token to the tree builder. The $token will be one of the
  1841. * strings "tag", "endtag", or "text".
  1842. */
  1843. private function insertToken( $token, $value, $attribs = null, $selfClose = false ) {
  1844. // validate tags against $unsupportedSet
  1845. if ( $token === 'tag' || $token === 'endtag' ) {
  1846. if ( isset( BalanceSets::$unsupportedSet[BalanceSets::HTML_NAMESPACE][$value] ) ) {
  1847. // As described in "simplifications" above, these tags are
  1848. // not supported in the balancer.
  1849. Assert::invariant(
  1850. !$this->strict,
  1851. "Unsupported $token <$value> found."
  1852. );
  1853. return false;
  1854. }
  1855. } elseif ( $token === 'text' && $value === '' ) {
  1856. // Don't actually inject the empty string as a text token.
  1857. return true;
  1858. }
  1859. // Support pre/listing/textarea by suppressing initial linefeed
  1860. if ( $this->ignoreLinefeed ) {
  1861. $this->ignoreLinefeed = false;
  1862. if ( $token === 'text' ) {
  1863. if ( $value[0] === "\n" ) {
  1864. if ( $value === "\n" ) {
  1865. // Nothing would be left, don't inject the empty string.
  1866. return true;
  1867. }
  1868. $value = substr( $value, 1 );
  1869. }
  1870. }
  1871. }
  1872. // Some hoops we have to jump through
  1873. $adjusted = $this->stack->adjustedCurrentNode( $this->fragmentContext );
  1874. // The spec calls this the "tree construction dispatcher".
  1875. $isForeign = true;
  1876. if (
  1877. $this->stack->length() === 0 ||
  1878. $adjusted->isHtml() ||
  1879. $token === 'eof'
  1880. ) {
  1881. $isForeign = false;
  1882. } elseif ( $adjusted->isMathmlTextIntegrationPoint() ) {
  1883. if ( $token === 'text' ) {
  1884. $isForeign = false;
  1885. } elseif (
  1886. $token === 'tag' &&
  1887. $value !== 'mglyph' && $value !== 'malignmark'
  1888. ) {
  1889. $isForeign = false;
  1890. }
  1891. } elseif (
  1892. $adjusted->namespaceURI === BalanceSets::MATHML_NAMESPACE &&
  1893. $adjusted->localName === 'annotation-xml' &&
  1894. $token === 'tag' && $value === 'svg'
  1895. ) {
  1896. $isForeign = false;
  1897. } elseif (
  1898. $adjusted->isHtmlIntegrationPoint() &&
  1899. ( $token === 'tag' || $token === 'text' )
  1900. ) {
  1901. $isForeign = false;
  1902. }
  1903. if ( $isForeign ) {
  1904. return $this->insertForeignToken( $token, $value, $attribs, $selfClose );
  1905. } else {
  1906. $func = $this->parseMode;
  1907. return $this->$func( $token, $value, $attribs, $selfClose );
  1908. }
  1909. }
  1910. private function insertForeignToken( $token, $value, $attribs = null, $selfClose = false ) {
  1911. if ( $token === 'text' ) {
  1912. $this->stack->insertText( $value );
  1913. return true;
  1914. } elseif ( $token === 'comment' ) {
  1915. $this->stack->insertComment( $value );
  1916. return true;
  1917. } elseif ( $token === 'tag' ) {
  1918. switch ( $value ) {
  1919. case 'font':
  1920. if ( isset( $attribs['color'] )
  1921. || isset( $attribs['face'] )
  1922. || isset( $attribs['size'] )
  1923. ) {
  1924. break;
  1925. }
  1926. // otherwise, fall through
  1927. case 'b':
  1928. case 'big':
  1929. case 'blockquote':
  1930. case 'body':
  1931. case 'br':
  1932. case 'center':
  1933. case 'code':
  1934. case 'dd':
  1935. case 'div':
  1936. case 'dl':
  1937. case 'dt':
  1938. case 'em':
  1939. case 'embed':
  1940. case 'h1':
  1941. case 'h2':
  1942. case 'h3':
  1943. case 'h4':
  1944. case 'h5':
  1945. case 'h6':
  1946. case 'head':
  1947. case 'hr':
  1948. case 'i':
  1949. case 'img':
  1950. case 'li':
  1951. case 'listing':
  1952. case 'menu':
  1953. case 'meta':
  1954. case 'nobr':
  1955. case 'ol':
  1956. case 'p':
  1957. case 'pre':
  1958. case 'ruby':
  1959. case 's':
  1960. case 'small':
  1961. case 'span':
  1962. case 'strong':
  1963. case 'strike':
  1964. case 'sub':
  1965. case 'sup':
  1966. case 'table':
  1967. case 'tt':
  1968. case 'u':
  1969. case 'ul':
  1970. case 'var':
  1971. if ( $this->fragmentContext ) {
  1972. break;
  1973. }
  1974. while ( true ) {
  1975. $this->stack->pop();
  1976. $node = $this->stack->currentNode;
  1977. if (
  1978. $node->isMathmlTextIntegrationPoint() ||
  1979. $node->isHtmlIntegrationPoint() ||
  1980. $node->isHtml()
  1981. ) {
  1982. break;
  1983. }
  1984. }
  1985. return $this->insertToken( $token, $value, $attribs, $selfClose );
  1986. }
  1987. // "Any other start tag"
  1988. $adjusted = ( $this->fragmentContext && $this->stack->length() === 1 ) ?
  1989. $this->fragmentContext : $this->stack->currentNode;
  1990. $this->stack->insertForeignElement(
  1991. $adjusted->namespaceURI, $value, $attribs
  1992. );
  1993. if ( $selfClose ) {
  1994. $this->stack->pop();
  1995. }
  1996. return true;
  1997. } elseif ( $token === 'endtag' ) {
  1998. $first = true;
  1999. foreach ( $this->stack as $i => $node ) {
  2000. if ( $node->isHtml() && !$first ) {
  2001. // process the end tag as HTML
  2002. $func = $this->parseMode;
  2003. return $this->$func( $token, $value, $attribs, $selfClose );
  2004. } elseif ( $i === 0 ) {
  2005. return true;
  2006. } elseif ( $node->localName === $value ) {
  2007. $this->stack->popTag( $node );
  2008. return true;
  2009. }
  2010. $first = false;
  2011. }
  2012. }
  2013. }
  2014. /**
  2015. * Grab the next "token" from $bitsIterator. This is either a open/close
  2016. * tag or text or a comment, depending on whether the Sanitizer approves.
  2017. */
  2018. private function advance() {
  2019. $x = $this->bitsIterator->current();
  2020. $this->bitsIterator->next();
  2021. $regs = [];
  2022. // Handle comments. These won't be generated by mediawiki (they
  2023. // are stripped in the Sanitizer) but may be generated by extensions.
  2024. if (
  2025. $this->allowComments &&
  2026. !( $this->inRCDATA || $this->inRAWTEXT ) &&
  2027. preg_match( self::VALID_COMMENT_REGEX, $x, $regs, PREG_OFFSET_CAPTURE ) &&
  2028. // verify EOF condition where necessary
  2029. ( $regs[4][1] < 0 || !$this->bitsIterator->valid() )
  2030. ) {
  2031. $contents = $regs[2][0];
  2032. $rest = $regs[5][0];
  2033. $this->insertToken( 'comment', $contents );
  2034. $this->insertToken( 'text', str_replace( '>', '&gt;', $rest ) );
  2035. return;
  2036. }
  2037. // $slash: Does the current element start with a '/'?
  2038. // $t: Current element name
  2039. // $attribStr: String between element name and >
  2040. // $brace: Ending '>' or '/>'
  2041. // $rest: Everything until the next element from the $bitsIterator
  2042. if ( preg_match( Sanitizer::ELEMENT_BITS_REGEX, $x, $regs ) ) {
  2043. list( /* $qbar */, $slash, $t, $attribStr, $brace, $rest ) = $regs;
  2044. $t = strtolower( $t );
  2045. if ( $this->strict ) {
  2046. // Verify that attributes are all properly double-quoted
  2047. Assert::invariant(
  2048. preg_match(
  2049. '/^( [:_A-Z0-9][-.:_A-Z0-9]*="[^"]*")*[ ]*$/i', $attribStr
  2050. ),
  2051. "Bad attribute string found"
  2052. );
  2053. }
  2054. } else {
  2055. Assert::invariant(
  2056. !$this->strict, "< found which does not start a valid tag"
  2057. );
  2058. $slash = $t = $attribStr = $brace = $rest = null;
  2059. }
  2060. $goodTag = $t;
  2061. if ( $this->inRCDATA ) {
  2062. if ( $slash && $t === $this->inRCDATA ) {
  2063. $this->inRCDATA = false;
  2064. } else {
  2065. // No tags allowed; this emulates the "rcdata" tokenizer mode.
  2066. $goodTag = false;
  2067. }
  2068. }
  2069. if ( $this->inRAWTEXT ) {
  2070. if ( $slash && $t === $this->inRAWTEXT ) {
  2071. $this->inRAWTEXT = false;
  2072. } else {
  2073. // No tags allowed, no entity-escaping done.
  2074. $goodTag = false;
  2075. }
  2076. }
  2077. $sanitize = $this->allowedHtmlElements !== null;
  2078. if ( $sanitize ) {
  2079. $goodTag = $t && isset( $this->allowedHtmlElements[$t] );
  2080. }
  2081. if ( $goodTag ) {
  2082. if ( is_callable( $this->processingCallback ) ) {
  2083. call_user_func_array( $this->processingCallback, [ &$attribStr, $this->processingArgs ] );
  2084. }
  2085. if ( $sanitize ) {
  2086. $goodTag = Sanitizer::validateTag( $attribStr, $t );
  2087. }
  2088. }
  2089. if ( $goodTag ) {
  2090. if ( $sanitize ) {
  2091. $attribs = Sanitizer::decodeTagAttributes( $attribStr );
  2092. $attribs = Sanitizer::validateTagAttributes( $attribs, $t );
  2093. } else {
  2094. $attribs = Sanitizer::decodeTagAttributes( $attribStr );
  2095. }
  2096. $goodTag = $this->insertToken(
  2097. $slash ? 'endtag' : 'tag', $t, $attribs, $brace === '/>'
  2098. );
  2099. }
  2100. if ( $goodTag ) {
  2101. $rest = str_replace( '>', '&gt;', $rest );
  2102. $this->insertToken( 'text', str_replace( '>', '&gt;', $rest ) );
  2103. } elseif ( $this->inRAWTEXT ) {
  2104. $this->insertToken( 'text', "<$x" );
  2105. } else {
  2106. // bad tag; serialize entire thing as text.
  2107. $this->insertToken( 'text', '&lt;' . str_replace( '>', '&gt;', $x ) );
  2108. }
  2109. }
  2110. private function switchMode( $mode ) {
  2111. Assert::parameter(
  2112. substr( $mode, -4 ) === 'Mode', '$mode', 'should end in Mode'
  2113. );
  2114. $oldMode = $this->parseMode;
  2115. $this->parseMode = $mode;
  2116. return $oldMode;
  2117. }
  2118. private function switchModeAndReprocess( $mode, $token, $value, $attribs, $selfClose ) {
  2119. $this->switchMode( $mode );
  2120. return $this->insertToken( $token, $value, $attribs, $selfClose );
  2121. }
  2122. private function resetInsertionMode() {
  2123. $last = false;
  2124. foreach ( $this->stack as $i => $node ) {
  2125. if ( $i === 0 ) {
  2126. $last = true;
  2127. if ( $this->fragmentContext ) {
  2128. $node = $this->fragmentContext;
  2129. }
  2130. }
  2131. if ( $node->isHtml() ) {
  2132. switch ( $node->localName ) {
  2133. case 'select':
  2134. $stackLength = $this->stack->length();
  2135. for ( $j = $i + 1; $j < $stackLength - 1; $j++ ) {
  2136. $ancestor = $this->stack->node( $stackLength - $j - 1 );
  2137. if ( $ancestor->isHtmlNamed( 'template' ) ) {
  2138. break;
  2139. }
  2140. if ( $ancestor->isHtmlNamed( 'table' ) ) {
  2141. $this->switchMode( 'inSelectInTableMode' );
  2142. return;
  2143. }
  2144. }
  2145. $this->switchMode( 'inSelectMode' );
  2146. return;
  2147. case 'tr':
  2148. $this->switchMode( 'inRowMode' );
  2149. return;
  2150. case 'tbody':
  2151. case 'tfoot':
  2152. case 'thead':
  2153. $this->switchMode( 'inTableBodyMode' );
  2154. return;
  2155. case 'caption':
  2156. $this->switchMode( 'inCaptionMode' );
  2157. return;
  2158. case 'colgroup':
  2159. $this->switchMode( 'inColumnGroupMode' );
  2160. return;
  2161. case 'table':
  2162. $this->switchMode( 'inTableMode' );
  2163. return;
  2164. case 'template':
  2165. $this->switchMode(
  2166. array_slice( $this->templateInsertionModes, -1 )[0]
  2167. );
  2168. return;
  2169. case 'body':
  2170. $this->switchMode( 'inBodyMode' );
  2171. return;
  2172. // OMITTED: <frameset>
  2173. // OMITTED: <html>
  2174. // OMITTED: <head>
  2175. default:
  2176. if ( !$last ) {
  2177. // OMITTED: <head>
  2178. if ( $node->isA( BalanceSets::$tableCellSet ) ) {
  2179. $this->switchMode( 'inCellMode' );
  2180. return;
  2181. }
  2182. }
  2183. }
  2184. }
  2185. if ( $last ) {
  2186. $this->switchMode( 'inBodyMode' );
  2187. return;
  2188. }
  2189. }
  2190. }
  2191. private function stopParsing() {
  2192. // Most of the spec methods are inapplicable, other than step 2:
  2193. // "pop all the nodes off the stack of open elements".
  2194. // We're going to keep the top-most <html> element on the stack, though.
  2195. // Clear the AFE list first, otherwise the element objects will stay live
  2196. // during serialization, potentially using O(N^2) memory. Note that
  2197. // popping the stack will never result in reconstructing the active
  2198. // formatting elements.
  2199. $this->afe = null;
  2200. $this->stack->popTo( 1 );
  2201. }
  2202. private function parseRawText( $value, $attribs = null ) {
  2203. $this->stack->insertHTMLElement( $value, $attribs );
  2204. $this->inRAWTEXT = $value;
  2205. $this->originalInsertionMode = $this->switchMode( 'inTextMode' );
  2206. return true;
  2207. }
  2208. private function inTextMode( $token, $value, $attribs = null, $selfClose = false ) {
  2209. if ( $token === 'text' ) {
  2210. $this->stack->insertText( $value );
  2211. return true;
  2212. } elseif ( $token === 'eof' ) {
  2213. $this->stack->pop();
  2214. return $this->switchModeAndReprocess(
  2215. $this->originalInsertionMode, $token, $value, $attribs, $selfClose
  2216. );
  2217. } elseif ( $token === 'endtag' ) {
  2218. $this->stack->pop();
  2219. $this->switchMode( $this->originalInsertionMode );
  2220. return true;
  2221. }
  2222. return true;
  2223. }
  2224. private function inHeadMode( $token, $value, $attribs = null, $selfClose = false ) {
  2225. if ( $token === 'text' ) {
  2226. if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
  2227. $this->stack->insertText( $matches[0] );
  2228. $value = substr( $value, strlen( $matches[0] ) );
  2229. }
  2230. if ( strlen( $value ) === 0 ) {
  2231. return true; // All text handled.
  2232. }
  2233. // Fall through to handle non-whitespace below.
  2234. } elseif ( $token === 'tag' ) {
  2235. switch ( $value ) {
  2236. case 'meta':
  2237. // OMITTED: in a full HTML parser, this might change the encoding.
  2238. // falls through
  2239. // OMITTED: <html>
  2240. case 'base':
  2241. case 'basefont':
  2242. case 'bgsound':
  2243. case 'link':
  2244. $this->stack->insertHTMLElement( $value, $attribs );
  2245. $this->stack->pop();
  2246. return true;
  2247. // OMITTED: <title>
  2248. // OMITTED: <noscript>
  2249. case 'noframes':
  2250. case 'style':
  2251. return $this->parseRawText( $value, $attribs );
  2252. // OMITTED: <script>
  2253. case 'template':
  2254. $this->stack->insertHTMLElement( $value, $attribs );
  2255. $this->afe->insertMarker();
  2256. // OMITTED: frameset_ok
  2257. $this->switchMode( 'inTemplateMode' );
  2258. $this->templateInsertionModes[] = $this->parseMode;
  2259. return true;
  2260. // OMITTED: <head>
  2261. }
  2262. } elseif ( $token === 'endtag' ) {
  2263. switch ( $value ) {
  2264. // OMITTED: <head>
  2265. // OMITTED: <body>
  2266. // OMITTED: <html>
  2267. case 'br':
  2268. break; // handle at the bottom of the function
  2269. case 'template':
  2270. if ( $this->stack->indexOf( $value ) < 0 ) {
  2271. return true; // Ignore the token.
  2272. }
  2273. $this->stack->generateImpliedEndTags( null, true /* thorough */ );
  2274. $this->stack->popTag( $value );
  2275. $this->afe->clearToMarker();
  2276. array_pop( $this->templateInsertionModes );
  2277. $this->resetInsertionMode();
  2278. return true;
  2279. default:
  2280. // ignore any other end tag
  2281. return true;
  2282. }
  2283. } elseif ( $token === 'comment' ) {
  2284. $this->stack->insertComment( $value );
  2285. return true;
  2286. }
  2287. // If not handled above
  2288. $this->inHeadMode( 'endtag', 'head' ); // synthetic </head>
  2289. // Then redo this one
  2290. return $this->insertToken( $token, $value, $attribs, $selfClose );
  2291. }
  2292. private function inBodyMode( $token, $value, $attribs = null, $selfClose = false ) {
  2293. if ( $token === 'text' ) {
  2294. $this->afe->reconstruct( $this->stack );
  2295. $this->stack->insertText( $value );
  2296. return true;
  2297. } elseif ( $token === 'eof' ) {
  2298. if ( !empty( $this->templateInsertionModes ) ) {
  2299. return $this->inTemplateMode( $token, $value, $attribs, $selfClose );
  2300. }
  2301. $this->stopParsing();
  2302. return true;
  2303. } elseif ( $token === 'tag' ) {
  2304. switch ( $value ) {
  2305. // OMITTED: <html>
  2306. case 'base':
  2307. case 'basefont':
  2308. case 'bgsound':
  2309. case 'link':
  2310. case 'meta':
  2311. case 'noframes':
  2312. // OMITTED: <script>
  2313. case 'style':
  2314. case 'template':
  2315. // OMITTED: <title>
  2316. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  2317. // OMITTED: <body>
  2318. // OMITTED: <frameset>
  2319. case 'address':
  2320. case 'article':
  2321. case 'aside':
  2322. case 'blockquote':
  2323. case 'center':
  2324. case 'details':
  2325. case 'dialog':
  2326. case 'dir':
  2327. case 'div':
  2328. case 'dl':
  2329. case 'fieldset':
  2330. case 'figcaption':
  2331. case 'figure':
  2332. case 'footer':
  2333. case 'header':
  2334. case 'hgroup':
  2335. case 'main':
  2336. case 'nav':
  2337. case 'ol':
  2338. case 'p':
  2339. case 'section':
  2340. case 'summary':
  2341. case 'ul':
  2342. if ( $this->stack->inButtonScope( 'p' ) ) {
  2343. $this->inBodyMode( 'endtag', 'p' );
  2344. }
  2345. $this->stack->insertHTMLElement( $value, $attribs );
  2346. return true;
  2347. case 'menu':
  2348. if ( $this->stack->inButtonScope( "p" ) ) {
  2349. $this->inBodyMode( 'endtag', 'p' );
  2350. }
  2351. if ( $this->stack->currentNode->isHtmlNamed( 'menuitem' ) ) {
  2352. $this->stack->pop();
  2353. }
  2354. $this->stack->insertHTMLElement( $value, $attribs );
  2355. return true;
  2356. case 'h1':
  2357. case 'h2':
  2358. case 'h3':
  2359. case 'h4':
  2360. case 'h5':
  2361. case 'h6':
  2362. if ( $this->stack->inButtonScope( 'p' ) ) {
  2363. $this->inBodyMode( 'endtag', 'p' );
  2364. }
  2365. if ( $this->stack->currentNode->isA( BalanceSets::$headingSet ) ) {
  2366. $this->stack->pop();
  2367. }
  2368. $this->stack->insertHTMLElement( $value, $attribs );
  2369. return true;
  2370. case 'pre':
  2371. case 'listing':
  2372. if ( $this->stack->inButtonScope( 'p' ) ) {
  2373. $this->inBodyMode( 'endtag', 'p' );
  2374. }
  2375. $this->stack->insertHTMLElement( $value, $attribs );
  2376. $this->ignoreLinefeed = true;
  2377. // OMITTED: frameset_ok
  2378. return true;
  2379. case 'form':
  2380. if (
  2381. $this->formElementPointer &&
  2382. $this->stack->indexOf( 'template' ) < 0
  2383. ) {
  2384. return true; // in a form, not in a template.
  2385. }
  2386. if ( $this->stack->inButtonScope( "p" ) ) {
  2387. $this->inBodyMode( 'endtag', 'p' );
  2388. }
  2389. $elt = $this->stack->insertHTMLElement( $value, $attribs );
  2390. if ( $this->stack->indexOf( 'template' ) < 0 ) {
  2391. $this->formElementPointer = $elt;
  2392. }
  2393. return true;
  2394. case 'li':
  2395. // OMITTED: frameset_ok
  2396. foreach ( $this->stack as $node ) {
  2397. if ( $node->isHtmlNamed( 'li' ) ) {
  2398. $this->inBodyMode( 'endtag', 'li' );
  2399. break;
  2400. }
  2401. if (
  2402. $node->isA( BalanceSets::$specialSet ) &&
  2403. !$node->isA( BalanceSets::$addressDivPSet )
  2404. ) {
  2405. break;
  2406. }
  2407. }
  2408. if ( $this->stack->inButtonScope( 'p' ) ) {
  2409. $this->inBodyMode( 'endtag', 'p' );
  2410. }
  2411. $this->stack->insertHTMLElement( $value, $attribs );
  2412. return true;
  2413. case 'dd':
  2414. case 'dt':
  2415. // OMITTED: frameset_ok
  2416. foreach ( $this->stack as $node ) {
  2417. if ( $node->isHtmlNamed( 'dd' ) ) {
  2418. $this->inBodyMode( 'endtag', 'dd' );
  2419. break;
  2420. }
  2421. if ( $node->isHtmlNamed( 'dt' ) ) {
  2422. $this->inBodyMode( 'endtag', 'dt' );
  2423. break;
  2424. }
  2425. if (
  2426. $node->isA( BalanceSets::$specialSet ) &&
  2427. !$node->isA( BalanceSets::$addressDivPSet )
  2428. ) {
  2429. break;
  2430. }
  2431. }
  2432. if ( $this->stack->inButtonScope( 'p' ) ) {
  2433. $this->inBodyMode( 'endtag', 'p' );
  2434. }
  2435. $this->stack->insertHTMLElement( $value, $attribs );
  2436. return true;
  2437. // OMITTED: <plaintext>
  2438. case 'button':
  2439. if ( $this->stack->inScope( 'button' ) ) {
  2440. $this->inBodyMode( 'endtag', 'button' );
  2441. return $this->insertToken( $token, $value, $attribs, $selfClose );
  2442. }
  2443. $this->afe->reconstruct( $this->stack );
  2444. $this->stack->insertHTMLElement( $value, $attribs );
  2445. return true;
  2446. case 'a':
  2447. $activeElement = $this->afe->findElementByTag( 'a' );
  2448. if ( $activeElement ) {
  2449. $this->inBodyMode( 'endtag', 'a' );
  2450. if ( $this->afe->isInList( $activeElement ) ) {
  2451. $this->afe->remove( $activeElement );
  2452. // Don't flatten here, since when we fall
  2453. // through below we might foster parent
  2454. // the new <a> tag inside this one.
  2455. $this->stack->removeElement( $activeElement, false );
  2456. }
  2457. }
  2458. // Falls through
  2459. case 'b':
  2460. case 'big':
  2461. case 'code':
  2462. case 'em':
  2463. case 'font':
  2464. case 'i':
  2465. case 's':
  2466. case 'small':
  2467. case 'strike':
  2468. case 'strong':
  2469. case 'tt':
  2470. case 'u':
  2471. $this->afe->reconstruct( $this->stack );
  2472. $this->afe->push( $this->stack->insertHTMLElement( $value, $attribs ) );
  2473. return true;
  2474. case 'nobr':
  2475. $this->afe->reconstruct( $this->stack );
  2476. if ( $this->stack->inScope( 'nobr' ) ) {
  2477. $this->inBodyMode( 'endtag', 'nobr' );
  2478. $this->afe->reconstruct( $this->stack );
  2479. }
  2480. $this->afe->push( $this->stack->insertHTMLElement( $value, $attribs ) );
  2481. return true;
  2482. case 'applet':
  2483. case 'marquee':
  2484. case 'object':
  2485. $this->afe->reconstruct( $this->stack );
  2486. $this->stack->insertHTMLElement( $value, $attribs );
  2487. $this->afe->insertMarker();
  2488. // OMITTED: frameset_ok
  2489. return true;
  2490. case 'table':
  2491. // The document is never in "quirks mode"; see simplifications
  2492. // above.
  2493. if ( $this->stack->inButtonScope( 'p' ) ) {
  2494. $this->inBodyMode( 'endtag', 'p' );
  2495. }
  2496. $this->stack->insertHTMLElement( $value, $attribs );
  2497. // OMITTED: frameset_ok
  2498. $this->switchMode( 'inTableMode' );
  2499. return true;
  2500. case 'area':
  2501. case 'br':
  2502. case 'embed':
  2503. case 'img':
  2504. case 'keygen':
  2505. case 'wbr':
  2506. $this->afe->reconstruct( $this->stack );
  2507. $this->stack->insertHTMLElement( $value, $attribs );
  2508. $this->stack->pop();
  2509. // OMITTED: frameset_ok
  2510. return true;
  2511. case 'input':
  2512. $this->afe->reconstruct( $this->stack );
  2513. $this->stack->insertHTMLElement( $value, $attribs );
  2514. $this->stack->pop();
  2515. // OMITTED: frameset_ok
  2516. // (hence we don't need to examine the tag's "type" attribute)
  2517. return true;
  2518. case 'param':
  2519. case 'source':
  2520. case 'track':
  2521. $this->stack->insertHTMLElement( $value, $attribs );
  2522. $this->stack->pop();
  2523. return true;
  2524. case 'hr':
  2525. if ( $this->stack->inButtonScope( 'p' ) ) {
  2526. $this->inBodyMode( 'endtag', 'p' );
  2527. }
  2528. if ( $this->stack->currentNode->isHtmlNamed( 'menuitem' ) ) {
  2529. $this->stack->pop();
  2530. }
  2531. $this->stack->insertHTMLElement( $value, $attribs );
  2532. $this->stack->pop();
  2533. return true;
  2534. case 'image':
  2535. // warts!
  2536. return $this->inBodyMode( $token, 'img', $attribs, $selfClose );
  2537. case 'textarea':
  2538. $this->stack->insertHTMLElement( $value, $attribs );
  2539. $this->ignoreLinefeed = true;
  2540. $this->inRCDATA = $value; // emulate rcdata tokenizer mode
  2541. // OMITTED: frameset_ok
  2542. return true;
  2543. // OMITTED: <xmp>
  2544. // OMITTED: <iframe>
  2545. // OMITTED: <noembed>
  2546. // OMITTED: <noscript>
  2547. case 'select':
  2548. $this->afe->reconstruct( $this->stack );
  2549. $this->stack->insertHTMLElement( $value, $attribs );
  2550. switch ( $this->parseMode ) {
  2551. case 'inTableMode':
  2552. case 'inCaptionMode':
  2553. case 'inTableBodyMode':
  2554. case 'inRowMode':
  2555. case 'inCellMode':
  2556. $this->switchMode( 'inSelectInTableMode' );
  2557. return true;
  2558. default:
  2559. $this->switchMode( 'inSelectMode' );
  2560. return true;
  2561. }
  2562. case 'optgroup':
  2563. case 'option':
  2564. if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
  2565. $this->inBodyMode( 'endtag', 'option' );
  2566. }
  2567. $this->afe->reconstruct( $this->stack );
  2568. $this->stack->insertHTMLElement( $value, $attribs );
  2569. return true;
  2570. case 'menuitem':
  2571. if ( $this->stack->currentNode->isHtmlNamed( 'menuitem' ) ) {
  2572. $this->stack->pop();
  2573. }
  2574. $this->afe->reconstruct( $this->stack );
  2575. $this->stack->insertHTMLElement( $value, $attribs );
  2576. return true;
  2577. case 'rb':
  2578. case 'rtc':
  2579. if ( $this->stack->inScope( 'ruby' ) ) {
  2580. $this->stack->generateImpliedEndTags();
  2581. }
  2582. $this->stack->insertHTMLElement( $value, $attribs );
  2583. return true;
  2584. case 'rp':
  2585. case 'rt':
  2586. if ( $this->stack->inScope( 'ruby' ) ) {
  2587. $this->stack->generateImpliedEndTags( 'rtc' );
  2588. }
  2589. $this->stack->insertHTMLElement( $value, $attribs );
  2590. return true;
  2591. case 'math':
  2592. $this->afe->reconstruct( $this->stack );
  2593. // We skip the spec's "adjust MathML attributes" and
  2594. // "adjust foreign attributes" steps, since the browser will
  2595. // do this later when it parses the output and it doesn't affect
  2596. // balancing.
  2597. $this->stack->insertForeignElement(
  2598. BalanceSets::MATHML_NAMESPACE, $value, $attribs
  2599. );
  2600. if ( $selfClose ) {
  2601. // emit explicit </math> tag.
  2602. $this->stack->pop();
  2603. }
  2604. return true;
  2605. case 'svg':
  2606. $this->afe->reconstruct( $this->stack );
  2607. // We skip the spec's "adjust SVG attributes" and
  2608. // "adjust foreign attributes" steps, since the browser will
  2609. // do this later when it parses the output and it doesn't affect
  2610. // balancing.
  2611. $this->stack->insertForeignElement(
  2612. BalanceSets::SVG_NAMESPACE, $value, $attribs
  2613. );
  2614. if ( $selfClose ) {
  2615. // emit explicit </svg> tag.
  2616. $this->stack->pop();
  2617. }
  2618. return true;
  2619. case 'caption':
  2620. case 'col':
  2621. case 'colgroup':
  2622. // OMITTED: <frame>
  2623. case 'head':
  2624. case 'tbody':
  2625. case 'td':
  2626. case 'tfoot':
  2627. case 'th':
  2628. case 'thead':
  2629. case 'tr':
  2630. // Ignore table tags if we're not inTableMode
  2631. return true;
  2632. }
  2633. // Handle any other start tag here
  2634. $this->afe->reconstruct( $this->stack );
  2635. $this->stack->insertHTMLElement( $value, $attribs );
  2636. return true;
  2637. } elseif ( $token === 'endtag' ) {
  2638. switch ( $value ) {
  2639. // </body>,</html> are unsupported.
  2640. case 'template':
  2641. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  2642. case 'address':
  2643. case 'article':
  2644. case 'aside':
  2645. case 'blockquote':
  2646. case 'button':
  2647. case 'center':
  2648. case 'details':
  2649. case 'dialog':
  2650. case 'dir':
  2651. case 'div':
  2652. case 'dl':
  2653. case 'fieldset':
  2654. case 'figcaption':
  2655. case 'figure':
  2656. case 'footer':
  2657. case 'header':
  2658. case 'hgroup':
  2659. case 'listing':
  2660. case 'main':
  2661. case 'menu':
  2662. case 'nav':
  2663. case 'ol':
  2664. case 'pre':
  2665. case 'section':
  2666. case 'summary':
  2667. case 'ul':
  2668. // Ignore if there is not a matching open tag
  2669. if ( !$this->stack->inScope( $value ) ) {
  2670. return true;
  2671. }
  2672. $this->stack->generateImpliedEndTags();
  2673. $this->stack->popTag( $value );
  2674. return true;
  2675. case 'form':
  2676. if ( $this->stack->indexOf( 'template' ) < 0 ) {
  2677. $openform = $this->formElementPointer;
  2678. $this->formElementPointer = null;
  2679. if ( !$openform || !$this->stack->inScope( $openform ) ) {
  2680. return true;
  2681. }
  2682. $this->stack->generateImpliedEndTags();
  2683. // Don't flatten yet if we're removing a <form> element
  2684. // out-of-order. (eg. `<form><div></form>`)
  2685. $flatten = ( $this->stack->currentNode === $openform );
  2686. $this->stack->removeElement( $openform, $flatten );
  2687. } else {
  2688. if ( !$this->stack->inScope( 'form' ) ) {
  2689. return true;
  2690. }
  2691. $this->stack->generateImpliedEndTags();
  2692. $this->stack->popTag( 'form' );
  2693. }
  2694. return true;
  2695. case 'p':
  2696. if ( !$this->stack->inButtonScope( 'p' ) ) {
  2697. $this->inBodyMode( 'tag', 'p', [] );
  2698. return $this->insertToken( $token, $value, $attribs, $selfClose );
  2699. }
  2700. $this->stack->generateImpliedEndTags( $value );
  2701. $this->stack->popTag( $value );
  2702. return true;
  2703. case 'li':
  2704. if ( !$this->stack->inListItemScope( $value ) ) {
  2705. return true; // ignore
  2706. }
  2707. $this->stack->generateImpliedEndTags( $value );
  2708. $this->stack->popTag( $value );
  2709. return true;
  2710. case 'dd':
  2711. case 'dt':
  2712. if ( !$this->stack->inScope( $value ) ) {
  2713. return true; // ignore
  2714. }
  2715. $this->stack->generateImpliedEndTags( $value );
  2716. $this->stack->popTag( $value );
  2717. return true;
  2718. case 'h1':
  2719. case 'h2':
  2720. case 'h3':
  2721. case 'h4':
  2722. case 'h5':
  2723. case 'h6':
  2724. if ( !$this->stack->inScope( BalanceSets::$headingSet ) ) {
  2725. return true; // ignore
  2726. }
  2727. $this->stack->generateImpliedEndTags();
  2728. $this->stack->popTag( BalanceSets::$headingSet );
  2729. return true;
  2730. case 'sarcasm':
  2731. // Take a deep breath, then:
  2732. break;
  2733. case 'a':
  2734. case 'b':
  2735. case 'big':
  2736. case 'code':
  2737. case 'em':
  2738. case 'font':
  2739. case 'i':
  2740. case 'nobr':
  2741. case 's':
  2742. case 'small':
  2743. case 'strike':
  2744. case 'strong':
  2745. case 'tt':
  2746. case 'u':
  2747. if ( $this->stack->adoptionAgency( $value, $this->afe ) ) {
  2748. return true; // If we did something, we're done.
  2749. }
  2750. break; // Go to the "any other end tag" case.
  2751. case 'applet':
  2752. case 'marquee':
  2753. case 'object':
  2754. if ( !$this->stack->inScope( $value ) ) {
  2755. return true; // ignore
  2756. }
  2757. $this->stack->generateImpliedEndTags();
  2758. $this->stack->popTag( $value );
  2759. $this->afe->clearToMarker();
  2760. return true;
  2761. case 'br':
  2762. // Turn </br> into <br>
  2763. return $this->inBodyMode( 'tag', $value, [] );
  2764. }
  2765. // Any other end tag goes here
  2766. foreach ( $this->stack as $i => $node ) {
  2767. if ( $node->isHtmlNamed( $value ) ) {
  2768. $this->stack->generateImpliedEndTags( $value );
  2769. $this->stack->popTo( $i ); // including $i
  2770. break;
  2771. } elseif ( $node->isA( BalanceSets::$specialSet ) ) {
  2772. return true; // ignore this close token.
  2773. }
  2774. }
  2775. return true;
  2776. } elseif ( $token === 'comment' ) {
  2777. $this->stack->insertComment( $value );
  2778. return true;
  2779. } else {
  2780. Assert::invariant( false, "Bad token type: $token" );
  2781. }
  2782. }
  2783. private function inTableMode( $token, $value, $attribs = null, $selfClose = false ) {
  2784. if ( $token === 'text' ) {
  2785. if ( $this->textIntegrationMode ) {
  2786. return $this->inBodyMode( $token, $value, $attribs, $selfClose );
  2787. } elseif ( $this->stack->currentNode->isA( BalanceSets::$tableSectionRowSet ) ) {
  2788. $this->pendingTableText = '';
  2789. $this->originalInsertionMode = $this->parseMode;
  2790. return $this->switchModeAndReprocess( 'inTableTextMode',
  2791. $token, $value, $attribs, $selfClose );
  2792. }
  2793. // fall through to default case.
  2794. } elseif ( $token === 'eof' ) {
  2795. $this->stopParsing();
  2796. return true;
  2797. } elseif ( $token === 'tag' ) {
  2798. switch ( $value ) {
  2799. case 'caption':
  2800. $this->afe->insertMarker();
  2801. $this->stack->insertHTMLElement( $value, $attribs );
  2802. $this->switchMode( 'inCaptionMode' );
  2803. return true;
  2804. case 'colgroup':
  2805. $this->stack->clearToContext( BalanceSets::$tableContextSet );
  2806. $this->stack->insertHTMLElement( $value, $attribs );
  2807. $this->switchMode( 'inColumnGroupMode' );
  2808. return true;
  2809. case 'col':
  2810. $this->inTableMode( 'tag', 'colgroup', [] );
  2811. return $this->insertToken( $token, $value, $attribs, $selfClose );
  2812. case 'tbody':
  2813. case 'tfoot':
  2814. case 'thead':
  2815. $this->stack->clearToContext( BalanceSets::$tableContextSet );
  2816. $this->stack->insertHTMLElement( $value, $attribs );
  2817. $this->switchMode( 'inTableBodyMode' );
  2818. return true;
  2819. case 'td':
  2820. case 'th':
  2821. case 'tr':
  2822. $this->inTableMode( 'tag', 'tbody', [] );
  2823. return $this->insertToken( $token, $value, $attribs, $selfClose );
  2824. case 'table':
  2825. if ( !$this->stack->inTableScope( $value ) ) {
  2826. return true; // Ignore this tag.
  2827. }
  2828. $this->inTableMode( 'endtag', $value );
  2829. return $this->insertToken( $token, $value, $attribs, $selfClose );
  2830. case 'style':
  2831. // OMITTED: <script>
  2832. case 'template':
  2833. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  2834. case 'input':
  2835. if ( !isset( $attribs['type'] ) || strcasecmp( $attribs['type'], 'hidden' ) !== 0 ) {
  2836. break; // Handle this as "everything else"
  2837. }
  2838. $this->stack->insertHTMLElement( $value, $attribs );
  2839. $this->stack->pop();
  2840. return true;
  2841. case 'form':
  2842. if (
  2843. $this->formElementPointer ||
  2844. $this->stack->indexOf( 'template' ) >= 0
  2845. ) {
  2846. return true; // ignore this token
  2847. }
  2848. $this->formElementPointer =
  2849. $this->stack->insertHTMLElement( $value, $attribs );
  2850. $this->stack->popTag( $this->formElementPointer );
  2851. return true;
  2852. }
  2853. // Fall through for "anything else" clause.
  2854. } elseif ( $token === 'endtag' ) {
  2855. switch ( $value ) {
  2856. case 'table':
  2857. if ( !$this->stack->inTableScope( $value ) ) {
  2858. return true; // Ignore.
  2859. }
  2860. $this->stack->popTag( $value );
  2861. $this->resetInsertionMode();
  2862. return true;
  2863. // OMITTED: <body>
  2864. case 'caption':
  2865. case 'col':
  2866. case 'colgroup':
  2867. // OMITTED: <html>
  2868. case 'tbody':
  2869. case 'td':
  2870. case 'tfoot':
  2871. case 'th':
  2872. case 'thead':
  2873. case 'tr':
  2874. return true; // Ignore the token.
  2875. case 'template':
  2876. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  2877. }
  2878. // Fall through for "anything else" clause.
  2879. } elseif ( $token === 'comment' ) {
  2880. $this->stack->insertComment( $value );
  2881. return true;
  2882. }
  2883. // This is the "anything else" case:
  2884. $this->stack->fosterParentMode = true;
  2885. $this->inBodyMode( $token, $value, $attribs, $selfClose );
  2886. $this->stack->fosterParentMode = false;
  2887. return true;
  2888. }
  2889. private function inTableTextMode( $token, $value, $attribs = null, $selfClose = false ) {
  2890. if ( $token === 'text' ) {
  2891. $this->pendingTableText .= $value;
  2892. return true;
  2893. }
  2894. // Non-text token:
  2895. $text = $this->pendingTableText;
  2896. $this->pendingTableText = '';
  2897. if ( preg_match( '/[^\x09\x0A\x0C\x0D\x20]/', $text ) ) {
  2898. // This should match the "anything else" case inTableMode
  2899. $this->stack->fosterParentMode = true;
  2900. $this->inBodyMode( 'text', $text );
  2901. $this->stack->fosterParentMode = false;
  2902. } else {
  2903. // Pending text is just whitespace.
  2904. $this->stack->insertText( $text );
  2905. }
  2906. return $this->switchModeAndReprocess(
  2907. $this->originalInsertionMode, $token, $value, $attribs, $selfClose
  2908. );
  2909. }
  2910. // helper for inCaptionMode
  2911. private function endCaption() {
  2912. if ( !$this->stack->inTableScope( 'caption' ) ) {
  2913. return false;
  2914. }
  2915. $this->stack->generateImpliedEndTags();
  2916. $this->stack->popTag( 'caption' );
  2917. $this->afe->clearToMarker();
  2918. $this->switchMode( 'inTableMode' );
  2919. return true;
  2920. }
  2921. private function inCaptionMode( $token, $value, $attribs = null, $selfClose = false ) {
  2922. if ( $token === 'tag' ) {
  2923. switch ( $value ) {
  2924. case 'caption':
  2925. case 'col':
  2926. case 'colgroup':
  2927. case 'tbody':
  2928. case 'td':
  2929. case 'tfoot':
  2930. case 'th':
  2931. case 'thead':
  2932. case 'tr':
  2933. if ( $this->endCaption() ) {
  2934. $this->insertToken( $token, $value, $attribs, $selfClose );
  2935. }
  2936. return true;
  2937. }
  2938. // Fall through to "anything else" case.
  2939. } elseif ( $token === 'endtag' ) {
  2940. switch ( $value ) {
  2941. case 'caption':
  2942. $this->endCaption();
  2943. return true;
  2944. case 'table':
  2945. if ( $this->endCaption() ) {
  2946. $this->insertToken( $token, $value, $attribs, $selfClose );
  2947. }
  2948. return true;
  2949. case 'body':
  2950. case 'col':
  2951. case 'colgroup':
  2952. // OMITTED: <html>
  2953. case 'tbody':
  2954. case 'td':
  2955. case 'tfoot':
  2956. case 'th':
  2957. case 'thead':
  2958. case 'tr':
  2959. // Ignore the token
  2960. return true;
  2961. }
  2962. // Fall through to "anything else" case.
  2963. }
  2964. // The Anything Else case
  2965. return $this->inBodyMode( $token, $value, $attribs, $selfClose );
  2966. }
  2967. private function inColumnGroupMode( $token, $value, $attribs = null, $selfClose = false ) {
  2968. if ( $token === 'text' ) {
  2969. if ( preg_match( '/^[\x09\x0A\x0C\x0D\x20]+/', $value, $matches ) ) {
  2970. $this->stack->insertText( $matches[0] );
  2971. $value = substr( $value, strlen( $matches[0] ) );
  2972. }
  2973. if ( strlen( $value ) === 0 ) {
  2974. return true; // All text handled.
  2975. }
  2976. // Fall through to handle non-whitespace below.
  2977. } elseif ( $token === 'tag' ) {
  2978. switch ( $value ) {
  2979. // OMITTED: <html>
  2980. case 'col':
  2981. $this->stack->insertHTMLElement( $value, $attribs );
  2982. $this->stack->pop();
  2983. return true;
  2984. case 'template':
  2985. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  2986. }
  2987. // Fall through for "anything else".
  2988. } elseif ( $token === 'endtag' ) {
  2989. switch ( $value ) {
  2990. case 'colgroup':
  2991. if ( !$this->stack->currentNode->isHtmlNamed( 'colgroup' ) ) {
  2992. return true; // Ignore the token.
  2993. }
  2994. $this->stack->pop();
  2995. $this->switchMode( 'inTableMode' );
  2996. return true;
  2997. case 'col':
  2998. return true; // Ignore the token.
  2999. case 'template':
  3000. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  3001. }
  3002. // Fall through for "anything else".
  3003. } elseif ( $token === 'eof' ) {
  3004. return $this->inBodyMode( $token, $value, $attribs, $selfClose );
  3005. } elseif ( $token === 'comment' ) {
  3006. $this->stack->insertComment( $value );
  3007. return true;
  3008. }
  3009. // Anything else
  3010. if ( !$this->stack->currentNode->isHtmlNamed( 'colgroup' ) ) {
  3011. return true; // Ignore the token.
  3012. }
  3013. $this->inColumnGroupMode( 'endtag', 'colgroup' );
  3014. return $this->insertToken( $token, $value, $attribs, $selfClose );
  3015. }
  3016. // Helper function for inTableBodyMode
  3017. private function endSection() {
  3018. if ( !(
  3019. $this->stack->inTableScope( 'tbody' ) ||
  3020. $this->stack->inTableScope( 'thead' ) ||
  3021. $this->stack->inTableScope( 'tfoot' )
  3022. ) ) {
  3023. return false;
  3024. }
  3025. $this->stack->clearToContext( BalanceSets::$tableBodyContextSet );
  3026. $this->stack->pop();
  3027. $this->switchMode( 'inTableMode' );
  3028. return true;
  3029. }
  3030. private function inTableBodyMode( $token, $value, $attribs = null, $selfClose = false ) {
  3031. if ( $token === 'tag' ) {
  3032. switch ( $value ) {
  3033. case 'tr':
  3034. $this->stack->clearToContext( BalanceSets::$tableBodyContextSet );
  3035. $this->stack->insertHTMLElement( $value, $attribs );
  3036. $this->switchMode( 'inRowMode' );
  3037. return true;
  3038. case 'th':
  3039. case 'td':
  3040. $this->inTableBodyMode( 'tag', 'tr', [] );
  3041. $this->insertToken( $token, $value, $attribs, $selfClose );
  3042. return true;
  3043. case 'caption':
  3044. case 'col':
  3045. case 'colgroup':
  3046. case 'tbody':
  3047. case 'tfoot':
  3048. case 'thead':
  3049. if ( $this->endSection() ) {
  3050. $this->insertToken( $token, $value, $attribs, $selfClose );
  3051. }
  3052. return true;
  3053. }
  3054. } elseif ( $token === 'endtag' ) {
  3055. switch ( $value ) {
  3056. case 'table':
  3057. if ( $this->endSection() ) {
  3058. $this->insertToken( $token, $value, $attribs, $selfClose );
  3059. }
  3060. return true;
  3061. case 'tbody':
  3062. case 'tfoot':
  3063. case 'thead':
  3064. if ( $this->stack->inTableScope( $value ) ) {
  3065. $this->endSection();
  3066. }
  3067. return true;
  3068. // OMITTED: <body>
  3069. case 'caption':
  3070. case 'col':
  3071. case 'colgroup':
  3072. // OMITTED: <html>
  3073. case 'td':
  3074. case 'th':
  3075. case 'tr':
  3076. return true; // Ignore the token.
  3077. }
  3078. }
  3079. // Anything else:
  3080. return $this->inTableMode( $token, $value, $attribs, $selfClose );
  3081. }
  3082. // Helper function for inRowMode
  3083. private function endRow() {
  3084. if ( !$this->stack->inTableScope( 'tr' ) ) {
  3085. return false;
  3086. }
  3087. $this->stack->clearToContext( BalanceSets::$tableRowContextSet );
  3088. $this->stack->pop();
  3089. $this->switchMode( 'inTableBodyMode' );
  3090. return true;
  3091. }
  3092. private function inRowMode( $token, $value, $attribs = null, $selfClose = false ) {
  3093. if ( $token === 'tag' ) {
  3094. switch ( $value ) {
  3095. case 'th':
  3096. case 'td':
  3097. $this->stack->clearToContext( BalanceSets::$tableRowContextSet );
  3098. $this->stack->insertHTMLElement( $value, $attribs );
  3099. $this->switchMode( 'inCellMode' );
  3100. $this->afe->insertMarker();
  3101. return true;
  3102. case 'caption':
  3103. case 'col':
  3104. case 'colgroup':
  3105. case 'tbody':
  3106. case 'tfoot':
  3107. case 'thead':
  3108. case 'tr':
  3109. if ( $this->endRow() ) {
  3110. $this->insertToken( $token, $value, $attribs, $selfClose );
  3111. }
  3112. return true;
  3113. }
  3114. } elseif ( $token === 'endtag' ) {
  3115. switch ( $value ) {
  3116. case 'tr':
  3117. $this->endRow();
  3118. return true;
  3119. case 'table':
  3120. if ( $this->endRow() ) {
  3121. $this->insertToken( $token, $value, $attribs, $selfClose );
  3122. }
  3123. return true;
  3124. case 'tbody':
  3125. case 'tfoot':
  3126. case 'thead':
  3127. if (
  3128. $this->stack->inTableScope( $value ) &&
  3129. $this->endRow()
  3130. ) {
  3131. $this->insertToken( $token, $value, $attribs, $selfClose );
  3132. }
  3133. return true;
  3134. // OMITTED: <body>
  3135. case 'caption':
  3136. case 'col':
  3137. case 'colgroup':
  3138. // OMITTED: <html>
  3139. case 'td':
  3140. case 'th':
  3141. return true; // Ignore the token.
  3142. }
  3143. }
  3144. // Anything else:
  3145. return $this->inTableMode( $token, $value, $attribs, $selfClose );
  3146. }
  3147. // Helper for inCellMode
  3148. private function endCell() {
  3149. if ( $this->stack->inTableScope( 'td' ) ) {
  3150. $this->inCellMode( 'endtag', 'td' );
  3151. return true;
  3152. } elseif ( $this->stack->inTableScope( 'th' ) ) {
  3153. $this->inCellMode( 'endtag', 'th' );
  3154. return true;
  3155. } else {
  3156. return false;
  3157. }
  3158. }
  3159. private function inCellMode( $token, $value, $attribs = null, $selfClose = false ) {
  3160. if ( $token === 'tag' ) {
  3161. switch ( $value ) {
  3162. case 'caption':
  3163. case 'col':
  3164. case 'colgroup':
  3165. case 'tbody':
  3166. case 'td':
  3167. case 'tfoot':
  3168. case 'th':
  3169. case 'thead':
  3170. case 'tr':
  3171. if ( $this->endCell() ) {
  3172. $this->insertToken( $token, $value, $attribs, $selfClose );
  3173. }
  3174. return true;
  3175. }
  3176. } elseif ( $token === 'endtag' ) {
  3177. switch ( $value ) {
  3178. case 'td':
  3179. case 'th':
  3180. if ( $this->stack->inTableScope( $value ) ) {
  3181. $this->stack->generateImpliedEndTags();
  3182. $this->stack->popTag( $value );
  3183. $this->afe->clearToMarker();
  3184. $this->switchMode( 'inRowMode' );
  3185. }
  3186. return true;
  3187. // OMITTED: <body>
  3188. case 'caption':
  3189. case 'col':
  3190. case 'colgroup':
  3191. // OMITTED: <html>
  3192. return true;
  3193. case 'table':
  3194. case 'tbody':
  3195. case 'tfoot':
  3196. case 'thead':
  3197. case 'tr':
  3198. if ( $this->stack->inTableScope( $value ) ) {
  3199. $this->stack->generateImpliedEndTags();
  3200. $this->stack->popTag( BalanceSets::$tableCellSet );
  3201. $this->afe->clearToMarker();
  3202. $this->switchMode( 'inRowMode' );
  3203. $this->insertToken( $token, $value, $attribs, $selfClose );
  3204. }
  3205. return true;
  3206. }
  3207. }
  3208. // Anything else:
  3209. return $this->inBodyMode( $token, $value, $attribs, $selfClose );
  3210. }
  3211. private function inSelectMode( $token, $value, $attribs = null, $selfClose = false ) {
  3212. if ( $token === 'text' ) {
  3213. $this->stack->insertText( $value );
  3214. return true;
  3215. } elseif ( $token === 'eof' ) {
  3216. return $this->inBodyMode( $token, $value, $attribs, $selfClose );
  3217. } elseif ( $token === 'tag' ) {
  3218. switch ( $value ) {
  3219. // OMITTED: <html>
  3220. case 'option':
  3221. if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
  3222. $this->stack->pop();
  3223. }
  3224. $this->stack->insertHTMLElement( $value, $attribs );
  3225. return true;
  3226. case 'optgroup':
  3227. if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
  3228. $this->stack->pop();
  3229. }
  3230. if ( $this->stack->currentNode->isHtmlNamed( 'optgroup' ) ) {
  3231. $this->stack->pop();
  3232. }
  3233. $this->stack->insertHTMLElement( $value, $attribs );
  3234. return true;
  3235. case 'select':
  3236. $this->inSelectMode( 'endtag', $value ); // treat it like endtag
  3237. return true;
  3238. case 'input':
  3239. case 'keygen':
  3240. case 'textarea':
  3241. if ( !$this->stack->inSelectScope( 'select' ) ) {
  3242. return true; // ignore token (fragment case)
  3243. }
  3244. $this->inSelectMode( 'endtag', 'select' );
  3245. return $this->insertToken( $token, $value, $attribs, $selfClose );
  3246. case 'script':
  3247. case 'template':
  3248. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  3249. }
  3250. } elseif ( $token === 'endtag' ) {
  3251. switch ( $value ) {
  3252. case 'optgroup':
  3253. if (
  3254. $this->stack->currentNode->isHtmlNamed( 'option' ) &&
  3255. $this->stack->length() >= 2 &&
  3256. $this->stack->node( $this->stack->length() - 2 )->isHtmlNamed( 'optgroup' )
  3257. ) {
  3258. $this->stack->pop();
  3259. }
  3260. if ( $this->stack->currentNode->isHtmlNamed( 'optgroup' ) ) {
  3261. $this->stack->pop();
  3262. }
  3263. return true;
  3264. case 'option':
  3265. if ( $this->stack->currentNode->isHtmlNamed( 'option' ) ) {
  3266. $this->stack->pop();
  3267. }
  3268. return true;
  3269. case 'select':
  3270. if ( !$this->stack->inSelectScope( $value ) ) {
  3271. return true; // fragment case
  3272. }
  3273. $this->stack->popTag( $value );
  3274. $this->resetInsertionMode();
  3275. return true;
  3276. case 'template':
  3277. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  3278. }
  3279. } elseif ( $token === 'comment' ) {
  3280. $this->stack->insertComment( $value );
  3281. return true;
  3282. }
  3283. // anything else: just ignore the token
  3284. return true;
  3285. }
  3286. private function inSelectInTableMode( $token, $value, $attribs = null, $selfClose = false ) {
  3287. switch ( $value ) {
  3288. case 'caption':
  3289. case 'table':
  3290. case 'tbody':
  3291. case 'tfoot':
  3292. case 'thead':
  3293. case 'tr':
  3294. case 'td':
  3295. case 'th':
  3296. if ( $token === 'tag' ) {
  3297. $this->inSelectInTableMode( 'endtag', 'select' );
  3298. return $this->insertToken( $token, $value, $attribs, $selfClose );
  3299. } elseif ( $token === 'endtag' ) {
  3300. if ( $this->stack->inTableScope( $value ) ) {
  3301. $this->inSelectInTableMode( 'endtag', 'select' );
  3302. return $this->insertToken( $token, $value, $attribs, $selfClose );
  3303. }
  3304. return true;
  3305. }
  3306. }
  3307. // anything else
  3308. return $this->inSelectMode( $token, $value, $attribs, $selfClose );
  3309. }
  3310. private function inTemplateMode( $token, $value, $attribs = null, $selfClose = false ) {
  3311. if ( $token === 'text' || $token === 'comment' ) {
  3312. return $this->inBodyMode( $token, $value, $attribs, $selfClose );
  3313. } elseif ( $token === 'eof' ) {
  3314. if ( $this->stack->indexOf( 'template' ) < 0 ) {
  3315. $this->stopParsing();
  3316. } else {
  3317. $this->stack->popTag( 'template' );
  3318. $this->afe->clearToMarker();
  3319. array_pop( $this->templateInsertionModes );
  3320. $this->resetInsertionMode();
  3321. $this->insertToken( $token, $value, $attribs, $selfClose );
  3322. }
  3323. return true;
  3324. } elseif ( $token === 'tag' ) {
  3325. switch ( $value ) {
  3326. case 'base':
  3327. case 'basefont':
  3328. case 'bgsound':
  3329. case 'link':
  3330. case 'meta':
  3331. case 'noframes':
  3332. // OMITTED: <script>
  3333. case 'style':
  3334. case 'template':
  3335. // OMITTED: <title>
  3336. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  3337. case 'caption':
  3338. case 'colgroup':
  3339. case 'tbody':
  3340. case 'tfoot':
  3341. case 'thead':
  3342. return $this->switchModeAndReprocess(
  3343. 'inTableMode', $token, $value, $attribs, $selfClose
  3344. );
  3345. case 'col':
  3346. return $this->switchModeAndReprocess(
  3347. 'inColumnGroupMode', $token, $value, $attribs, $selfClose
  3348. );
  3349. case 'tr':
  3350. return $this->switchModeAndReprocess(
  3351. 'inTableBodyMode', $token, $value, $attribs, $selfClose
  3352. );
  3353. case 'td':
  3354. case 'th':
  3355. return $this->switchModeAndReprocess(
  3356. 'inRowMode', $token, $value, $attribs, $selfClose
  3357. );
  3358. }
  3359. return $this->switchModeAndReprocess(
  3360. 'inBodyMode', $token, $value, $attribs, $selfClose
  3361. );
  3362. } elseif ( $token === 'endtag' ) {
  3363. switch ( $value ) {
  3364. case 'template':
  3365. return $this->inHeadMode( $token, $value, $attribs, $selfClose );
  3366. }
  3367. return true;
  3368. } else {
  3369. Assert::invariant( false, "Bad token type: $token" );
  3370. }
  3371. }
  3372. }