Preprocessor_DOM.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  1. <?php
  2. /**
  3. * @ingroup Parser
  4. */
  5. class Preprocessor_DOM implements Preprocessor {
  6. var $parser, $memoryLimit;
  7. const CACHE_VERSION = 1;
  8. function __construct( $parser ) {
  9. $this->parser = $parser;
  10. $mem = ini_get( 'memory_limit' );
  11. $this->memoryLimit = false;
  12. if ( strval( $mem ) !== '' && $mem != -1 ) {
  13. if ( preg_match( '/^\d+$/', $mem ) ) {
  14. $this->memoryLimit = $mem;
  15. } elseif ( preg_match( '/^(\d+)M$/i', $mem, $m ) ) {
  16. $this->memoryLimit = $m[1] * 1048576;
  17. }
  18. }
  19. }
  20. function newFrame() {
  21. return new PPFrame_DOM( $this );
  22. }
  23. function newCustomFrame( $args ) {
  24. return new PPCustomFrame_DOM( $this, $args );
  25. }
  26. function memCheck() {
  27. if ( $this->memoryLimit === false ) {
  28. return;
  29. }
  30. $usage = memory_get_usage();
  31. if ( $usage > $this->memoryLimit * 0.9 ) {
  32. $limit = intval( $this->memoryLimit * 0.9 / 1048576 + 0.5 );
  33. throw new MWException( "Preprocessor hit 90% memory limit ($limit MB)" );
  34. }
  35. return $usage <= $this->memoryLimit * 0.8;
  36. }
  37. /**
  38. * Preprocess some wikitext and return the document tree.
  39. * This is the ghost of Parser::replace_variables().
  40. *
  41. * @param string $text The text to parse
  42. * @param integer flags Bitwise combination of:
  43. * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
  44. * included. Default is to assume a direct page view.
  45. *
  46. * The generated DOM tree must depend only on the input text and the flags.
  47. * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
  48. *
  49. * Any flag added to the $flags parameter here, or any other parameter liable to cause a
  50. * change in the DOM tree for a given text, must be passed through the section identifier
  51. * in the section edit link and thus back to extractSections().
  52. *
  53. * The output of this function is currently only cached in process memory, but a persistent
  54. * cache may be implemented at a later date which takes further advantage of these strict
  55. * dependency requirements.
  56. *
  57. * @private
  58. */
  59. function preprocessToObj( $text, $flags = 0 ) {
  60. wfProfileIn( __METHOD__ );
  61. global $wgMemc, $wgPreprocessorCacheThreshold;
  62. $xml = false;
  63. $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
  64. if ( $cacheable ) {
  65. wfProfileIn( __METHOD__.'-cacheable' );
  66. $cacheKey = wfMemcKey( 'preprocess-xml', md5($text), $flags );
  67. $cacheValue = $wgMemc->get( $cacheKey );
  68. if ( $cacheValue ) {
  69. $version = substr( $cacheValue, 0, 8 );
  70. if ( intval( $version ) == self::CACHE_VERSION ) {
  71. $xml = substr( $cacheValue, 8 );
  72. // From the cache
  73. wfDebugLog( "Preprocessor", "Loaded preprocessor XML from memcached (key $cacheKey)" );
  74. }
  75. }
  76. }
  77. if ( $xml === false ) {
  78. if ( $cacheable ) {
  79. wfProfileIn( __METHOD__.'-cache-miss' );
  80. $xml = $this->preprocessToXml( $text, $flags );
  81. $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . $xml;
  82. $wgMemc->set( $cacheKey, $cacheValue, 86400 );
  83. wfProfileOut( __METHOD__.'-cache-miss' );
  84. wfDebugLog( "Preprocessor", "Saved preprocessor XML to memcached (key $cacheKey)" );
  85. } else {
  86. $xml = $this->preprocessToXml( $text, $flags );
  87. }
  88. }
  89. wfProfileIn( __METHOD__.'-loadXML' );
  90. $dom = new DOMDocument;
  91. wfSuppressWarnings();
  92. $result = $dom->loadXML( $xml );
  93. wfRestoreWarnings();
  94. if ( !$result ) {
  95. // Try running the XML through UtfNormal to get rid of invalid characters
  96. $xml = UtfNormal::cleanUp( $xml );
  97. $result = $dom->loadXML( $xml );
  98. if ( !$result ) {
  99. throw new MWException( __METHOD__.' generated invalid XML' );
  100. }
  101. }
  102. $obj = new PPNode_DOM( $dom->documentElement );
  103. wfProfileOut( __METHOD__.'-loadXML' );
  104. if ( $cacheable ) {
  105. wfProfileOut( __METHOD__.'-cacheable' );
  106. }
  107. wfProfileOut( __METHOD__ );
  108. return $obj;
  109. }
  110. function preprocessToXml( $text, $flags = 0 ) {
  111. wfProfileIn( __METHOD__ );
  112. $rules = array(
  113. '{' => array(
  114. 'end' => '}',
  115. 'names' => array(
  116. 2 => 'template',
  117. 3 => 'tplarg',
  118. ),
  119. 'min' => 2,
  120. 'max' => 3,
  121. ),
  122. '[' => array(
  123. 'end' => ']',
  124. 'names' => array( 2 => null ),
  125. 'min' => 2,
  126. 'max' => 2,
  127. )
  128. );
  129. $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
  130. $xmlishElements = $this->parser->getStripList();
  131. $enableOnlyinclude = false;
  132. if ( $forInclusion ) {
  133. $ignoredTags = array( 'includeonly', '/includeonly' );
  134. $ignoredElements = array( 'noinclude' );
  135. $xmlishElements[] = 'noinclude';
  136. if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
  137. $enableOnlyinclude = true;
  138. }
  139. } else {
  140. $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
  141. $ignoredElements = array( 'includeonly' );
  142. $xmlishElements[] = 'includeonly';
  143. }
  144. $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
  145. // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
  146. $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
  147. $stack = new PPDStack;
  148. $searchBase = "[{<\n"; #}
  149. $revText = strrev( $text ); // For fast reverse searches
  150. $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
  151. $accum =& $stack->getAccum(); # Current accumulator
  152. $accum = '<root>';
  153. $findEquals = false; # True to find equals signs in arguments
  154. $findPipe = false; # True to take notice of pipe characters
  155. $headingIndex = 1;
  156. $inHeading = false; # True if $i is inside a possible heading
  157. $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
  158. $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
  159. $fakeLineStart = true; # Do a line-start run without outputting an LF character
  160. while ( true ) {
  161. //$this->memCheck();
  162. if ( $findOnlyinclude ) {
  163. // Ignore all input up to the next <onlyinclude>
  164. $startPos = strpos( $text, '<onlyinclude>', $i );
  165. if ( $startPos === false ) {
  166. // Ignored section runs to the end
  167. $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
  168. break;
  169. }
  170. $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
  171. $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
  172. $i = $tagEndPos;
  173. $findOnlyinclude = false;
  174. }
  175. if ( $fakeLineStart ) {
  176. $found = 'line-start';
  177. $curChar = '';
  178. } else {
  179. # Find next opening brace, closing brace or pipe
  180. $search = $searchBase;
  181. if ( $stack->top === false ) {
  182. $currentClosing = '';
  183. } else {
  184. $currentClosing = $stack->top->close;
  185. $search .= $currentClosing;
  186. }
  187. if ( $findPipe ) {
  188. $search .= '|';
  189. }
  190. if ( $findEquals ) {
  191. // First equals will be for the template
  192. $search .= '=';
  193. }
  194. $rule = null;
  195. # Output literal section, advance input counter
  196. $literalLength = strcspn( $text, $search, $i );
  197. if ( $literalLength > 0 ) {
  198. $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
  199. $i += $literalLength;
  200. }
  201. if ( $i >= strlen( $text ) ) {
  202. if ( $currentClosing == "\n" ) {
  203. // Do a past-the-end run to finish off the heading
  204. $curChar = '';
  205. $found = 'line-end';
  206. } else {
  207. # All done
  208. break;
  209. }
  210. } else {
  211. $curChar = $text[$i];
  212. if ( $curChar == '|' ) {
  213. $found = 'pipe';
  214. } elseif ( $curChar == '=' ) {
  215. $found = 'equals';
  216. } elseif ( $curChar == '<' ) {
  217. $found = 'angle';
  218. } elseif ( $curChar == "\n" ) {
  219. if ( $inHeading ) {
  220. $found = 'line-end';
  221. } else {
  222. $found = 'line-start';
  223. }
  224. } elseif ( $curChar == $currentClosing ) {
  225. $found = 'close';
  226. } elseif ( isset( $rules[$curChar] ) ) {
  227. $found = 'open';
  228. $rule = $rules[$curChar];
  229. } else {
  230. # Some versions of PHP have a strcspn which stops on null characters
  231. # Ignore and continue
  232. ++$i;
  233. continue;
  234. }
  235. }
  236. }
  237. if ( $found == 'angle' ) {
  238. $matches = false;
  239. // Handle </onlyinclude>
  240. if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
  241. $findOnlyinclude = true;
  242. continue;
  243. }
  244. // Determine element name
  245. if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
  246. // Element name missing or not listed
  247. $accum .= '&lt;';
  248. ++$i;
  249. continue;
  250. }
  251. // Handle comments
  252. if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
  253. // To avoid leaving blank lines, when a comment is both preceded
  254. // and followed by a newline (ignoring spaces), trim leading and
  255. // trailing spaces and one of the newlines.
  256. // Find the end
  257. $endPos = strpos( $text, '-->', $i + 4 );
  258. if ( $endPos === false ) {
  259. // Unclosed comment in input, runs to end
  260. $inner = substr( $text, $i );
  261. $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
  262. $i = strlen( $text );
  263. } else {
  264. // Search backwards for leading whitespace
  265. $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
  266. // Search forwards for trailing whitespace
  267. // $wsEnd will be the position of the last space
  268. $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
  269. // Eat the line if possible
  270. // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
  271. // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
  272. // it's a possible beneficial b/c break.
  273. if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
  274. && substr( $text, $wsEnd + 1, 1 ) == "\n" )
  275. {
  276. $startPos = $wsStart;
  277. $endPos = $wsEnd + 1;
  278. // Remove leading whitespace from the end of the accumulator
  279. // Sanity check first though
  280. $wsLength = $i - $wsStart;
  281. if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
  282. $accum = substr( $accum, 0, -$wsLength );
  283. }
  284. // Do a line-start run next time to look for headings after the comment
  285. $fakeLineStart = true;
  286. } else {
  287. // No line to eat, just take the comment itself
  288. $startPos = $i;
  289. $endPos += 2;
  290. }
  291. if ( $stack->top ) {
  292. $part = $stack->top->getCurrentPart();
  293. if ( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) {
  294. // Comments abutting, no change in visual end
  295. $part->commentEnd = $wsEnd;
  296. } else {
  297. $part->visualEnd = $wsStart;
  298. $part->commentEnd = $endPos;
  299. }
  300. }
  301. $i = $endPos + 1;
  302. $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
  303. $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
  304. }
  305. continue;
  306. }
  307. $name = $matches[1];
  308. $lowerName = strtolower( $name );
  309. $attrStart = $i + strlen( $name ) + 1;
  310. // Find end of tag
  311. $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
  312. if ( $tagEndPos === false ) {
  313. // Infinite backtrack
  314. // Disable tag search to prevent worst-case O(N^2) performance
  315. $noMoreGT = true;
  316. $accum .= '&lt;';
  317. ++$i;
  318. continue;
  319. }
  320. // Handle ignored tags
  321. if ( in_array( $lowerName, $ignoredTags ) ) {
  322. $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
  323. $i = $tagEndPos + 1;
  324. continue;
  325. }
  326. $tagStartPos = $i;
  327. if ( $text[$tagEndPos-1] == '/' ) {
  328. $attrEnd = $tagEndPos - 1;
  329. $inner = null;
  330. $i = $tagEndPos + 1;
  331. $close = '';
  332. } else {
  333. $attrEnd = $tagEndPos;
  334. // Find closing tag
  335. if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
  336. $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
  337. {
  338. $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
  339. $i = $matches[0][1] + strlen( $matches[0][0] );
  340. $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
  341. } else {
  342. // No end tag -- let it run out to the end of the text.
  343. $inner = substr( $text, $tagEndPos + 1 );
  344. $i = strlen( $text );
  345. $close = '';
  346. }
  347. }
  348. // <includeonly> and <noinclude> just become <ignore> tags
  349. if ( in_array( $lowerName, $ignoredElements ) ) {
  350. $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
  351. . '</ignore>';
  352. continue;
  353. }
  354. $accum .= '<ext>';
  355. if ( $attrEnd <= $attrStart ) {
  356. $attr = '';
  357. } else {
  358. $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
  359. }
  360. $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
  361. // Note that the attr element contains the whitespace between name and attribute,
  362. // this is necessary for precise reconstruction during pre-save transform.
  363. '<attr>' . htmlspecialchars( $attr ) . '</attr>';
  364. if ( $inner !== null ) {
  365. $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
  366. }
  367. $accum .= $close . '</ext>';
  368. }
  369. elseif ( $found == 'line-start' ) {
  370. // Is this the start of a heading?
  371. // Line break belongs before the heading element in any case
  372. if ( $fakeLineStart ) {
  373. $fakeLineStart = false;
  374. } else {
  375. $accum .= $curChar;
  376. $i++;
  377. }
  378. $count = strspn( $text, '=', $i, 6 );
  379. if ( $count == 1 && $findEquals ) {
  380. // DWIM: This looks kind of like a name/value separator
  381. // Let's let the equals handler have it and break the potential heading
  382. // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
  383. } elseif ( $count > 0 ) {
  384. $piece = array(
  385. 'open' => "\n",
  386. 'close' => "\n",
  387. 'parts' => array( new PPDPart( str_repeat( '=', $count ) ) ),
  388. 'startPos' => $i,
  389. 'count' => $count );
  390. $stack->push( $piece );
  391. $accum =& $stack->getAccum();
  392. extract( $stack->getFlags() );
  393. $i += $count;
  394. }
  395. }
  396. elseif ( $found == 'line-end' ) {
  397. $piece = $stack->top;
  398. // A heading must be open, otherwise \n wouldn't have been in the search list
  399. assert( $piece->open == "\n" );
  400. $part = $piece->getCurrentPart();
  401. // Search back through the input to see if it has a proper close
  402. // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
  403. $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
  404. $searchStart = $i - $wsLength;
  405. if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
  406. // Comment found at line end
  407. // Search for equals signs before the comment
  408. $searchStart = $part->visualEnd;
  409. $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
  410. }
  411. $count = $piece->count;
  412. $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
  413. if ( $equalsLength > 0 ) {
  414. if ( $i - $equalsLength == $piece->startPos ) {
  415. // This is just a single string of equals signs on its own line
  416. // Replicate the doHeadings behaviour /={count}(.+)={count}/
  417. // First find out how many equals signs there really are (don't stop at 6)
  418. $count = $equalsLength;
  419. if ( $count < 3 ) {
  420. $count = 0;
  421. } else {
  422. $count = min( 6, intval( ( $count - 1 ) / 2 ) );
  423. }
  424. } else {
  425. $count = min( $equalsLength, $count );
  426. }
  427. if ( $count > 0 ) {
  428. // Normal match, output <h>
  429. $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
  430. $headingIndex++;
  431. } else {
  432. // Single equals sign on its own line, count=0
  433. $element = $accum;
  434. }
  435. } else {
  436. // No match, no <h>, just pass down the inner text
  437. $element = $accum;
  438. }
  439. // Unwind the stack
  440. $stack->pop();
  441. $accum =& $stack->getAccum();
  442. extract( $stack->getFlags() );
  443. // Append the result to the enclosing accumulator
  444. $accum .= $element;
  445. // Note that we do NOT increment the input pointer.
  446. // This is because the closing linebreak could be the opening linebreak of
  447. // another heading. Infinite loops are avoided because the next iteration MUST
  448. // hit the heading open case above, which unconditionally increments the
  449. // input pointer.
  450. }
  451. elseif ( $found == 'open' ) {
  452. # count opening brace characters
  453. $count = strspn( $text, $curChar, $i );
  454. # we need to add to stack only if opening brace count is enough for one of the rules
  455. if ( $count >= $rule['min'] ) {
  456. # Add it to the stack
  457. $piece = array(
  458. 'open' => $curChar,
  459. 'close' => $rule['end'],
  460. 'count' => $count,
  461. 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
  462. );
  463. $stack->push( $piece );
  464. $accum =& $stack->getAccum();
  465. extract( $stack->getFlags() );
  466. } else {
  467. # Add literal brace(s)
  468. $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
  469. }
  470. $i += $count;
  471. }
  472. elseif ( $found == 'close' ) {
  473. $piece = $stack->top;
  474. # lets check if there are enough characters for closing brace
  475. $maxCount = $piece->count;
  476. $count = strspn( $text, $curChar, $i, $maxCount );
  477. # check for maximum matching characters (if there are 5 closing
  478. # characters, we will probably need only 3 - depending on the rules)
  479. $matchingCount = 0;
  480. $rule = $rules[$piece->open];
  481. if ( $count > $rule['max'] ) {
  482. # The specified maximum exists in the callback array, unless the caller
  483. # has made an error
  484. $matchingCount = $rule['max'];
  485. } else {
  486. # Count is less than the maximum
  487. # Skip any gaps in the callback array to find the true largest match
  488. # Need to use array_key_exists not isset because the callback can be null
  489. $matchingCount = $count;
  490. while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
  491. --$matchingCount;
  492. }
  493. }
  494. if ($matchingCount <= 0) {
  495. # No matching element found in callback array
  496. # Output a literal closing brace and continue
  497. $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
  498. $i += $count;
  499. continue;
  500. }
  501. $name = $rule['names'][$matchingCount];
  502. if ( $name === null ) {
  503. // No element, just literal text
  504. $element = $piece->breakSyntax( $matchingCount ) . str_repeat( $rule['end'], $matchingCount );
  505. } else {
  506. # Create XML element
  507. # Note: $parts is already XML, does not need to be encoded further
  508. $parts = $piece->parts;
  509. $title = $parts[0]->out;
  510. unset( $parts[0] );
  511. # The invocation is at the start of the line if lineStart is set in
  512. # the stack, and all opening brackets are used up.
  513. if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
  514. $attr = ' lineStart="1"';
  515. } else {
  516. $attr = '';
  517. }
  518. $element = "<$name$attr>";
  519. $element .= "<title>$title</title>";
  520. $argIndex = 1;
  521. foreach ( $parts as $partIndex => $part ) {
  522. if ( isset( $part->eqpos ) ) {
  523. $argName = substr( $part->out, 0, $part->eqpos );
  524. $argValue = substr( $part->out, $part->eqpos + 1 );
  525. $element .= "<part><name>$argName</name>=<value>$argValue</value></part>";
  526. } else {
  527. $element .= "<part><name index=\"$argIndex\" /><value>{$part->out}</value></part>";
  528. $argIndex++;
  529. }
  530. }
  531. $element .= "</$name>";
  532. }
  533. # Advance input pointer
  534. $i += $matchingCount;
  535. # Unwind the stack
  536. $stack->pop();
  537. $accum =& $stack->getAccum();
  538. # Re-add the old stack element if it still has unmatched opening characters remaining
  539. if ($matchingCount < $piece->count) {
  540. $piece->parts = array( new PPDPart );
  541. $piece->count -= $matchingCount;
  542. # do we still qualify for any callback with remaining count?
  543. $names = $rules[$piece->open]['names'];
  544. $skippedBraces = 0;
  545. $enclosingAccum =& $accum;
  546. while ( $piece->count ) {
  547. if ( array_key_exists( $piece->count, $names ) ) {
  548. $stack->push( $piece );
  549. $accum =& $stack->getAccum();
  550. break;
  551. }
  552. --$piece->count;
  553. $skippedBraces ++;
  554. }
  555. $enclosingAccum .= str_repeat( $piece->open, $skippedBraces );
  556. }
  557. extract( $stack->getFlags() );
  558. # Add XML element to the enclosing accumulator
  559. $accum .= $element;
  560. }
  561. elseif ( $found == 'pipe' ) {
  562. $findEquals = true; // shortcut for getFlags()
  563. $stack->addPart();
  564. $accum =& $stack->getAccum();
  565. ++$i;
  566. }
  567. elseif ( $found == 'equals' ) {
  568. $findEquals = false; // shortcut for getFlags()
  569. $stack->getCurrentPart()->eqpos = strlen( $accum );
  570. $accum .= '=';
  571. ++$i;
  572. }
  573. }
  574. # Output any remaining unclosed brackets
  575. foreach ( $stack->stack as $piece ) {
  576. $stack->rootAccum .= $piece->breakSyntax();
  577. }
  578. $stack->rootAccum .= '</root>';
  579. $xml = $stack->rootAccum;
  580. wfProfileOut( __METHOD__ );
  581. return $xml;
  582. }
  583. }
  584. /**
  585. * Stack class to help Preprocessor::preprocessToObj()
  586. * @ingroup Parser
  587. */
  588. class PPDStack {
  589. var $stack, $rootAccum, $top;
  590. var $out;
  591. var $elementClass = 'PPDStackElement';
  592. static $false = false;
  593. function __construct() {
  594. $this->stack = array();
  595. $this->top = false;
  596. $this->rootAccum = '';
  597. $this->accum =& $this->rootAccum;
  598. }
  599. function count() {
  600. return count( $this->stack );
  601. }
  602. function &getAccum() {
  603. return $this->accum;
  604. }
  605. function getCurrentPart() {
  606. if ( $this->top === false ) {
  607. return false;
  608. } else {
  609. return $this->top->getCurrentPart();
  610. }
  611. }
  612. function push( $data ) {
  613. if ( $data instanceof $this->elementClass ) {
  614. $this->stack[] = $data;
  615. } else {
  616. $class = $this->elementClass;
  617. $this->stack[] = new $class( $data );
  618. }
  619. $this->top = $this->stack[ count( $this->stack ) - 1 ];
  620. $this->accum =& $this->top->getAccum();
  621. }
  622. function pop() {
  623. if ( !count( $this->stack ) ) {
  624. throw new MWException( __METHOD__.': no elements remaining' );
  625. }
  626. $temp = array_pop( $this->stack );
  627. if ( count( $this->stack ) ) {
  628. $this->top = $this->stack[ count( $this->stack ) - 1 ];
  629. $this->accum =& $this->top->getAccum();
  630. } else {
  631. $this->top = self::$false;
  632. $this->accum =& $this->rootAccum;
  633. }
  634. return $temp;
  635. }
  636. function addPart( $s = '' ) {
  637. $this->top->addPart( $s );
  638. $this->accum =& $this->top->getAccum();
  639. }
  640. function getFlags() {
  641. if ( !count( $this->stack ) ) {
  642. return array(
  643. 'findEquals' => false,
  644. 'findPipe' => false,
  645. 'inHeading' => false,
  646. );
  647. } else {
  648. return $this->top->getFlags();
  649. }
  650. }
  651. }
  652. /**
  653. * @ingroup Parser
  654. */
  655. class PPDStackElement {
  656. var $open, // Opening character (\n for heading)
  657. $close, // Matching closing character
  658. $count, // Number of opening characters found (number of "=" for heading)
  659. $parts, // Array of PPDPart objects describing pipe-separated parts.
  660. $lineStart; // True if the open char appeared at the start of the input line. Not set for headings.
  661. var $partClass = 'PPDPart';
  662. function __construct( $data = array() ) {
  663. $class = $this->partClass;
  664. $this->parts = array( new $class );
  665. foreach ( $data as $name => $value ) {
  666. $this->$name = $value;
  667. }
  668. }
  669. function &getAccum() {
  670. return $this->parts[count($this->parts) - 1]->out;
  671. }
  672. function addPart( $s = '' ) {
  673. $class = $this->partClass;
  674. $this->parts[] = new $class( $s );
  675. }
  676. function getCurrentPart() {
  677. return $this->parts[count($this->parts) - 1];
  678. }
  679. function getFlags() {
  680. $partCount = count( $this->parts );
  681. $findPipe = $this->open != "\n" && $this->open != '[';
  682. return array(
  683. 'findPipe' => $findPipe,
  684. 'findEquals' => $findPipe && $partCount > 1 && !isset( $this->parts[$partCount - 1]->eqpos ),
  685. 'inHeading' => $this->open == "\n",
  686. );
  687. }
  688. /**
  689. * Get the output string that would result if the close is not found.
  690. */
  691. function breakSyntax( $openingCount = false ) {
  692. if ( $this->open == "\n" ) {
  693. $s = $this->parts[0]->out;
  694. } else {
  695. if ( $openingCount === false ) {
  696. $openingCount = $this->count;
  697. }
  698. $s = str_repeat( $this->open, $openingCount );
  699. $first = true;
  700. foreach ( $this->parts as $part ) {
  701. if ( $first ) {
  702. $first = false;
  703. } else {
  704. $s .= '|';
  705. }
  706. $s .= $part->out;
  707. }
  708. }
  709. return $s;
  710. }
  711. }
  712. /**
  713. * @ingroup Parser
  714. */
  715. class PPDPart {
  716. var $out; // Output accumulator string
  717. // Optional member variables:
  718. // eqpos Position of equals sign in output accumulator
  719. // commentEnd Past-the-end input pointer for the last comment encountered
  720. // visualEnd Past-the-end input pointer for the end of the accumulator minus comments
  721. function __construct( $out = '' ) {
  722. $this->out = $out;
  723. }
  724. }
  725. /**
  726. * An expansion frame, used as a context to expand the result of preprocessToObj()
  727. * @ingroup Parser
  728. */
  729. class PPFrame_DOM implements PPFrame {
  730. var $preprocessor, $parser, $title;
  731. var $titleCache;
  732. /**
  733. * Hashtable listing templates which are disallowed for expansion in this frame,
  734. * having been encountered previously in parent frames.
  735. */
  736. var $loopCheckHash;
  737. /**
  738. * Recursion depth of this frame, top = 0
  739. * Note that this is NOT the same as expansion depth in expand()
  740. */
  741. var $depth;
  742. /**
  743. * Construct a new preprocessor frame.
  744. * @param Preprocessor $preprocessor The parent preprocessor
  745. */
  746. function __construct( $preprocessor ) {
  747. $this->preprocessor = $preprocessor;
  748. $this->parser = $preprocessor->parser;
  749. $this->title = $this->parser->mTitle;
  750. $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
  751. $this->loopCheckHash = array();
  752. $this->depth = 0;
  753. }
  754. /**
  755. * Create a new child frame
  756. * $args is optionally a multi-root PPNode or array containing the template arguments
  757. */
  758. function newChild( $args = false, $title = false ) {
  759. $namedArgs = array();
  760. $numberedArgs = array();
  761. if ( $title === false ) {
  762. $title = $this->title;
  763. }
  764. if ( $args !== false ) {
  765. $xpath = false;
  766. if ( $args instanceof PPNode ) {
  767. $args = $args->node;
  768. }
  769. foreach ( $args as $arg ) {
  770. if ( !$xpath ) {
  771. $xpath = new DOMXPath( $arg->ownerDocument );
  772. }
  773. $nameNodes = $xpath->query( 'name', $arg );
  774. $value = $xpath->query( 'value', $arg );
  775. if ( $nameNodes->item( 0 )->hasAttributes() ) {
  776. // Numbered parameter
  777. $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
  778. $numberedArgs[$index] = $value->item( 0 );
  779. unset( $namedArgs[$index] );
  780. } else {
  781. // Named parameter
  782. $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
  783. $namedArgs[$name] = $value->item( 0 );
  784. unset( $numberedArgs[$name] );
  785. }
  786. }
  787. }
  788. return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
  789. }
  790. function expand( $root, $flags = 0 ) {
  791. static $expansionDepth = 0;
  792. if ( is_string( $root ) ) {
  793. return $root;
  794. }
  795. if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->mMaxPPNodeCount )
  796. {
  797. return '<span class="error">Node-count limit exceeded</span>';
  798. }
  799. if ( $expansionDepth > $this->parser->mOptions->mMaxPPExpandDepth ) {
  800. return '<span class="error">Expansion depth limit exceeded</span>';
  801. }
  802. wfProfileIn( __METHOD__ );
  803. ++$expansionDepth;
  804. if ( $root instanceof PPNode_DOM ) {
  805. $root = $root->node;
  806. }
  807. if ( $root instanceof DOMDocument ) {
  808. $root = $root->documentElement;
  809. }
  810. $outStack = array( '', '' );
  811. $iteratorStack = array( false, $root );
  812. $indexStack = array( 0, 0 );
  813. while ( count( $iteratorStack ) > 1 ) {
  814. $level = count( $outStack ) - 1;
  815. $iteratorNode =& $iteratorStack[ $level ];
  816. $out =& $outStack[$level];
  817. $index =& $indexStack[$level];
  818. if ( $iteratorNode instanceof PPNode_DOM ) $iteratorNode = $iteratorNode->node;
  819. if ( is_array( $iteratorNode ) ) {
  820. if ( $index >= count( $iteratorNode ) ) {
  821. // All done with this iterator
  822. $iteratorStack[$level] = false;
  823. $contextNode = false;
  824. } else {
  825. $contextNode = $iteratorNode[$index];
  826. $index++;
  827. }
  828. } elseif ( $iteratorNode instanceof DOMNodeList ) {
  829. if ( $index >= $iteratorNode->length ) {
  830. // All done with this iterator
  831. $iteratorStack[$level] = false;
  832. $contextNode = false;
  833. } else {
  834. $contextNode = $iteratorNode->item( $index );
  835. $index++;
  836. }
  837. } else {
  838. // Copy to $contextNode and then delete from iterator stack,
  839. // because this is not an iterator but we do have to execute it once
  840. $contextNode = $iteratorStack[$level];
  841. $iteratorStack[$level] = false;
  842. }
  843. if ( $contextNode instanceof PPNode_DOM ) $contextNode = $contextNode->node;
  844. $newIterator = false;
  845. if ( $contextNode === false ) {
  846. // nothing to do
  847. } elseif ( is_string( $contextNode ) ) {
  848. $out .= $contextNode;
  849. } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
  850. $newIterator = $contextNode;
  851. } elseif ( $contextNode instanceof DOMNode ) {
  852. if ( $contextNode->nodeType == XML_TEXT_NODE ) {
  853. $out .= $contextNode->nodeValue;
  854. } elseif ( $contextNode->nodeName == 'template' ) {
  855. # Double-brace expansion
  856. $xpath = new DOMXPath( $contextNode->ownerDocument );
  857. $titles = $xpath->query( 'title', $contextNode );
  858. $title = $titles->item( 0 );
  859. $parts = $xpath->query( 'part', $contextNode );
  860. if ( $flags & self::NO_TEMPLATES ) {
  861. $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
  862. } else {
  863. $lineStart = $contextNode->getAttribute( 'lineStart' );
  864. $params = array(
  865. 'title' => new PPNode_DOM( $title ),
  866. 'parts' => new PPNode_DOM( $parts ),
  867. 'lineStart' => $lineStart );
  868. $ret = $this->parser->braceSubstitution( $params, $this );
  869. if ( isset( $ret['object'] ) ) {
  870. $newIterator = $ret['object'];
  871. } else {
  872. $out .= $ret['text'];
  873. }
  874. }
  875. } elseif ( $contextNode->nodeName == 'tplarg' ) {
  876. # Triple-brace expansion
  877. $xpath = new DOMXPath( $contextNode->ownerDocument );
  878. $titles = $xpath->query( 'title', $contextNode );
  879. $title = $titles->item( 0 );
  880. $parts = $xpath->query( 'part', $contextNode );
  881. if ( $flags & self::NO_ARGS ) {
  882. $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
  883. } else {
  884. $params = array(
  885. 'title' => new PPNode_DOM( $title ),
  886. 'parts' => new PPNode_DOM( $parts ) );
  887. $ret = $this->parser->argSubstitution( $params, $this );
  888. if ( isset( $ret['object'] ) ) {
  889. $newIterator = $ret['object'];
  890. } else {
  891. $out .= $ret['text'];
  892. }
  893. }
  894. } elseif ( $contextNode->nodeName == 'comment' ) {
  895. # HTML-style comment
  896. # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
  897. if ( $this->parser->ot['html']
  898. || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
  899. || ( $flags & self::STRIP_COMMENTS ) )
  900. {
  901. $out .= '';
  902. }
  903. # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
  904. # Not in RECOVER_COMMENTS mode (extractSections) though
  905. elseif ( $this->parser->ot['wiki'] && ! ( $flags & self::RECOVER_COMMENTS ) ) {
  906. $out .= $this->parser->insertStripItem( $contextNode->textContent );
  907. }
  908. # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
  909. else {
  910. $out .= $contextNode->textContent;
  911. }
  912. } elseif ( $contextNode->nodeName == 'ignore' ) {
  913. # Output suppression used by <includeonly> etc.
  914. # OT_WIKI will only respect <ignore> in substed templates.
  915. # The other output types respect it unless NO_IGNORE is set.
  916. # extractSections() sets NO_IGNORE and so never respects it.
  917. if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & self::NO_IGNORE ) ) {
  918. $out .= $contextNode->textContent;
  919. } else {
  920. $out .= '';
  921. }
  922. } elseif ( $contextNode->nodeName == 'ext' ) {
  923. # Extension tag
  924. $xpath = new DOMXPath( $contextNode->ownerDocument );
  925. $names = $xpath->query( 'name', $contextNode );
  926. $attrs = $xpath->query( 'attr', $contextNode );
  927. $inners = $xpath->query( 'inner', $contextNode );
  928. $closes = $xpath->query( 'close', $contextNode );
  929. $params = array(
  930. 'name' => new PPNode_DOM( $names->item( 0 ) ),
  931. 'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
  932. 'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
  933. 'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
  934. );
  935. $out .= $this->parser->extensionSubstitution( $params, $this );
  936. } elseif ( $contextNode->nodeName == 'h' ) {
  937. # Heading
  938. $s = $this->expand( $contextNode->childNodes, $flags );
  939. # Insert a heading marker only for <h> children of <root>
  940. # This is to stop extractSections from going over multiple tree levels
  941. if ( $contextNode->parentNode->nodeName == 'root'
  942. && $this->parser->ot['html'] )
  943. {
  944. # Insert heading index marker
  945. $headingIndex = $contextNode->getAttribute( 'i' );
  946. $titleText = $this->title->getPrefixedDBkey();
  947. $this->parser->mHeadings[] = array( $titleText, $headingIndex );
  948. $serial = count( $this->parser->mHeadings ) - 1;
  949. $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
  950. $count = $contextNode->getAttribute( 'level' );
  951. $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
  952. $this->parser->mStripState->general->setPair( $marker, '' );
  953. }
  954. $out .= $s;
  955. } else {
  956. # Generic recursive expansion
  957. $newIterator = $contextNode->childNodes;
  958. }
  959. } else {
  960. wfProfileOut( __METHOD__ );
  961. throw new MWException( __METHOD__.': Invalid parameter type' );
  962. }
  963. if ( $newIterator !== false ) {
  964. if ( $newIterator instanceof PPNode_DOM ) {
  965. $newIterator = $newIterator->node;
  966. }
  967. $outStack[] = '';
  968. $iteratorStack[] = $newIterator;
  969. $indexStack[] = 0;
  970. } elseif ( $iteratorStack[$level] === false ) {
  971. // Return accumulated value to parent
  972. // With tail recursion
  973. while ( $iteratorStack[$level] === false && $level > 0 ) {
  974. $outStack[$level - 1] .= $out;
  975. array_pop( $outStack );
  976. array_pop( $iteratorStack );
  977. array_pop( $indexStack );
  978. $level--;
  979. }
  980. }
  981. }
  982. --$expansionDepth;
  983. wfProfileOut( __METHOD__ );
  984. return $outStack[0];
  985. }
  986. function implodeWithFlags( $sep, $flags /*, ... */ ) {
  987. $args = array_slice( func_get_args(), 2 );
  988. $first = true;
  989. $s = '';
  990. foreach ( $args as $root ) {
  991. if ( $root instanceof PPNode_DOM ) $root = $root->node;
  992. if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
  993. $root = array( $root );
  994. }
  995. foreach ( $root as $node ) {
  996. if ( $first ) {
  997. $first = false;
  998. } else {
  999. $s .= $sep;
  1000. }
  1001. $s .= $this->expand( $node, $flags );
  1002. }
  1003. }
  1004. return $s;
  1005. }
  1006. /**
  1007. * Implode with no flags specified
  1008. * This previously called implodeWithFlags but has now been inlined to reduce stack depth
  1009. */
  1010. function implode( $sep /*, ... */ ) {
  1011. $args = array_slice( func_get_args(), 1 );
  1012. $first = true;
  1013. $s = '';
  1014. foreach ( $args as $root ) {
  1015. if ( $root instanceof PPNode_DOM ) $root = $root->node;
  1016. if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
  1017. $root = array( $root );
  1018. }
  1019. foreach ( $root as $node ) {
  1020. if ( $first ) {
  1021. $first = false;
  1022. } else {
  1023. $s .= $sep;
  1024. }
  1025. $s .= $this->expand( $node );
  1026. }
  1027. }
  1028. return $s;
  1029. }
  1030. /**
  1031. * Makes an object that, when expand()ed, will be the same as one obtained
  1032. * with implode()
  1033. */
  1034. function virtualImplode( $sep /*, ... */ ) {
  1035. $args = array_slice( func_get_args(), 1 );
  1036. $out = array();
  1037. $first = true;
  1038. if ( $root instanceof PPNode_DOM ) $root = $root->node;
  1039. foreach ( $args as $root ) {
  1040. if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
  1041. $root = array( $root );
  1042. }
  1043. foreach ( $root as $node ) {
  1044. if ( $first ) {
  1045. $first = false;
  1046. } else {
  1047. $out[] = $sep;
  1048. }
  1049. $out[] = $node;
  1050. }
  1051. }
  1052. return $out;
  1053. }
  1054. /**
  1055. * Virtual implode with brackets
  1056. */
  1057. function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
  1058. $args = array_slice( func_get_args(), 3 );
  1059. $out = array( $start );
  1060. $first = true;
  1061. foreach ( $args as $root ) {
  1062. if ( $root instanceof PPNode_DOM ) $root = $root->node;
  1063. if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
  1064. $root = array( $root );
  1065. }
  1066. foreach ( $root as $node ) {
  1067. if ( $first ) {
  1068. $first = false;
  1069. } else {
  1070. $out[] = $sep;
  1071. }
  1072. $out[] = $node;
  1073. }
  1074. }
  1075. $out[] = $end;
  1076. return $out;
  1077. }
  1078. function __toString() {
  1079. return 'frame{}';
  1080. }
  1081. function getPDBK( $level = false ) {
  1082. if ( $level === false ) {
  1083. return $this->title->getPrefixedDBkey();
  1084. } else {
  1085. return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
  1086. }
  1087. }
  1088. /**
  1089. * Returns true if there are no arguments in this frame
  1090. */
  1091. function isEmpty() {
  1092. return true;
  1093. }
  1094. function getArgument( $name ) {
  1095. return false;
  1096. }
  1097. /**
  1098. * Returns true if the infinite loop check is OK, false if a loop is detected
  1099. */
  1100. function loopCheck( $title ) {
  1101. return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
  1102. }
  1103. /**
  1104. * Return true if the frame is a template frame
  1105. */
  1106. function isTemplate() {
  1107. return false;
  1108. }
  1109. }
  1110. /**
  1111. * Expansion frame with template arguments
  1112. * @ingroup Parser
  1113. */
  1114. class PPTemplateFrame_DOM extends PPFrame_DOM {
  1115. var $numberedArgs, $namedArgs, $parent;
  1116. var $numberedExpansionCache, $namedExpansionCache;
  1117. function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
  1118. $this->preprocessor = $preprocessor;
  1119. $this->parser = $preprocessor->parser;
  1120. $this->parent = $parent;
  1121. $this->numberedArgs = $numberedArgs;
  1122. $this->namedArgs = $namedArgs;
  1123. $this->title = $title;
  1124. $pdbk = $title ? $title->getPrefixedDBkey() : false;
  1125. $this->titleCache = $parent->titleCache;
  1126. $this->titleCache[] = $pdbk;
  1127. $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
  1128. if ( $pdbk !== false ) {
  1129. $this->loopCheckHash[$pdbk] = true;
  1130. }
  1131. $this->depth = $parent->depth + 1;
  1132. $this->numberedExpansionCache = $this->namedExpansionCache = array();
  1133. }
  1134. function __toString() {
  1135. $s = 'tplframe{';
  1136. $first = true;
  1137. $args = $this->numberedArgs + $this->namedArgs;
  1138. foreach ( $args as $name => $value ) {
  1139. if ( $first ) {
  1140. $first = false;
  1141. } else {
  1142. $s .= ', ';
  1143. }
  1144. $s .= "\"$name\":\"" .
  1145. str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
  1146. }
  1147. $s .= '}';
  1148. return $s;
  1149. }
  1150. /**
  1151. * Returns true if there are no arguments in this frame
  1152. */
  1153. function isEmpty() {
  1154. return !count( $this->numberedArgs ) && !count( $this->namedArgs );
  1155. }
  1156. function getArguments() {
  1157. $arguments = array();
  1158. foreach ( array_merge(
  1159. array_keys($this->numberedArgs),
  1160. array_keys($this->namedArgs)) as $key ) {
  1161. $arguments[$key] = $this->getArgument($key);
  1162. }
  1163. return $arguments;
  1164. }
  1165. function getNumberedArguments() {
  1166. $arguments = array();
  1167. foreach ( array_keys($this->numberedArgs) as $key ) {
  1168. $arguments[$key] = $this->getArgument($key);
  1169. }
  1170. return $arguments;
  1171. }
  1172. function getNamedArguments() {
  1173. $arguments = array();
  1174. foreach ( array_keys($this->namedArgs) as $key ) {
  1175. $arguments[$key] = $this->getArgument($key);
  1176. }
  1177. return $arguments;
  1178. }
  1179. function getNumberedArgument( $index ) {
  1180. if ( !isset( $this->numberedArgs[$index] ) ) {
  1181. return false;
  1182. }
  1183. if ( !isset( $this->numberedExpansionCache[$index] ) ) {
  1184. # No trimming for unnamed arguments
  1185. $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], self::STRIP_COMMENTS );
  1186. }
  1187. return $this->numberedExpansionCache[$index];
  1188. }
  1189. function getNamedArgument( $name ) {
  1190. if ( !isset( $this->namedArgs[$name] ) ) {
  1191. return false;
  1192. }
  1193. if ( !isset( $this->namedExpansionCache[$name] ) ) {
  1194. # Trim named arguments post-expand, for backwards compatibility
  1195. $this->namedExpansionCache[$name] = trim(
  1196. $this->parent->expand( $this->namedArgs[$name], self::STRIP_COMMENTS ) );
  1197. }
  1198. return $this->namedExpansionCache[$name];
  1199. }
  1200. function getArgument( $name ) {
  1201. $text = $this->getNumberedArgument( $name );
  1202. if ( $text === false ) {
  1203. $text = $this->getNamedArgument( $name );
  1204. }
  1205. return $text;
  1206. }
  1207. /**
  1208. * Return true if the frame is a template frame
  1209. */
  1210. function isTemplate() {
  1211. return true;
  1212. }
  1213. }
  1214. /**
  1215. * Expansion frame with custom arguments
  1216. * @ingroup Parser
  1217. */
  1218. class PPCustomFrame_DOM extends PPFrame_DOM {
  1219. var $args;
  1220. function __construct( $preprocessor, $args ) {
  1221. $this->preprocessor = $preprocessor;
  1222. $this->parser = $preprocessor->parser;
  1223. $this->args = $args;
  1224. }
  1225. function __toString() {
  1226. $s = 'cstmframe{';
  1227. $first = true;
  1228. foreach ( $this->args as $name => $value ) {
  1229. if ( $first ) {
  1230. $first = false;
  1231. } else {
  1232. $s .= ', ';
  1233. }
  1234. $s .= "\"$name\":\"" .
  1235. str_replace( '"', '\\"', $value->__toString() ) . '"';
  1236. }
  1237. $s .= '}';
  1238. return $s;
  1239. }
  1240. function isEmpty() {
  1241. return !count( $this->args );
  1242. }
  1243. function getArgument( $index ) {
  1244. if ( !isset( $this->args[$index] ) ) {
  1245. return false;
  1246. }
  1247. return $this->args[$index];
  1248. }
  1249. }
  1250. /**
  1251. * @ingroup Parser
  1252. */
  1253. class PPNode_DOM implements PPNode {
  1254. var $node;
  1255. function __construct( $node, $xpath = false ) {
  1256. $this->node = $node;
  1257. }
  1258. function __get( $name ) {
  1259. if ( $name == 'xpath' ) {
  1260. $this->xpath = new DOMXPath( $this->node->ownerDocument );
  1261. }
  1262. return $this->xpath;
  1263. }
  1264. function __toString() {
  1265. if ( $this->node instanceof DOMNodeList ) {
  1266. $s = '';
  1267. foreach ( $this->node as $node ) {
  1268. $s .= $node->ownerDocument->saveXML( $node );
  1269. }
  1270. } else {
  1271. $s = $this->node->ownerDocument->saveXML( $this->node );
  1272. }
  1273. return $s;
  1274. }
  1275. function getChildren() {
  1276. return $this->node->childNodes ? new self( $this->node->childNodes ) : false;
  1277. }
  1278. function getFirstChild() {
  1279. return $this->node->firstChild ? new self( $this->node->firstChild ) : false;
  1280. }
  1281. function getNextSibling() {
  1282. return $this->node->nextSibling ? new self( $this->node->nextSibling ) : false;
  1283. }
  1284. function getChildrenOfType( $type ) {
  1285. return new self( $this->xpath->query( $type, $this->node ) );
  1286. }
  1287. function getLength() {
  1288. if ( $this->node instanceof DOMNodeList ) {
  1289. return $this->node->length;
  1290. } else {
  1291. return false;
  1292. }
  1293. }
  1294. function item( $i ) {
  1295. $item = $this->node->item( $i );
  1296. return $item ? new self( $item ) : false;
  1297. }
  1298. function getName() {
  1299. if ( $this->node instanceof DOMNodeList ) {
  1300. return '#nodelist';
  1301. } else {
  1302. return $this->node->nodeName;
  1303. }
  1304. }
  1305. /**
  1306. * Split a <part> node into an associative array containing:
  1307. * name PPNode name
  1308. * index String index
  1309. * value PPNode value
  1310. */
  1311. function splitArg() {
  1312. $names = $this->xpath->query( 'name', $this->node );
  1313. $values = $this->xpath->query( 'value', $this->node );
  1314. if ( !$names->length || !$values->length ) {
  1315. throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
  1316. }
  1317. $name = $names->item( 0 );
  1318. $index = $name->getAttribute( 'index' );
  1319. return array(
  1320. 'name' => new self( $name ),
  1321. 'index' => $index,
  1322. 'value' => new self( $values->item( 0 ) ) );
  1323. }
  1324. /**
  1325. * Split an <ext> node into an associative array containing name, attr, inner and close
  1326. * All values in the resulting array are PPNodes. Inner and close are optional.
  1327. */
  1328. function splitExt() {
  1329. $names = $this->xpath->query( 'name', $this->node );
  1330. $attrs = $this->xpath->query( 'attr', $this->node );
  1331. $inners = $this->xpath->query( 'inner', $this->node );
  1332. $closes = $this->xpath->query( 'close', $this->node );
  1333. if ( !$names->length || !$attrs->length ) {
  1334. throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
  1335. }
  1336. $parts = array(
  1337. 'name' => new self( $names->item( 0 ) ),
  1338. 'attr' => new self( $attrs->item( 0 ) ) );
  1339. if ( $inners->length ) {
  1340. $parts['inner'] = new self( $inners->item( 0 ) );
  1341. }
  1342. if ( $closes->length ) {
  1343. $parts['close'] = new self( $closes->item( 0 ) );
  1344. }
  1345. return $parts;
  1346. }
  1347. /**
  1348. * Split a <h> node
  1349. */
  1350. function splitHeading() {
  1351. if ( !$this->nodeName == 'h' ) {
  1352. throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
  1353. }
  1354. return array(
  1355. 'i' => $this->node->getAttribute( 'i' ),
  1356. 'level' => $this->node->getAttribute( 'level' ),
  1357. 'contents' => $this->getChildren()
  1358. );
  1359. }
  1360. }