MediaWiki  master
PPFrame_DOM.php
Go to the documentation of this file.
1 <?php
27 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
28 class PPFrame_DOM implements PPFrame {
29 
33  public $preprocessor;
34 
38  public $parser;
39 
43  public $title;
44  public $titleCache;
45 
51 
56  public $depth;
57 
58  private $volatile = false;
59  private $ttl = null;
60 
65 
70  public function __construct( $preprocessor ) {
71  $this->preprocessor = $preprocessor;
72  $this->parser = $preprocessor->parser;
73  $this->title = $this->parser->mTitle;
74  $this->titleCache = [ $this->title ? $this->title->getPrefixedDBkey() : false ];
75  $this->loopCheckHash = [];
76  $this->depth = 0;
77  $this->childExpansionCache = [];
78  }
79 
89  public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
90  $namedArgs = [];
91  $numberedArgs = [];
92  if ( $title === false ) {
94  }
95  if ( $args !== false ) {
96  $xpath = false;
97  if ( $args instanceof PPNode ) {
98  $args = $args->node;
99  }
100  foreach ( $args as $arg ) {
101  if ( $arg instanceof PPNode ) {
102  $arg = $arg->node;
103  }
104  if ( !$xpath || $xpath->document !== $arg->ownerDocument ) {
105  $xpath = new DOMXPath( $arg->ownerDocument );
106  }
107 
108  $nameNodes = $xpath->query( 'name', $arg );
109  $value = $xpath->query( 'value', $arg );
110  if ( $nameNodes->item( 0 )->hasAttributes() ) {
111  // Numbered parameter
112  $index = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
113  $index = $index - $indexOffset;
114  if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
115  $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
116  wfEscapeWikiText( $this->title ),
118  wfEscapeWikiText( $index ) )->text() );
119  $this->parser->addTrackingCategory( 'duplicate-args-category' );
120  }
121  $numberedArgs[$index] = $value->item( 0 );
122  unset( $namedArgs[$index] );
123  } else {
124  // Named parameter
125  $name = trim( $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS ) );
126  if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
127  $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
128  wfEscapeWikiText( $this->title ),
130  wfEscapeWikiText( $name ) )->text() );
131  $this->parser->addTrackingCategory( 'duplicate-args-category' );
132  }
133  $namedArgs[$name] = $value->item( 0 );
134  unset( $numberedArgs[$name] );
135  }
136  }
137  }
138  return new PPTemplateFrame_DOM( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
139  }
140 
148  public function cachedExpand( $key, $root, $flags = 0 ) {
149  // we don't have a parent, so we don't have a cache
150  return $this->expand( $root, $flags );
151  }
152 
159  public function expand( $root, $flags = 0 ) {
160  static $expansionDepth = 0;
161  if ( is_string( $root ) ) {
162  return $root;
163  }
164 
165  if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
166  $this->parser->limitationWarn( 'node-count-exceeded',
167  $this->parser->mPPNodeCount,
168  $this->parser->mOptions->getMaxPPNodeCount()
169  );
170  return '<span class="error">Node-count limit exceeded</span>';
171  }
172 
173  if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
174  $this->parser->limitationWarn( 'expansion-depth-exceeded',
175  $expansionDepth,
176  $this->parser->mOptions->getMaxPPExpandDepth()
177  );
178  return '<span class="error">Expansion depth limit exceeded</span>';
179  }
180  ++$expansionDepth;
181  if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
182  $this->parser->mHighestExpansionDepth = $expansionDepth;
183  }
184 
185  if ( $root instanceof PPNode_DOM ) {
186  $root = $root->node;
187  }
188  if ( $root instanceof DOMDocument ) {
189  $root = $root->documentElement;
190  }
191 
192  $outStack = [ '', '' ];
193  $iteratorStack = [ false, $root ];
194  $indexStack = [ 0, 0 ];
195 
196  while ( count( $iteratorStack ) > 1 ) {
197  $level = count( $outStack ) - 1;
198  $iteratorNode =& $iteratorStack[$level];
199  $out =& $outStack[$level];
200  $index =& $indexStack[$level];
201 
202  if ( $iteratorNode instanceof PPNode_DOM ) {
203  $iteratorNode = $iteratorNode->node;
204  }
205 
206  if ( is_array( $iteratorNode ) ) {
207  if ( $index >= count( $iteratorNode ) ) {
208  // All done with this iterator
209  $iteratorStack[$level] = false;
210  $contextNode = false;
211  } else {
212  $contextNode = $iteratorNode[$index];
213  $index++;
214  }
215  } elseif ( $iteratorNode instanceof DOMNodeList ) {
216  if ( $index >= $iteratorNode->length ) {
217  // All done with this iterator
218  $iteratorStack[$level] = false;
219  $contextNode = false;
220  } else {
221  $contextNode = $iteratorNode->item( $index );
222  $index++;
223  }
224  } else {
225  // Copy to $contextNode and then delete from iterator stack,
226  // because this is not an iterator but we do have to execute it once
227  $contextNode = $iteratorStack[$level];
228  $iteratorStack[$level] = false;
229  }
230 
231  if ( $contextNode instanceof PPNode_DOM ) {
232  $contextNode = $contextNode->node;
233  }
234 
235  $newIterator = false;
236 
237  if ( $contextNode === false ) {
238  // nothing to do
239  } elseif ( is_string( $contextNode ) ) {
240  $out .= $contextNode;
241  } elseif ( is_array( $contextNode ) || $contextNode instanceof DOMNodeList ) {
242  $newIterator = $contextNode;
243  } elseif ( $contextNode instanceof DOMNode ) {
244  if ( $contextNode->nodeType == XML_TEXT_NODE ) {
245  $out .= $contextNode->nodeValue;
246  } elseif ( $contextNode->nodeName == 'template' ) {
247  # Double-brace expansion
248  $xpath = new DOMXPath( $contextNode->ownerDocument );
249  $titles = $xpath->query( 'title', $contextNode );
250  $title = $titles->item( 0 );
251  $parts = $xpath->query( 'part', $contextNode );
252  if ( $flags & PPFrame::NO_TEMPLATES ) {
253  $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $title, $parts );
254  } else {
255  $lineStart = $contextNode->getAttribute( 'lineStart' );
256  $params = [
257  'title' => new PPNode_DOM( $title ),
258  'parts' => new PPNode_DOM( $parts ),
259  'lineStart' => $lineStart ];
260  $ret = $this->parser->braceSubstitution( $params, $this );
261  if ( isset( $ret['object'] ) ) {
262  $newIterator = $ret['object'];
263  } else {
264  $out .= $ret['text'];
265  }
266  }
267  } elseif ( $contextNode->nodeName == 'tplarg' ) {
268  # Triple-brace expansion
269  $xpath = new DOMXPath( $contextNode->ownerDocument );
270  $titles = $xpath->query( 'title', $contextNode );
271  $title = $titles->item( 0 );
272  $parts = $xpath->query( 'part', $contextNode );
273  if ( $flags & PPFrame::NO_ARGS ) {
274  $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $title, $parts );
275  } else {
276  $params = [
277  'title' => new PPNode_DOM( $title ),
278  'parts' => new PPNode_DOM( $parts ) ];
279  $ret = $this->parser->argSubstitution( $params, $this );
280  if ( isset( $ret['object'] ) ) {
281  $newIterator = $ret['object'];
282  } else {
283  $out .= $ret['text'];
284  }
285  }
286  } elseif ( $contextNode->nodeName == 'comment' ) {
287  # HTML-style comment
288  # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
289  # Not in RECOVER_COMMENTS mode (msgnw) though.
290  if ( ( $this->parser->ot['html']
291  || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
292  || ( $flags & PPFrame::STRIP_COMMENTS )
293  ) && !( $flags & PPFrame::RECOVER_COMMENTS )
294  ) {
295  $out .= '';
296  } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
297  # Add a strip marker in PST mode so that pstPass2() can
298  # run some old-fashioned regexes on the result.
299  # Not in RECOVER_COMMENTS mode (extractSections) though.
300  $out .= $this->parser->insertStripItem( $contextNode->textContent );
301  } else {
302  # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
303  $out .= $contextNode->textContent;
304  }
305  } elseif ( $contextNode->nodeName == 'ignore' ) {
306  # Output suppression used by <includeonly> etc.
307  # OT_WIKI will only respect <ignore> in substed templates.
308  # The other output types respect it unless NO_IGNORE is set.
309  # extractSections() sets NO_IGNORE and so never respects it.
310  if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
311  || ( $flags & PPFrame::NO_IGNORE )
312  ) {
313  $out .= $contextNode->textContent;
314  } else {
315  $out .= '';
316  }
317  } elseif ( $contextNode->nodeName == 'ext' ) {
318  # Extension tag
319  $xpath = new DOMXPath( $contextNode->ownerDocument );
320  $names = $xpath->query( 'name', $contextNode );
321  $attrs = $xpath->query( 'attr', $contextNode );
322  $inners = $xpath->query( 'inner', $contextNode );
323  $closes = $xpath->query( 'close', $contextNode );
324  if ( $flags & PPFrame::NO_TAGS ) {
325  $s = '<' . $this->expand( $names->item( 0 ), $flags );
326  if ( $attrs->length > 0 ) {
327  $s .= $this->expand( $attrs->item( 0 ), $flags );
328  }
329  if ( $inners->length > 0 ) {
330  $s .= '>' . $this->expand( $inners->item( 0 ), $flags );
331  if ( $closes->length > 0 ) {
332  $s .= $this->expand( $closes->item( 0 ), $flags );
333  }
334  } else {
335  $s .= '/>';
336  }
337  $out .= $s;
338  } else {
339  $params = [
340  'name' => new PPNode_DOM( $names->item( 0 ) ),
341  'attr' => $attrs->length > 0 ? new PPNode_DOM( $attrs->item( 0 ) ) : null,
342  'inner' => $inners->length > 0 ? new PPNode_DOM( $inners->item( 0 ) ) : null,
343  'close' => $closes->length > 0 ? new PPNode_DOM( $closes->item( 0 ) ) : null,
344  ];
345  $out .= $this->parser->extensionSubstitution( $params, $this );
346  }
347  } elseif ( $contextNode->nodeName == 'h' ) {
348  # Heading
349  $s = $this->expand( $contextNode->childNodes, $flags );
350 
351  # Insert a heading marker only for <h> children of <root>
352  # This is to stop extractSections from going over multiple tree levels
353  if ( $contextNode->parentNode->nodeName == 'root' && $this->parser->ot['html'] ) {
354  # Insert heading index marker
355  $headingIndex = $contextNode->getAttribute( 'i' );
356  $titleText = $this->title->getPrefixedDBkey();
357  $this->parser->mHeadings[] = [ $titleText, $headingIndex ];
358  $serial = count( $this->parser->mHeadings ) - 1;
359  $marker = Parser::MARKER_PREFIX . "-h-$serial-" . Parser::MARKER_SUFFIX;
360  $count = $contextNode->getAttribute( 'level' );
361  $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
362  $this->parser->mStripState->addGeneral( $marker, '' );
363  }
364  $out .= $s;
365  } else {
366  # Generic recursive expansion
367  $newIterator = $contextNode->childNodes;
368  }
369  } else {
370  throw new MWException( __METHOD__ . ': Invalid parameter type' );
371  }
372 
373  if ( $newIterator !== false ) {
374  if ( $newIterator instanceof PPNode_DOM ) {
375  $newIterator = $newIterator->node;
376  }
377  $outStack[] = '';
378  $iteratorStack[] = $newIterator;
379  $indexStack[] = 0;
380  } elseif ( $iteratorStack[$level] === false ) {
381  // Return accumulated value to parent
382  // With tail recursion
383  while ( $iteratorStack[$level] === false && $level > 0 ) {
384  $outStack[$level - 1] .= $out;
385  array_pop( $outStack );
386  array_pop( $iteratorStack );
387  array_pop( $indexStack );
388  $level--;
389  }
390  }
391  }
392  --$expansionDepth;
393  return $outStack[0];
394  }
395 
402  public function implodeWithFlags( $sep, $flags, ...$args ) {
403  $first = true;
404  $s = '';
405  foreach ( $args as $root ) {
406  if ( $root instanceof PPNode_DOM ) {
407  $root = $root->node;
408  }
409  if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
410  $root = [ $root ];
411  }
412  foreach ( $root as $node ) {
413  if ( $first ) {
414  $first = false;
415  } else {
416  $s .= $sep;
417  }
418  $s .= $this->expand( $node, $flags );
419  }
420  }
421  return $s;
422  }
423 
432  public function implode( $sep, ...$args ) {
433  $first = true;
434  $s = '';
435  foreach ( $args as $root ) {
436  if ( $root instanceof PPNode_DOM ) {
437  $root = $root->node;
438  }
439  if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
440  $root = [ $root ];
441  }
442  foreach ( $root as $node ) {
443  if ( $first ) {
444  $first = false;
445  } else {
446  $s .= $sep;
447  }
448  $s .= $this->expand( $node );
449  }
450  }
451  return $s;
452  }
453 
462  public function virtualImplode( $sep, ...$args ) {
463  $out = [];
464  $first = true;
465 
466  foreach ( $args as $root ) {
467  if ( $root instanceof PPNode_DOM ) {
468  $root = $root->node;
469  }
470  if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
471  $root = [ $root ];
472  }
473  foreach ( $root as $node ) {
474  if ( $first ) {
475  $first = false;
476  } else {
477  $out[] = $sep;
478  }
479  $out[] = $node;
480  }
481  }
482  return $out;
483  }
484 
493  public function virtualBracketedImplode( $start, $sep, $end, ...$args ) {
494  $out = [ $start ];
495  $first = true;
496 
497  foreach ( $args as $root ) {
498  if ( $root instanceof PPNode_DOM ) {
499  $root = $root->node;
500  }
501  if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
502  $root = [ $root ];
503  }
504  foreach ( $root as $node ) {
505  if ( $first ) {
506  $first = false;
507  } else {
508  $out[] = $sep;
509  }
510  $out[] = $node;
511  }
512  }
513  $out[] = $end;
514  return $out;
515  }
516 
517  public function __toString() {
518  return 'frame{}';
519  }
520 
521  public function getPDBK( $level = false ) {
522  if ( $level === false ) {
523  return $this->title->getPrefixedDBkey();
524  } else {
525  return $this->titleCache[$level] ?? false;
526  }
527  }
528 
532  public function getArguments() {
533  return [];
534  }
535 
539  public function getNumberedArguments() {
540  return [];
541  }
542 
546  public function getNamedArguments() {
547  return [];
548  }
549 
555  public function isEmpty() {
556  return true;
557  }
558 
563  public function getArgument( $name ) {
564  return false;
565  }
566 
573  public function loopCheck( $title ) {
574  return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
575  }
576 
582  public function isTemplate() {
583  return false;
584  }
585 
591  public function getTitle() {
592  return $this->title;
593  }
594 
600  public function setVolatile( $flag = true ) {
601  $this->volatile = $flag;
602  }
603 
609  public function isVolatile() {
610  return $this->volatile;
611  }
612 
618  public function setTTL( $ttl ) {
619  if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
620  $this->ttl = $ttl;
621  }
622  }
623 
629  public function getTTL() {
630  return $this->ttl;
631  }
632 }
const MARKER_PREFIX
Definition: Parser.php:136
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
getTTL()
Get the TTL.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1971
getNumberedArguments()
getArgument( $name)
Expansion frame with template arguments.
There are three types of nodes:
Definition: PPNode.php:35
$value
virtualBracketedImplode( $start, $sep, $end,... $args)
Virtual implode with brackets.
getTitle()
Get a title of frame.
const RECOVER_COMMENTS
Definition: PPFrame.php:30
expand( $root, $flags=0)
title
const NO_ARGS
Definition: PPFrame.php:26
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
cachedExpand( $key, $root, $flags=0)
const NO_IGNORE
Definition: PPFrame.php:29
isTemplate()
Return true if the frame is a template frame.
if( $line===false) $args
Definition: cdb.php:64
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:767
const NO_TEMPLATES
Definition: PPFrame.php:27
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
newChild( $args=false, $title=false, $indexOffset=0)
Create a new child frame $args is optionally a multi-root PPNode or array containing the template arg...
Definition: PPFrame_DOM.php:89
Title $title
Definition: PPFrame_DOM.php:43
implode( $sep,... $args)
Implode with no flags specified This previously called implodeWithFlags but has now been inlined to r...
$params
implodeWithFlags( $sep, $flags,... $args)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
setVolatile( $flag=true)
Set the volatile flag.
loopCheck( $title)
Returns true if the infinite loop check is OK, false if a loop is detected.
Preprocessor $preprocessor
Definition: PPFrame_DOM.php:33
setTTL( $ttl)
Set the TTL.
An expansion frame, used as a context to expand the result of preprocessToObj()
Definition: PPFrame_DOM.php:28
getPDBK( $level=false)
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$loopCheckHash
Hashtable listing templates which are disallowed for expansion in this frame, having been encountered...
Definition: PPFrame_DOM.php:50
__construct( $preprocessor)
Construct a new preprocessor frame.
Definition: PPFrame_DOM.php:70
virtualImplode( $sep,... $args)
Makes an object that, when expand()ed, will be the same as one obtained with implode() ...
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
const NO_TAGS
Definition: PPFrame.php:31
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition: linkcache.txt:17
isVolatile()
Get the volatile flag.
Parser $parser
Definition: PPFrame_DOM.php:38
array $childExpansionCache
Definition: PPFrame_DOM.php:64
$depth
Recursion depth of this frame, top = 0 Note that this is NOT the same as expansion depth in expand() ...
Definition: PPFrame_DOM.php:56
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
isEmpty()
Returns true if there are no arguments in this frame.
const STRIP_COMMENTS
Definition: PPFrame.php:28
getPrefixedDBkey()
Get the prefixed database key form.
Definition: Title.php:1710