MediaWiki master
PPFrame_Hash.php
Go to the documentation of this file.
1<?php
7
8namespace MediaWiki\Parser;
9
10use InvalidArgumentException;
11use MediaWiki\Message\Message;
12use MediaWiki\Parser\Parsoid\Config\DataAccess;
13use MediaWiki\Title\Title;
14use RuntimeException;
15use Stringable;
16use Wikimedia\Parsoid\Fragments\HeadingPFragment;
17
22// phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
23class PPFrame_Hash implements Stringable, PPFrame {
24
28 public $parser;
29
34
38 public $title;
39
44
51
57 public $depth;
58
60 private $volatile = false;
62 private $ttl = null;
63
71 private $maxPPNodeCount;
75 private $maxPPExpandDepth;
76
80 public function __construct( $preprocessor ) {
81 $this->preprocessor = $preprocessor;
82 $this->parser = $preprocessor->parser;
83 $this->title = $this->parser->getTitle();
84 $this->maxPPNodeCount = $this->parser->getOptions()->getMaxPPNodeCount();
85 $this->maxPPExpandDepth = $this->parser->getOptions()->getMaxPPExpandDepth();
86 $this->titleCache = [ $this->title ? $this->title->getPrefixedDBkey() : false ];
87 $this->loopCheckHash = [];
88 $this->depth = 0;
89 $this->childExpansionCache = [];
90 }
91
101 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
102 $namedArgs = [];
103 $numberedArgs = [];
104 if ( $title === false ) {
106 }
107 if ( $args !== false ) {
108 if ( $args instanceof PPNode_Hash_Array ) {
109 $args = $args->value;
110 } elseif ( !is_array( $args ) ) {
111 throw new InvalidArgumentException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
112 }
113 foreach ( $args as $arg ) {
114 $bits = $arg->splitArg();
115 if ( $bits['index'] !== '' ) {
116 // Numbered parameter
117 $index = $bits['index'] - $indexOffset;
118 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
119 $this->parser->getOutput()->addWarningMsg(
120 'duplicate-args-warning',
121 wfEscapeWikiText( (string)$this->title ),
122 wfEscapeWikiText( (string)$title ),
123 Message::numParam( $index )
124 );
125 $this->parser->addTrackingCategory( 'duplicate-args-category' );
126 }
127 $numberedArgs[$index] = $bits['value'];
128 unset( $namedArgs[$index] );
129 } else {
130 // Named parameter
131 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
132 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
133 $this->parser->getOutput()->addWarningMsg(
134 'duplicate-args-warning',
135 wfEscapeWikiText( (string)$this->title ),
136 wfEscapeWikiText( (string)$title ),
137 // @phan-suppress-next-line SecurityCheck-DoubleEscaped
138 wfEscapeWikiText( $name )
139 );
140 $this->parser->addTrackingCategory( 'duplicate-args-category' );
141 }
142 $namedArgs[$name] = $bits['value'];
143 unset( $numberedArgs[$name] );
144 }
145 }
146 }
147 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
148 }
149
156 public function cachedExpand( $key, $root, $flags = 0 ) {
157 // we don't have a parent, so we don't have a cache
158 return $this->expand( $root, $flags );
159 }
160
166 public function expand( $root, $flags = 0 ) {
167 static $expansionDepth = 0;
168 if ( is_string( $root ) ) {
169 return $root;
170 }
171
172 if ( ++$this->parser->mPPNodeCount > $this->maxPPNodeCount ) {
173 $this->parser->limitationWarn( 'node-count-exceeded',
174 $this->parser->mPPNodeCount,
175 $this->maxPPNodeCount
176 );
177 return '<span class="error">Node-count limit exceeded</span>';
178 }
179 if ( $expansionDepth > $this->maxPPExpandDepth ) {
180 $this->parser->limitationWarn( 'expansion-depth-exceeded',
181 $expansionDepth,
182 $this->maxPPExpandDepth
183 );
184 return '<span class="error">Expansion depth limit exceeded</span>';
185 }
186 ++$expansionDepth;
187 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
188 $this->parser->mHighestExpansionDepth = $expansionDepth;
189 }
190
191 $outStack = [ '', '' ];
192 $iteratorStack = [ false, $root ];
193 $indexStack = [ 0, 0 ];
194
195 while ( count( $iteratorStack ) > 1 ) {
196 $level = count( $outStack ) - 1;
197 $iteratorNode =& $iteratorStack[$level];
198 $out =& $outStack[$level];
199 $index =& $indexStack[$level];
200
201 if ( is_array( $iteratorNode ) ) {
202 if ( $index >= count( $iteratorNode ) ) {
203 // All done with this iterator
204 $iteratorStack[$level] = false;
205 $contextNode = false;
206 } else {
207 $contextNode = $iteratorNode[$index];
208 $index++;
209 }
210 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
211 if ( $index >= $iteratorNode->getLength() ) {
212 // All done with this iterator
213 $iteratorStack[$level] = false;
214 $contextNode = false;
215 } else {
216 $contextNode = $iteratorNode->item( $index );
217 $index++;
218 }
219 } else {
220 // Copy to $contextNode and then delete from iterator stack,
221 // because this is not an iterator but we do have to execute it once
222 $contextNode = $iteratorStack[$level];
223 $iteratorStack[$level] = false;
224 }
225
226 $newIterator = false;
227 $contextName = false;
228 $contextChildren = false;
229
230 if ( $contextNode === false ) {
231 // nothing to do
232 } elseif ( is_string( $contextNode ) ) {
233 $out .= $contextNode;
234 } elseif ( $contextNode instanceof PPNode_Hash_Array ) {
235 $newIterator = $contextNode;
236 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
237 // No output
238 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
239 $out .= $contextNode->value;
240 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
241 $contextName = $contextNode->name;
242 $contextChildren = $contextNode->getRawChildren();
243 } elseif ( is_array( $contextNode ) ) {
244 // Node descriptor array
245 if ( count( $contextNode ) !== 2 ) {
246 throw new RuntimeException( __METHOD__ .
247 ': found an array where a node descriptor should be' );
248 }
249 [ $contextName, $contextChildren ] = $contextNode;
250 } else {
251 throw new RuntimeException( __METHOD__ . ': Invalid parameter type' );
252 }
253
254 // Handle node descriptor array or tree object
255 if ( $contextName === false ) {
256 // Not a node, already handled above
257 } elseif ( $contextName[0] === '@' ) {
258 // Attribute: no output
259 } elseif ( $contextName === 'template' ) {
260 # Double-brace expansion
261 $bits = PPNode_Hash_Tree::splitRawTemplate( $contextChildren );
262 if ( $flags & PPFrame::NO_TEMPLATES ) {
263 $newIterator = $this->virtualBracketedImplode(
264 '{{', '|', '}}',
265 $bits['title'],
266 $bits['parts']
267 );
268 } else {
269 $ret = $this->parser->braceSubstitution( $bits, $this );
270 if ( isset( $ret['object'] ) ) {
271 $newIterator = $ret['object'];
272 } else {
273 $out .= $ret['text'];
274 }
275 }
276 } elseif ( $contextName === 'tplarg' ) {
277 # Triple-brace expansion
278 $bits = PPNode_Hash_Tree::splitRawTemplate( $contextChildren );
279 if ( $flags & PPFrame::NO_ARGS ) {
280 $newIterator = $this->virtualBracketedImplode(
281 '{{{', '|', '}}}',
282 $bits['title'],
283 $bits['parts']
284 );
285 } else {
286 $ret = $this->parser->argSubstitution( $bits, $this );
287 if ( isset( $ret['object'] ) ) {
288 $newIterator = $ret['object'];
289 } else {
290 $out .= $ret['text'];
291 }
292 }
293 } elseif ( $contextName === 'comment' ) {
294 # HTML-style comment
295 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
296 # Not in RECOVER_COMMENTS mode (msgnw) though.
297 if ( ( $this->parser->getOutputType() === Parser::OT_HTML
298 || ( $this->parser->getOutputType() === Parser::OT_PREPROCESS &&
299 $this->parser->getOptions()->getRemoveComments() )
300 || ( $flags & PPFrame::STRIP_COMMENTS )
301 ) && !( $flags & PPFrame::RECOVER_COMMENTS )
302 ) {
303 $out .= '';
304 } elseif (
305 $this->parser->getOutputType() === Parser::OT_WIKI &&
306 !( $flags & PPFrame::RECOVER_COMMENTS )
307 ) {
308 # Add a strip marker in PST mode so that pstPass2() can
309 # run some old-fashioned regexes on the result.
310 # Not in RECOVER_COMMENTS mode (extractSections) though.
311 $out .= $this->parser->insertStripItem( $contextChildren[0] );
312 } else {
313 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
314 $out .= $contextChildren[0];
315 }
316 } elseif ( $contextName === 'ignore' ) {
317 # Output suppression used by <includeonly> etc.
318 # OT_WIKI will only respect <ignore> in substed templates.
319 # The other output types respect it unless NO_IGNORE is set.
320 # extractSections() sets NO_IGNORE and so never respects it.
321 if ( ( !isset( $this->parent ) && $this->parser->getOutputType() === Parser::OT_WIKI )
322 || ( $flags & PPFrame::NO_IGNORE )
323 ) {
324 $out .= $contextChildren[0];
325 } else {
326 // $out .= '';
327 }
328 } elseif ( $contextName === 'ext' ) {
329 # Extension tag
330 $bits = PPNode_Hash_Tree::splitRawExt( $contextChildren ) +
331 [ 'attr' => null, 'inner' => null, 'close' => null ];
332 if ( $flags & PPFrame::NO_TAGS ) {
333 $s = '<' . $bits['name']->getFirstChild()->value;
334 if ( $bits['attr'] ) {
335 $s .= $bits['attr']->getFirstChild()->value;
336 }
337 if ( $bits['inner'] ) {
338 $s .= '>' . $bits['inner']->getFirstChild()->value;
339 if ( $bits['close'] ) {
340 $s .= $bits['close']->getFirstChild()->value;
341 }
342 } else {
343 $s .= '/>';
344 }
345 $out .= $s;
346 } else {
347 $out .= $this->parser->extensionSubstitution( $bits, $this );
348 }
349 } elseif ( $contextName === 'h' ) {
350 # Heading
351 if ( $this->parser->getOutputType() === Parser::OT_HTML ) {
352 # Expand immediately and insert heading index marker
353 $s = $this->expand( $contextChildren, $flags );
354 $bits = PPNode_Hash_Tree::splitRawHeading( $contextChildren );
355 $titleText = $this->title->getPrefixedDBkey();
356 $this->parser->mHeadings[] = [ $titleText, $bits['i'] ];
357 $serial = count( $this->parser->mHeadings ) - 1;
358 $marker = Parser::MARKER_PREFIX . "-h-$serial-" . Parser::MARKER_SUFFIX;
359 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
360 $this->parser->getStripState()->addGeneral( $marker, '' );
361 $out .= $s;
362 } elseif (
363 $this->parser->useParsoidFragments() &&
364 $this->parser->getOutputType() === Parser::OT_PREPROCESS
365 ) {
366 $s = $this->expand( $contextChildren, $flags );
367 $fragment = DataAccess::unstripForParsoid( $s, $this->parser );
368 $bits = PPNode_Hash_Tree::splitRawHeading( $contextChildren );
369 $pFragment = new HeadingPFragment( $fragment, $this->title, $bits['i'] );
370
371 // Just generate a unique marker
372 $this->parser->mHeadings[] = [];
373 $serial = count( $this->parser->mHeadings ) - 1;
374 $marker = Parser::MARKER_PREFIX . "-h-$serial-" . Parser::MARKER_SUFFIX;
375
376 $this->parser->getStripState()->addParsoidOpaque( $marker, $pFragment );
377 $out .= $marker;
378 } else {
379 # Expand in virtual stack
380 $newIterator = $contextChildren;
381 }
382 } else {
383 # Generic recursive expansion
384 $newIterator = $contextChildren;
385 }
386
387 if ( $newIterator !== false ) {
388 $outStack[] = '';
389 $iteratorStack[] = $newIterator;
390 $indexStack[] = 0;
391 } elseif ( $iteratorStack[$level] === false ) {
392 // Return accumulated value to parent
393 // With tail recursion
394 while ( $iteratorStack[$level] === false && $level > 0 ) {
395 $outStack[$level - 1] .= $out;
396 array_pop( $outStack );
397 array_pop( $iteratorStack );
398 array_pop( $indexStack );
399 $level--;
400 }
401 }
402 }
403 --$expansionDepth;
404 return $outStack[0];
405 }
406
413 public function implodeWithFlags( $sep, $flags, ...$args ) {
414 $first = true;
415 $s = '';
416 foreach ( $args as $root ) {
417 if ( $root instanceof PPNode_Hash_Array ) {
418 $root = $root->value;
419 }
420 if ( !is_array( $root ) ) {
421 $root = [ $root ];
422 }
423 foreach ( $root as $node ) {
424 if ( $first ) {
425 $first = false;
426 } else {
427 $s .= $sep;
428 }
429 $s .= $this->expand( $node, $flags );
430 }
431 }
432 return $s;
433 }
434
442 public function implode( $sep, ...$args ) {
443 $first = true;
444 $s = '';
445 foreach ( $args as $root ) {
446 if ( $root instanceof PPNode_Hash_Array ) {
447 $root = $root->value;
448 }
449 if ( !is_array( $root ) ) {
450 $root = [ $root ];
451 }
452 foreach ( $root as $node ) {
453 if ( $first ) {
454 $first = false;
455 } else {
456 $s .= $sep;
457 }
458 $s .= $this->expand( $node );
459 }
460 }
461 return $s;
462 }
463
472 public function virtualImplode( $sep, ...$args ) {
473 $out = [];
474 $first = true;
475
476 foreach ( $args as $root ) {
477 if ( $root instanceof PPNode_Hash_Array ) {
478 $root = $root->value;
479 }
480 if ( !is_array( $root ) ) {
481 $root = [ $root ];
482 }
483 foreach ( $root as $node ) {
484 if ( $first ) {
485 $first = false;
486 } else {
487 $out[] = $sep;
488 }
489 $out[] = $node;
490 }
491 }
492 return new PPNode_Hash_Array( $out );
493 }
494
504 public function virtualBracketedImplode( $start, $sep, $end, ...$args ) {
505 $out = [ $start ];
506 $first = true;
507
508 foreach ( $args as $root ) {
509 if ( $root instanceof PPNode_Hash_Array ) {
510 $root = $root->value;
511 }
512 if ( !is_array( $root ) ) {
513 $root = [ $root ];
514 }
515 foreach ( $root as $node ) {
516 if ( $first ) {
517 $first = false;
518 } else {
519 $out[] = $sep;
520 }
521 $out[] = $node;
522 }
523 }
524 $out[] = $end;
525 return new PPNode_Hash_Array( $out );
526 }
527
528 public function __toString() {
529 return 'frame{}';
530 }
531
536 public function getPDBK( $level = false ) {
537 if ( $level === false ) {
538 return $this->title->getPrefixedDBkey();
539 } else {
540 return $this->titleCache[$level] ?? false;
541 }
542 }
543
547 public function getArguments() {
548 return [];
549 }
550
554 public function getNumberedArguments() {
555 return [];
556 }
557
561 public function getNamedArguments() {
562 return [];
563 }
564
570 public function isEmpty() {
571 return true;
572 }
573
578 public function getArgument( $name ) {
579 return false;
580 }
581
589 public function loopCheck( $title ) {
590 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
591 }
592
598 public function isTemplate() {
599 return false;
600 }
601
607 public function getTitle() {
608 return $this->title;
609 }
610
616 public function setVolatile( $flag = true ) {
617 $this->volatile = $flag;
618 }
619
625 public function isVolatile() {
626 return $this->volatile;
627 }
628
633 public function setTTL( $ttl ) {
634 wfDeprecated( __METHOD__, '1.44' );
635 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
636 $this->ttl = $ttl;
637 }
638 }
639
644 public function getTTL() {
645 wfDeprecated( __METHOD__, '1.46' );
646 return $this->ttl;
647 }
648}
649
651class_alias( PPFrame_Hash::class, 'PPFrame_Hash' );
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
An expansion frame, used as a context to expand the result of preprocessToObj().
implodeWithFlags( $sep, $flags,... $args)
setVolatile( $flag=true)
Set the volatile flag.
loopCheck( $title)
Returns true if the infinite loop check is OK, false if a loop is detected.
int $depth
Recursion depth of this frame, top = 0 Note that this is NOT the same as expansion depth in expand().
true[] $loopCheckHash
Hashtable listing templates which are disallowed for expansion in this frame, having been encountered...
isEmpty()
Returns true if there are no arguments in this frame.
cachedExpand( $key, $root, $flags=0)
virtualImplode( $sep,... $args)
Makes an object that, when expand()ed, will be the same as one obtained with implode().
implode( $sep,... $args)
Implode with no flags specified This previously called implodeWithFlags but has now been inlined to r...
getTitle()
Get a title of frame.
isTemplate()
Return true if the frame is a template frame.
isVolatile()
Get the volatile flag.
virtualBracketedImplode( $start, $sep, $end,... $args)
Virtual implode with brackets.
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...
static splitRawHeading(array $children)
Like splitHeading() but for a raw child array.
static splitRawExt(array $children)
Like splitExt() but for a raw child array.
static splitRawTemplate(array $children)
Like splitTemplate() but for a raw child array.
Expansion frame with template arguments.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:139
const OT_PREPROCESS
Output type: like Parser\preprocess().
Definition Parser.php:181
const OT_WIKI
Output type: like Parser\preSaveTransform().
Definition Parser.php:179
const OT_HTML
Output type: like Parser\parse().
Definition Parser.php:177
static unstripForParsoid(string $wikitext, Parser $parser)
Where the result has strip state markers, tunnel this content through Parsoid as a PFragment type.
Represents a title within MediaWiki.
Definition Title.php:69
getPrefixedDBkey()
Get the prefixed database key form.
Definition Title.php:1802