Debian Codegraph @

includes/CommentFormatter/CommentParser.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\CommentFormatter;
4
5 use File;
6 use HtmlArmor;
7 use MediaWiki\Cache\LinkBatch;
8 use MediaWiki\Cache\LinkBatchFactory;
9 use MediaWiki\Cache\LinkCache;
10 use MediaWiki\HookContainer\HookContainer;
11 use MediaWiki\HookContainer\HookRunner;
12 use MediaWiki\Html\Html;
13 use MediaWiki\Language\Language;
14 use MediaWiki\Linker\Linker;
15 use MediaWiki\Linker\LinkRenderer;
16 use MediaWiki\Linker\LinkTarget;
17 use MediaWiki\Parser\Parser;
18 use MediaWiki\Parser\Sanitizer;
19 use MediaWiki\SpecialPage\SpecialPage;
20 use MediaWiki\Title\MalformedTitleException;
21 use MediaWiki\Title\NamespaceInfo;
22 use MediaWiki\Title\Title;
23 use MediaWiki\Title\TitleParser;
24 use MediaWiki\Title\TitleValue;
25 use MediaWiki\WikiMap\WikiMap;
26 use RepoGroup;
27 use StringUtils;
28
29 /**
30 * The text processing backend for CommentFormatter.
31 *
32 * CommentParser objects should be discarded after the comment batch is
33 * complete, in order to reduce memory usage.
34 *
35 * @internal
36 */
37 class CommentParser {
38 /** @var LinkRenderer */
39 private $linkRenderer;
40 /** @var LinkBatchFactory */
41 private $linkBatchFactory;
42 /** @var RepoGroup */
43 private $repoGroup;
44 /** @var Language */
45 private $userLang;
46 /** @var Language */
47 private $contLang;
48 /** @var TitleParser */
49 private $titleParser;
50 /** @var NamespaceInfo */
51 private $namespaceInfo;
52 /** @var HookRunner */
53 private $hookRunner;
54 /** @var LinkCache */
55 private $linkCache;
56
57 /** @var callable[] */
58 private $links = [];
59 /** @var LinkBatch|null */
60 private $linkBatch;
61
62 /** @var array Input to RepoGroup::findFiles() */
63 private $fileBatch;
64 /** @var File[] Resolved File objects indexed by DB key */
65 private $files = [];
66
67 /** @var int The maximum number of digits in a marker ID */
68 private const MAX_ID_SIZE = 7;
69 /** @var string Prefix for marker. ' and " included to break attributes (T355538) */
70 private const MARKER_PREFIX = "\x1B\"'";
71
72 /**
73 * @param LinkRenderer $linkRenderer
74 * @param LinkBatchFactory $linkBatchFactory
75 * @param LinkCache $linkCache
76 * @param RepoGroup $repoGroup
77 * @param Language $userLang
78 * @param Language $contLang
79 * @param TitleParser $titleParser
80 * @param NamespaceInfo $namespaceInfo
81 * @param HookContainer $hookContainer
82 */
83 public function __construct(
84 LinkRenderer $linkRenderer,
85 LinkBatchFactory $linkBatchFactory,
86 LinkCache $linkCache,
87 RepoGroup $repoGroup,
88 Language $userLang,
89 Language $contLang,
90 TitleParser $titleParser,
91 NamespaceInfo $namespaceInfo,
92 HookContainer $hookContainer
93 ) {
94 $this->linkRenderer = $linkRenderer;
95 $this->linkBatchFactory = $linkBatchFactory;
96 $this->linkCache = $linkCache;
97 $this->repoGroup = $repoGroup;
98 $this->userLang = $userLang;
99 $this->contLang = $contLang;
100 $this->titleParser = $titleParser;
101 $this->namespaceInfo = $namespaceInfo;
102 $this->hookRunner = new HookRunner( $hookContainer );
103 }
104
105 /**
106 * Convert a comment to HTML, but replace links with markers which are
107 * resolved later.
108 *
109 * @param string $comment
110 * @param LinkTarget|null $selfLinkTarget
111 * @param bool $samePage
112 * @param string|false|null $wikiId
113 * @param bool $enableSectionLinks
114 * @return string
115 */
116 public function preprocess( string $comment, ?LinkTarget $selfLinkTarget = null,
117 $samePage = false, $wikiId = false, $enableSectionLinks = true
118 ) {
119 return $this->preprocessInternal( $comment, false, $selfLinkTarget,
120 $samePage, $wikiId, $enableSectionLinks );
121 }
122
123 /**
124 * Convert a comment in pseudo-HTML format to HTML, replacing links with markers.
125 *
126 * @param string $comment
127 * @param LinkTarget|null $selfLinkTarget
128 * @param bool $samePage
129 * @param string|false|null $wikiId
130 * @param bool $enableSectionLinks
131 * @return string
132 */
133 public function preprocessUnsafe( $comment, ?LinkTarget $selfLinkTarget = null,
134 $samePage = false, $wikiId = false, $enableSectionLinks = true
135 ) {
136 return $this->preprocessInternal( $comment, true, $selfLinkTarget,
137 $samePage, $wikiId, $enableSectionLinks );
138 }
139
140 /**
141 * Execute pending batch queries and replace markers in the specified
142 * string(s) with actual links.
143 *
144 * @param string|string[] $comments
145 * @return string|string[]
146 */
147 public function finalize( $comments ) {
148 $this->flushLinkBatches();
149 return preg_replace_callback(
150 '/' . self::MARKER_PREFIX . '([0-9]{' . self::MAX_ID_SIZE . '})/',
151 function ( $m ) {
152 $callback = $this->links[(int)$m[1]] ?? null;
153 if ( $callback ) {
154 return $callback();
155 } else {
156 return '<!-- MISSING -->';
157 }
158 },
159 $comments
160 );
161 }
162
163 /**
164 * @param string $comment
165 * @param bool $unsafe
166 * @param LinkTarget|null $selfLinkTarget
167 * @param bool $samePage
168 * @param string|false|null $wikiId
169 * @param bool $enableSectionLinks
170 * @return string
171 */
172 private function preprocessInternal( $comment, $unsafe, $selfLinkTarget, $samePage, $wikiId,
173 $enableSectionLinks
174 ) {
175 // Sanitize text a bit
176 // \x1b needs to be stripped because it is used for link markers
177 $comment = strtr( $comment, "\n\x1b", " " );
178 // Allow HTML entities (for T15815)
179 if ( !$unsafe ) {
180 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
181 }
182 if ( $enableSectionLinks ) {
183 $comment = $this->doSectionLinks( $comment, $selfLinkTarget, $samePage, $wikiId );
184 }
185 return $this->doWikiLinks( $comment, $selfLinkTarget, $samePage, $wikiId );
186 }
187
188 /**
189 * Converts C-style comments in edit summaries into section links.
190 *
191 * Too many things are called "comments", so these are mostly now called
192 * section links rather than autocomments.
193 *
194 * We look for all comments, match any text before and after the comment,
195 * add a separator where needed and format the comment itself with CSS.
196 *
197 * @param string $comment Comment text
198 * @param LinkTarget|null $selfLinkTarget An optional LinkTarget object used to links to sections
199 * @param bool $samePage Whether section links should refer to local page
200 * @param string|false|null $wikiId Id of the wiki to link to (if not the local wiki),
201 * as used by WikiMap.
202 * @return string Preprocessed comment
203 */
204 private function doSectionLinks(
205 $comment,
206 $selfLinkTarget = null,
207 $samePage = false,
208 $wikiId = false
209 ) {
210 $comment = preg_replace_callback(
211 // To detect the presence of content before or after the
212 // auto-comment, we use capturing groups inside optional zero-width
213 // assertions. But older versions of PCRE can't directly make
214 // zero-width assertions optional, so wrap them in a non-capturing
215 // group.
216 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
217 function ( $match ) use ( $selfLinkTarget, $samePage, $wikiId ) {
218 // Ensure all match positions are defined
219 $match += [ '', '', '', '' ];
220
221 $pre = $match[1] !== '';
222 $auto = $match[2];
223 $post = $match[3] !== '';
224 $comment = null;
225
226 $this->hookRunner->onFormatAutocomments(
227 $comment, $pre, $auto, $post,
228 Title::castFromLinkTarget( $selfLinkTarget ),
229 $samePage,
230 $wikiId );
231 if ( $comment !== null ) {
232 return $comment;
233 }
234
235 if ( $selfLinkTarget ) {
236 $section = $auto;
237 # Remove links that a user may have manually put in the autosummary
238 # This could be improved by copying as much of Parser::stripSectionName as desired.
239 $section = str_replace( [
240 '[[:',
241 '[[',
242 ']]'
243 ], '', $section );
244
245 $section = substr( Parser::guessSectionNameFromStrippedText( $section ), 1 );
246 if ( $section !== '' ) {
247 if ( $samePage ) {
248 $sectionTitle = new TitleValue( NS_MAIN, '', $section );
249 } else {
250 $sectionTitle = $selfLinkTarget->createFragmentTarget( $section );
251 }
252 $auto = $this->makeSectionLink(
253 $sectionTitle,
254 $this->userLang->getArrow() .
255 Html::rawElement( 'bdi', [ 'dir' => $this->userLang->getDir() ], $auto ),
256 $wikiId,
257 $selfLinkTarget
258 );
259 }
260 }
261 if ( $pre ) {
262 # written summary $presep autocomment (summary /* section */)
263 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
264 }
265 if ( $post ) {
266 # autocomment $postsep written summary (/* section */ summary)
267 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
268 }
269 if ( $auto ) {
270 $auto = Html::rawElement( 'span', [ 'class' => 'autocomment' ], $auto );
271 }
272
273 // Make sure any brackets (which the user could have input in the edit summary)
274 // in the generated autocomment HTML don't trigger additional link processing (T406664).
275 return str_replace( [ '[', ']' ], [ '&#91;', '&#93;' ], $pre . $auto );
276 },
277 $comment
278 );
279 return $comment;
280 }
281
282 /**
283 * Make a section link. These don't need to go into the LinkBatch, since
284 * the link class does not depend on whether the link is known.
285 *
286 * @param LinkTarget $target
287 * @param string $text
288 * @param string|false|null $wikiId Id of the wiki to link to (if not the local wiki),
289 * as used by WikiMap.
290 * @param LinkTarget $contextTitle
291 *
292 * @return string HTML link
293 */
294 private function makeSectionLink(
295 LinkTarget $target, $text, $wikiId, LinkTarget $contextTitle
296 ) {
297 if ( $wikiId !== null && $wikiId !== false && !$target->isExternal() ) {
298 return $this->linkRenderer->makeExternalLink(
299 WikiMap::getForeignURL(
300 $wikiId,
301 $target->getNamespace() === 0
302 ? $target->getDBkey()
303 : $this->namespaceInfo->getCanonicalName( $target->getNamespace() ) .
304 ':' . $target->getDBkey(),
305 $target->getFragment()
306 ),
307 new HtmlArmor( $text ), // Already escaped
308 $contextTitle
309 );
310 }
311 return $this->linkRenderer->makePreloadedLink( $target, new HtmlArmor( $text ), '' );
312 }
313
314 /**
315 * Formats wiki links and media links in text; all other wiki formatting
316 * is ignored
317 *
318 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
319 *
320 * @param string $comment Text to format links in. WARNING! Since the output of this
321 * function is html, $comment must be sanitized for use as html. You probably want
322 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
323 * this function.
324 * as used by WikiMap.
325 * @param LinkTarget|null $selfLinkTarget An optional LinkTarget object used to links to sections
326 * @param bool $samePage Whether section links should refer to local page
327 * @param string|false|null $wikiId Id of the wiki to link to (if not the local wiki),
328 * as used by WikiMap.
329 *
330 * @return string HTML
331 */
332 private function doWikiLinks( $comment, $selfLinkTarget = null, $samePage = false, $wikiId = false ) {
333 return preg_replace_callback(
334 '/
335 \[\[
336 \s*+ # ignore leading whitespace, the *+ quantifier disallows backtracking
337 :? # ignore optional leading colon
338 ([^[\]|]+) # 1. link target; page names cannot include [, ] or |
339 (?:\|
340 # 2. link text
341 # Stop matching at ]] without relying on backtracking.
342 ((?:]?[^\]])*+)
343 )?
344 \]\]
345 ([^[]*) # 3. link trail (the text up until the next link)
346 /x',
347 function ( $match ) use ( $selfLinkTarget, $samePage, $wikiId ) {
348 $medians = '(?:';
349 $medians .= preg_quote(
350 $this->namespaceInfo->getCanonicalName( NS_MEDIA ), '/' );
351 $medians .= '|';
352 $medians .= preg_quote(
353 $this->contLang->getNsText( NS_MEDIA ),
354 '/'
355 ) . '):';
356
357 $comment = $match[0];
358
359 // Fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
360 if ( strpos( $match[1], '%' ) !== false ) {
361 $match[1] = strtr(
362 rawurldecode( $match[1] ),
363 [ '<' => '&lt;', '>' => '&gt;' ]
364 );
365 }
366
367 // Handle link renaming [[foo|text]] will show link as "text"
368 if ( $match[2] != "" ) {
369 $text = $match[2];
370 } else {
371 $text = $match[1];
372 }
373 $submatch = [];
374 $linkMarker = null;
375 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
376 // Media link; trail not supported.
377 $linkRegexp = '/\[\[(.*?)\]\]/';
378 $linkTarget = $this->titleParser->makeTitleValueSafe( NS_FILE, $submatch[1] );
379 if ( $linkTarget ) {
380 $linkMarker = $this->addFileLink( $linkTarget, $text );
381 }
382 } else {
383 // Other kind of link
384 // Make sure its target is non-empty
385 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
386 $match[1] = substr( $match[1], 1 );
387 }
388 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
389 if ( $match[1] !== false && $match[1] !== null && $match[1] !== '' ) {
390 if ( preg_match(
391 $this->contLang->linkTrail(),
392 $match[3],
393 $submatch
394 ) ) {
395 $trail = $submatch[1];
396 } else {
397 $trail = "";
398 }
399 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
400 [ $inside, $trail ] = Linker::splitTrail( $trail );
401
402 $linkText = $text;
403 $linkTarget = Linker::normalizeSubpageLink( $selfLinkTarget, $match[1], $linkText );
404
405 try {
406 $target = $this->titleParser->parseTitle( $linkTarget );
407
408 if ( $target->getText() == '' && !$target->isExternal()
409 && !$samePage && $selfLinkTarget
410 ) {
411 $target = $selfLinkTarget->createFragmentTarget( $target->getFragment() );
412 }
413
414 // We should deprecate `null` as a valid value for
415 // $selfLinkTarget to ensure that we can use it as
416 // the title context for the external link.
417 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
418 global $wgTitle;
419 $linkMarker = $this->addPageLink(
420 $target,
421 $linkText . $inside,
422 $wikiId,
423 $selfLinkTarget ?? $wgTitle ?? SpecialPage::getTitleFor( 'Badtitle' )
424 );
425 $linkMarker .= $trail;
426 } catch ( MalformedTitleException $e ) {
427 // Fall through
428 }
429 }
430 }
431 if ( $linkMarker ) {
432 // If the link is still valid, go ahead and replace it in!
433 $comment = preg_replace(
434 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable linkRegexp set when used
435 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal linkRegexp set when used
436 $linkRegexp,
437 StringUtils::escapeRegexReplacement( $linkMarker ),
438 $comment,
439 1
440 );
441 }
442
443 return $comment;
444 },
445 $comment
446 );
447 }
448
449 /**
450 * Add a deferred link to the list and return its marker.
451 *
452 * @param callable $callback
453 * @return string
454 */
455 private function addLinkMarker( $callback ) {
456 $nextId = count( $this->links );
457 if ( strlen( (string)$nextId ) > self::MAX_ID_SIZE ) {
458 throw new \RuntimeException( 'Too many links in comment batch' );
459 }
460 $this->links[] = $callback;
461 return sprintf( self::MARKER_PREFIX . "%0" . self::MAX_ID_SIZE . 'd', $nextId );
462 }
463
464 /**
465 * Link to a LinkTarget. Return either HTML or a marker depending on whether
466 * existence checks are deferred.
467 *
468 * @param LinkTarget $target
469 * @param string $text
470 * @param string|false|null $wikiId
471 * @param LinkTarget $contextTitle
472 * @return string
473 */
474 private function addPageLink( LinkTarget $target, $text, $wikiId, LinkTarget $contextTitle ) {
475 if ( $wikiId !== null && $wikiId !== false && !$target->isExternal() ) {
476 // Handle links from a foreign wiki ID
477 return $this->linkRenderer->makeExternalLink(
478 WikiMap::getForeignURL(
479 $wikiId,
480 $target->getNamespace() === 0
481 ? $target->getDBkey()
482 : $this->namespaceInfo->getCanonicalName( $target->getNamespace() ) .
483 ':' . $target->getDBkey(),
484 $target->getFragment()
485 ),
486 new HtmlArmor( $text ), // Already escaped
487 $contextTitle
488 );
489 } elseif ( $this->linkCache->getGoodLinkID( $target ) ||
490 Title::newFromLinkTarget( $target )->isAlwaysKnown()
491 ) {
492 // Already known
493 return $this->linkRenderer->makeKnownLink( $target, new HtmlArmor( $text ) );
494 } elseif ( $this->linkCache->isBadLink( $target ) ) {
495 // Already cached as unknown
496 return $this->linkRenderer->makeBrokenLink( $target, new HtmlArmor( $text ) );
497 }
498
499 // Defer page link
500 if ( !$this->linkBatch ) {
501 $this->linkBatch = $this->linkBatchFactory->newLinkBatch();
502 $this->linkBatch->setCaller( __METHOD__ );
503 }
504 $this->linkBatch->addObj( $target );
505 return $this->addLinkMarker( function () use ( $target, $text ) {
506 return $this->linkRenderer->makeLink( $target, new HtmlArmor( $text ) );
507 } );
508 }
509
510 /**
511 * Link to a file, returning a marker.
512 *
513 * @param LinkTarget $target The name of the file.
514 * @param string $html The inner HTML of the link
515 * @return string
516 */
517 private function addFileLink( LinkTarget $target, $html ) {
518 $this->fileBatch[] = [
519 'title' => $target
520 ];
521 return $this->addLinkMarker( function () use ( $target, $html ) {
522 return Linker::makeMediaLinkFile(
523 $target,
524 $this->files[$target->getDBkey()] ?? false,
525 $html
526 );
527 } );
528 }
529
530 /**
531 * Execute any pending link batch or file batch
532 */
533 private function flushLinkBatches() {
534 if ( $this->linkBatch ) {
535 $this->linkBatch->execute();
536 $this->linkBatch = null;
537 }
538 if ( $this->fileBatch ) {
539 $this->files += $this->repoGroup->findFiles( $this->fileBatch );
540 $this->fileBatch = [];
541 }
542 }
543
544 }