Pass $parser, &$query and &$widthOption to the 'ImageBeforeProduceHTML' hook
[lhc/web/wiklou.git] / includes / Linker.php
1 <?php
2 /**
3 * Methods to make links and related items.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22 use MediaWiki\Linker\LinkTarget;
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Some internal bits split of from Skin.php. These functions are used
27 * for primarily page content: links, embedded images, table of contents. Links
28 * are also used in the skin.
29 *
30 * @todo turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
31 *
32 * @ingroup Skins
33 */
34 class Linker {
35 /**
36 * Flags for userToolLinks()
37 */
38 const TOOL_LINKS_NOBLOCK = 1;
39 const TOOL_LINKS_EMAIL = 2;
40
41 /**
42 * Return the CSS colour of a known link
43 *
44 * @deprecated since 1.28, use LinkRenderer::getLinkClasses() instead
45 *
46 * @since 1.16.3
47 * @param LinkTarget $t
48 * @param int $threshold User defined threshold
49 * @return string CSS class
50 */
51 public static function getLinkColour( LinkTarget $t, $threshold ) {
52 wfDeprecated( __METHOD__, '1.28' );
53 $services = MediaWikiServices::getInstance();
54 $linkRenderer = $services->getLinkRenderer();
55 if ( $threshold !== $linkRenderer->getStubThreshold() ) {
56 // Need to create a new instance with the right stub threshold...
57 $linkRenderer = $services->getLinkRendererFactory()->create();
58 $linkRenderer->setStubThreshold( $threshold );
59 }
60
61 return $linkRenderer->getLinkClasses( $t );
62 }
63
64 /**
65 * This function returns an HTML link to the given target. It serves a few
66 * purposes:
67 * 1) If $target is a Title, the correct URL to link to will be figured
68 * out automatically.
69 * 2) It automatically adds the usual classes for various types of link
70 * targets: "new" for red links, "stub" for short articles, etc.
71 * 3) It escapes all attribute values safely so there's no risk of XSS.
72 * 4) It provides a default tooltip if the target is a Title (the page
73 * name of the target).
74 * link() replaces the old functions in the makeLink() family.
75 *
76 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
77 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
78 *
79 * @param LinkTarget $target Can currently only be a LinkTarget, but this may
80 * change to support Images, literal URLs, etc.
81 * @param string $html The HTML contents of the <a> element, i.e.,
82 * the link text. This is raw HTML and will not be escaped. If null,
83 * defaults to the prefixed text of the Title; or if the Title is just a
84 * fragment, the contents of the fragment.
85 * @param array $customAttribs A key => value array of extra HTML attributes,
86 * such as title and class. (href is ignored.) Classes will be
87 * merged with the default classes, while other attributes will replace
88 * default attributes. All passed attribute values will be HTML-escaped.
89 * A false attribute value means to suppress that attribute.
90 * @param array $query The query string to append to the URL
91 * you're linking to, in key => value array form. Query keys and values
92 * will be URL-encoded.
93 * @param string|array $options String or array of strings:
94 * 'known': Page is known to exist, so don't check if it does.
95 * 'broken': Page is known not to exist, so don't check if it does.
96 * 'noclasses': Don't add any classes automatically (includes "new",
97 * "stub", "mw-redirect", "extiw"). Only use the class attribute
98 * provided, if any, so you get a simple blue link with no funny i-
99 * cons.
100 * 'forcearticlepath': Use the article path always, even with a querystring.
101 * Has compatibility issues on some setups, so avoid wherever possible.
102 * 'http': Force a full URL with http:// as the scheme.
103 * 'https': Force a full URL with https:// as the scheme.
104 * 'stubThreshold' => (int): Stub threshold to use when determining link classes.
105 * @return string HTML <a> attribute
106 */
107 public static function link(
108 $target, $html = null, $customAttribs = [], $query = [], $options = []
109 ) {
110 if ( !$target instanceof LinkTarget ) {
111 wfWarn( __METHOD__ . ': Requires $target to be a LinkTarget object.', 2 );
112 return "<!-- ERROR -->$html";
113 }
114
115 if ( is_string( $query ) ) {
116 // some functions withing core using this still hand over query strings
117 wfDeprecated( __METHOD__ . ' with parameter $query as string (should be array)', '1.20' );
118 $query = wfCgiToArray( $query );
119 }
120
121 $services = MediaWikiServices::getInstance();
122 $options = (array)$options;
123 if ( $options ) {
124 // Custom options, create new LinkRenderer
125 if ( !isset( $options['stubThreshold'] ) ) {
126 $defaultLinkRenderer = $services->getLinkRenderer();
127 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
128 }
129 $linkRenderer = $services->getLinkRendererFactory()
130 ->createFromLegacyOptions( $options );
131 } else {
132 $linkRenderer = $services->getLinkRenderer();
133 }
134
135 if ( $html !== null ) {
136 $text = new HtmlArmor( $html );
137 } else {
138 $text = $html; // null
139 }
140 if ( in_array( 'known', $options, true ) ) {
141 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
142 } elseif ( in_array( 'broken', $options, true ) ) {
143 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
144 } elseif ( in_array( 'noclasses', $options, true ) ) {
145 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
146 } else {
147 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
148 }
149 }
150
151 /**
152 * Identical to link(), except $options defaults to 'known'.
153 *
154 * @since 1.16.3
155 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
156 * @see Linker::link
157 * @param Title $target
158 * @param string $html
159 * @param array $customAttribs
160 * @param array $query
161 * @param string|array $options
162 * @return string
163 */
164 public static function linkKnown(
165 $target, $html = null, $customAttribs = [],
166 $query = [], $options = [ 'known' ]
167 ) {
168 return self::link( $target, $html, $customAttribs, $query, $options );
169 }
170
171 /**
172 * Make appropriate markup for a link to the current article. This is since
173 * MediaWiki 1.29.0 rendered as an <a> tag without an href and with a class
174 * showing the link text. The calling sequence is the same as for the other
175 * make*LinkObj static functions, but $query is not used.
176 *
177 * @since 1.16.3
178 * @param Title $nt
179 * @param string $html [optional]
180 * @param string $query [optional]
181 * @param string $trail [optional]
182 * @param string $prefix [optional]
183 *
184 * @return string
185 */
186 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
187 $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
188 if ( !Hooks::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
189 return $ret;
190 }
191
192 if ( $html == '' ) {
193 $html = htmlspecialchars( $nt->getPrefixedText() );
194 }
195 list( $inside, $trail ) = self::splitTrail( $trail );
196 return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
197 }
198
199 /**
200 * Get a message saying that an invalid title was encountered.
201 * This should be called after a method like Title::makeTitleSafe() returned
202 * a value indicating that the title object is invalid.
203 *
204 * @param IContextSource $context Context to use to get the messages
205 * @param int $namespace Namespace number
206 * @param string $title Text of the title, without the namespace part
207 * @return string
208 */
209 public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
210 global $wgContLang;
211
212 // First we check whether the namespace exists or not.
213 if ( MWNamespace::exists( $namespace ) ) {
214 if ( $namespace == NS_MAIN ) {
215 $name = $context->msg( 'blanknamespace' )->text();
216 } else {
217 $name = $wgContLang->getFormattedNsText( $namespace );
218 }
219 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
220 } else {
221 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
222 }
223 }
224
225 /**
226 * @since 1.16.3
227 * @param LinkTarget $target
228 * @return LinkTarget
229 */
230 public static function normaliseSpecialPage( LinkTarget $target ) {
231 if ( $target->getNamespace() == NS_SPECIAL && !$target->isExternal() ) {
232 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $target->getDBkey() );
233 if ( !$name ) {
234 return $target;
235 }
236 $ret = SpecialPage::getTitleValueFor( $name, $subpage, $target->getFragment() );
237 return $ret;
238 } else {
239 return $target;
240 }
241 }
242
243 /**
244 * Returns the filename part of an url.
245 * Used as alternative text for external images.
246 *
247 * @param string $url
248 *
249 * @return string
250 */
251 private static function fnamePart( $url ) {
252 $basename = strrchr( $url, '/' );
253 if ( false === $basename ) {
254 $basename = $url;
255 } else {
256 $basename = substr( $basename, 1 );
257 }
258 return $basename;
259 }
260
261 /**
262 * Return the code for images which were added via external links,
263 * via Parser::maybeMakeExternalImage().
264 *
265 * @since 1.16.3
266 * @param string $url
267 * @param string $alt
268 *
269 * @return string
270 */
271 public static function makeExternalImage( $url, $alt = '' ) {
272 if ( $alt == '' ) {
273 $alt = self::fnamePart( $url );
274 }
275 $img = '';
276 $success = Hooks::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
277 if ( !$success ) {
278 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
279 . "with url {$url} and alt text {$alt} to {$img}\n", true );
280 return $img;
281 }
282 return Html::element( 'img',
283 [
284 'src' => $url,
285 'alt' => $alt ] );
286 }
287
288 /**
289 * Given parameters derived from [[Image:Foo|options...]], generate the
290 * HTML that that syntax inserts in the page.
291 *
292 * @param Parser $parser
293 * @param Title $title Title object of the file (not the currently viewed page)
294 * @param File $file File object, or false if it doesn't exist
295 * @param array $frameParams Associative array of parameters external to the media handler.
296 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
297 * will often be false.
298 * thumbnail If present, downscale and frame
299 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
300 * framed Shows image in original size in a frame
301 * frameless Downscale but don't frame
302 * upright If present, tweak default sizes for portrait orientation
303 * upright_factor Fudge factor for "upright" tweak (default 0.75)
304 * border If present, show a border around the image
305 * align Horizontal alignment (left, right, center, none)
306 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
307 * bottom, text-bottom)
308 * alt Alternate text for image (i.e. alt attribute). Plain text.
309 * class HTML for image classes. Plain text.
310 * caption HTML for image caption.
311 * link-url URL to link to
312 * link-title Title object to link to
313 * link-target Value for the target attribute, only with link-url
314 * no-link Boolean, suppress description link
315 *
316 * @param array $handlerParams Associative array of media handler parameters, to be passed
317 * to transform(). Typical keys are "width" and "page".
318 * @param string|bool $time Timestamp of the file, set as false for current
319 * @param string $query Query params for desc url
320 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
321 * @since 1.20
322 * @return string HTML for an image, with links, wrappers, etc.
323 */
324 public static function makeImageLink( Parser $parser, Title $title,
325 $file, $frameParams = [], $handlerParams = [], $time = false,
326 $query = "", $widthOption = null
327 ) {
328 $res = null;
329 $dummy = new DummyLinker;
330 if ( !Hooks::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
331 &$file, &$frameParams, &$handlerParams, &$time, &$res,
332 $parser, &$query, &$widthOption
333 ] ) ) {
334 return $res;
335 }
336
337 if ( $file && !$file->allowInlineDisplay() ) {
338 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
339 return self::link( $title );
340 }
341
342 // Clean up parameters
343 $page = $handlerParams['page'] ?? false;
344 if ( !isset( $frameParams['align'] ) ) {
345 $frameParams['align'] = '';
346 }
347 if ( !isset( $frameParams['alt'] ) ) {
348 $frameParams['alt'] = '';
349 }
350 if ( !isset( $frameParams['title'] ) ) {
351 $frameParams['title'] = '';
352 }
353 if ( !isset( $frameParams['class'] ) ) {
354 $frameParams['class'] = '';
355 }
356
357 $prefix = $postfix = '';
358
359 if ( 'center' == $frameParams['align'] ) {
360 $prefix = '<div class="center">';
361 $postfix = '</div>';
362 $frameParams['align'] = 'none';
363 }
364 if ( $file && !isset( $handlerParams['width'] ) ) {
365 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
366 // If its a vector image, and user only specifies height
367 // we don't want it to be limited by its "normal" width.
368 global $wgSVGMaxSize;
369 $handlerParams['width'] = $wgSVGMaxSize;
370 } else {
371 $handlerParams['width'] = $file->getWidth( $page );
372 }
373
374 if ( isset( $frameParams['thumbnail'] )
375 || isset( $frameParams['manualthumb'] )
376 || isset( $frameParams['framed'] )
377 || isset( $frameParams['frameless'] )
378 || !$handlerParams['width']
379 ) {
380 global $wgThumbLimits, $wgThumbUpright;
381
382 if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
383 $widthOption = User::getDefaultOption( 'thumbsize' );
384 }
385
386 // Reduce width for upright images when parameter 'upright' is used
387 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
388 $frameParams['upright'] = $wgThumbUpright;
389 }
390
391 // For caching health: If width scaled down due to upright
392 // parameter, round to full __0 pixel to avoid the creation of a
393 // lot of odd thumbs.
394 $prefWidth = isset( $frameParams['upright'] ) ?
395 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
396 $wgThumbLimits[$widthOption];
397
398 // Use width which is smaller: real image width or user preference width
399 // Unless image is scalable vector.
400 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
401 $prefWidth < $handlerParams['width'] || $file->isVectorized() ) ) {
402 $handlerParams['width'] = $prefWidth;
403 }
404 }
405 }
406
407 if ( isset( $frameParams['thumbnail'] ) || isset( $frameParams['manualthumb'] )
408 || isset( $frameParams['framed'] )
409 ) {
410 # Create a thumbnail. Alignment depends on the writing direction of
411 # the page content language (right-aligned for LTR languages,
412 # left-aligned for RTL languages)
413 # If a thumbnail width has not been provided, it is set
414 # to the default user option as specified in Language*.php
415 if ( $frameParams['align'] == '' ) {
416 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
417 }
418 return $prefix .
419 self::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
420 $postfix;
421 }
422
423 if ( $file && isset( $frameParams['frameless'] ) ) {
424 $srcWidth = $file->getWidth( $page );
425 # For "frameless" option: do not present an image bigger than the
426 # source (for bitmap-style images). This is the same behavior as the
427 # "thumb" option does it already.
428 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
429 $handlerParams['width'] = $srcWidth;
430 }
431 }
432
433 if ( $file && isset( $handlerParams['width'] ) ) {
434 # Create a resized image, without the additional thumbnail features
435 $thumb = $file->transform( $handlerParams );
436 } else {
437 $thumb = false;
438 }
439
440 if ( !$thumb ) {
441 $s = self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
442 } else {
443 self::processResponsiveImages( $file, $thumb, $handlerParams );
444 $params = [
445 'alt' => $frameParams['alt'],
446 'title' => $frameParams['title'],
447 'valign' => $frameParams['valign'] ?? false,
448 'img-class' => $frameParams['class'] ];
449 if ( isset( $frameParams['border'] ) ) {
450 $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
451 }
452 $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
453
454 $s = $thumb->toHtml( $params );
455 }
456 if ( $frameParams['align'] != '' ) {
457 $s = "<div class=\"float{$frameParams['align']}\">{$s}</div>";
458 }
459 return str_replace( "\n", ' ', $prefix . $s . $postfix );
460 }
461
462 /**
463 * Get the link parameters for MediaTransformOutput::toHtml() from given
464 * frame parameters supplied by the Parser.
465 * @param array $frameParams The frame parameters
466 * @param string $query An optional query string to add to description page links
467 * @param Parser|null $parser
468 * @return array
469 */
470 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
471 $mtoParams = [];
472 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
473 $mtoParams['custom-url-link'] = $frameParams['link-url'];
474 if ( isset( $frameParams['link-target'] ) ) {
475 $mtoParams['custom-target-link'] = $frameParams['link-target'];
476 }
477 if ( $parser ) {
478 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
479 foreach ( $extLinkAttrs as $name => $val ) {
480 // Currently could include 'rel' and 'target'
481 $mtoParams['parser-extlink-' . $name] = $val;
482 }
483 }
484 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
485 $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
486 self::normaliseSpecialPage( $frameParams['link-title'] )
487 );
488 } elseif ( !empty( $frameParams['no-link'] ) ) {
489 // No link
490 } else {
491 $mtoParams['desc-link'] = true;
492 $mtoParams['desc-query'] = $query;
493 }
494 return $mtoParams;
495 }
496
497 /**
498 * Make HTML for a thumbnail including image, border and caption
499 * @param Title $title
500 * @param File|bool $file File object or false if it doesn't exist
501 * @param string $label
502 * @param string $alt
503 * @param string $align
504 * @param array $params
505 * @param bool $framed
506 * @param string $manualthumb
507 * @return string
508 */
509 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt = '',
510 $align = 'right', $params = [], $framed = false, $manualthumb = ""
511 ) {
512 $frameParams = [
513 'alt' => $alt,
514 'caption' => $label,
515 'align' => $align
516 ];
517 if ( $framed ) {
518 $frameParams['framed'] = true;
519 }
520 if ( $manualthumb ) {
521 $frameParams['manualthumb'] = $manualthumb;
522 }
523 return self::makeThumbLink2( $title, $file, $frameParams, $params );
524 }
525
526 /**
527 * @param Title $title
528 * @param File $file
529 * @param array $frameParams
530 * @param array $handlerParams
531 * @param bool $time
532 * @param string $query
533 * @return string
534 */
535 public static function makeThumbLink2( Title $title, $file, $frameParams = [],
536 $handlerParams = [], $time = false, $query = ""
537 ) {
538 $exists = $file && $file->exists();
539
540 $page = $handlerParams['page'] ?? false;
541 if ( !isset( $frameParams['align'] ) ) {
542 $frameParams['align'] = 'right';
543 }
544 if ( !isset( $frameParams['alt'] ) ) {
545 $frameParams['alt'] = '';
546 }
547 if ( !isset( $frameParams['title'] ) ) {
548 $frameParams['title'] = '';
549 }
550 if ( !isset( $frameParams['caption'] ) ) {
551 $frameParams['caption'] = '';
552 }
553
554 if ( empty( $handlerParams['width'] ) ) {
555 // Reduce width for upright images when parameter 'upright' is used
556 $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
557 }
558 $thumb = false;
559 $noscale = false;
560 $manualthumb = false;
561
562 if ( !$exists ) {
563 $outerWidth = $handlerParams['width'] + 2;
564 } else {
565 if ( isset( $frameParams['manualthumb'] ) ) {
566 # Use manually specified thumbnail
567 $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
568 if ( $manual_title ) {
569 $manual_img = wfFindFile( $manual_title );
570 if ( $manual_img ) {
571 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
572 $manualthumb = true;
573 } else {
574 $exists = false;
575 }
576 }
577 } elseif ( isset( $frameParams['framed'] ) ) {
578 // Use image dimensions, don't scale
579 $thumb = $file->getUnscaledThumb( $handlerParams );
580 $noscale = true;
581 } else {
582 # Do not present an image bigger than the source, for bitmap-style images
583 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
584 $srcWidth = $file->getWidth( $page );
585 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
586 $handlerParams['width'] = $srcWidth;
587 }
588 $thumb = $file->transform( $handlerParams );
589 }
590
591 if ( $thumb ) {
592 $outerWidth = $thumb->getWidth() + 2;
593 } else {
594 $outerWidth = $handlerParams['width'] + 2;
595 }
596 }
597
598 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
599 # So we don't need to pass it here in $query. However, the URL for the
600 # zoom icon still needs it, so we make a unique query for it. See T16771
601 $url = $title->getLocalURL( $query );
602 if ( $page ) {
603 $url = wfAppendQuery( $url, [ 'page' => $page ] );
604 }
605 if ( $manualthumb
606 && !isset( $frameParams['link-title'] )
607 && !isset( $frameParams['link-url'] )
608 && !isset( $frameParams['no-link'] ) ) {
609 $frameParams['link-url'] = $url;
610 }
611
612 $s = "<div class=\"thumb t{$frameParams['align']}\">"
613 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
614
615 if ( !$exists ) {
616 $s .= self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
617 $zoomIcon = '';
618 } elseif ( !$thumb ) {
619 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
620 $zoomIcon = '';
621 } else {
622 if ( !$noscale && !$manualthumb ) {
623 self::processResponsiveImages( $file, $thumb, $handlerParams );
624 }
625 $params = [
626 'alt' => $frameParams['alt'],
627 'title' => $frameParams['title'],
628 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
629 ? $frameParams['class'] . ' '
630 : '' ) . 'thumbimage'
631 ];
632 $params = self::getImageLinkMTOParams( $frameParams, $query ) + $params;
633 $s .= $thumb->toHtml( $params );
634 if ( isset( $frameParams['framed'] ) ) {
635 $zoomIcon = "";
636 } else {
637 $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
638 Html::rawElement( 'a', [
639 'href' => $url,
640 'class' => 'internal',
641 'title' => wfMessage( 'thumbnail-more' )->text() ],
642 "" ) );
643 }
644 }
645 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
646 return str_replace( "\n", ' ', $s );
647 }
648
649 /**
650 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
651 * applicable.
652 *
653 * @param File $file
654 * @param MediaTransformOutput $thumb
655 * @param array $hp Image parameters
656 */
657 public static function processResponsiveImages( $file, $thumb, $hp ) {
658 global $wgResponsiveImages;
659 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
660 $hp15 = $hp;
661 $hp15['width'] = round( $hp['width'] * 1.5 );
662 $hp20 = $hp;
663 $hp20['width'] = $hp['width'] * 2;
664 if ( isset( $hp['height'] ) ) {
665 $hp15['height'] = round( $hp['height'] * 1.5 );
666 $hp20['height'] = $hp['height'] * 2;
667 }
668
669 $thumb15 = $file->transform( $hp15 );
670 $thumb20 = $file->transform( $hp20 );
671 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
672 $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
673 }
674 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
675 $thumb->responsiveUrls['2'] = $thumb20->getUrl();
676 }
677 }
678 }
679
680 /**
681 * Make a "broken" link to an image
682 *
683 * @since 1.16.3
684 * @param Title $title
685 * @param string $label Link label (plain text)
686 * @param string $query Query string
687 * @param string $unused1 Unused parameter kept for b/c
688 * @param string $unused2 Unused parameter kept for b/c
689 * @param bool $time A file of a certain timestamp was requested
690 * @return string
691 */
692 public static function makeBrokenImageLinkObj( $title, $label = '',
693 $query = '', $unused1 = '', $unused2 = '', $time = false
694 ) {
695 if ( !$title instanceof Title ) {
696 wfWarn( __METHOD__ . ': Requires $title to be a Title object.' );
697 return "<!-- ERROR -->" . htmlspecialchars( $label );
698 }
699
700 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
701 if ( $label == '' ) {
702 $label = $title->getPrefixedText();
703 }
704 $encLabel = htmlspecialchars( $label );
705 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
706
707 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads )
708 && !$currentExists
709 ) {
710 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
711
712 if ( $redir ) {
713 // We already know it's a redirect, so mark it
714 // accordingly
715 return self::link(
716 $title,
717 $encLabel,
718 [ 'class' => 'mw-redirect' ],
719 wfCgiToArray( $query ),
720 [ 'known', 'noclasses' ]
721 );
722 }
723
724 $href = self::getUploadUrl( $title, $query );
725
726 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
727 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
728 $encLabel . '</a>';
729 }
730
731 return self::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
732 }
733
734 /**
735 * Get the URL to upload a certain file
736 *
737 * @since 1.16.3
738 * @param Title $destFile Title object of the file to upload
739 * @param string $query Urlencoded query string to prepend
740 * @return string Urlencoded URL
741 */
742 protected static function getUploadUrl( $destFile, $query = '' ) {
743 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
744 $q = 'wpDestFile=' . $destFile->getPartialURL();
745 if ( $query != '' ) {
746 $q .= '&' . $query;
747 }
748
749 if ( $wgUploadMissingFileUrl ) {
750 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
751 } elseif ( $wgUploadNavigationUrl ) {
752 return wfAppendQuery( $wgUploadNavigationUrl, $q );
753 } else {
754 $upload = SpecialPage::getTitleFor( 'Upload' );
755 return $upload->getLocalURL( $q );
756 }
757 }
758
759 /**
760 * Create a direct link to a given uploaded file.
761 *
762 * @since 1.16.3
763 * @param Title $title
764 * @param string $html Pre-sanitized HTML
765 * @param string $time MW timestamp of file creation time
766 * @return string HTML
767 */
768 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
769 $img = wfFindFile( $title, [ 'time' => $time ] );
770 return self::makeMediaLinkFile( $title, $img, $html );
771 }
772
773 /**
774 * Create a direct link to a given uploaded file.
775 * This will make a broken link if $file is false.
776 *
777 * @since 1.16.3
778 * @param Title $title
779 * @param File|bool $file File object or false
780 * @param string $html Pre-sanitized HTML
781 * @return string HTML
782 *
783 * @todo Handle invalid or missing images better.
784 */
785 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
786 if ( $file && $file->exists() ) {
787 $url = $file->getUrl();
788 $class = 'internal';
789 } else {
790 $url = self::getUploadUrl( $title );
791 $class = 'new';
792 }
793
794 $alt = $title->getText();
795 if ( $html == '' ) {
796 $html = $alt;
797 }
798
799 $ret = '';
800 $attribs = [
801 'href' => $url,
802 'class' => $class,
803 'title' => $alt
804 ];
805
806 if ( !Hooks::run( 'LinkerMakeMediaLinkFile',
807 [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
808 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
809 . "with url {$url} and text {$html} to {$ret}\n", true );
810 return $ret;
811 }
812
813 return Html::rawElement( 'a', $attribs, $html );
814 }
815
816 /**
817 * Make a link to a special page given its name and, optionally,
818 * a message key from the link text.
819 * Usage example: Linker::specialLink( 'Recentchanges' )
820 *
821 * @since 1.16.3
822 * @param string $name
823 * @param string $key
824 * @return string
825 */
826 public static function specialLink( $name, $key = '' ) {
827 if ( $key == '' ) {
828 $key = strtolower( $name );
829 }
830
831 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->escaped() );
832 }
833
834 /**
835 * Make an external link
836 * @since 1.16.3. $title added in 1.21
837 * @param string $url URL to link to
838 * @param string $text Text of link
839 * @param bool $escape Do we escape the link text?
840 * @param string $linktype Type of external link. Gets added to the classes
841 * @param array $attribs Array of extra attributes to <a>
842 * @param Title|null $title Title object used for title specific link attributes
843 * @return string
844 */
845 public static function makeExternalLink( $url, $text, $escape = true,
846 $linktype = '', $attribs = [], $title = null
847 ) {
848 global $wgTitle;
849 $class = "external";
850 if ( $linktype ) {
851 $class .= " $linktype";
852 }
853 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
854 $class .= " {$attribs['class']}";
855 }
856 $attribs['class'] = $class;
857
858 if ( $escape ) {
859 $text = htmlspecialchars( $text );
860 }
861
862 if ( !$title ) {
863 $title = $wgTitle;
864 }
865 $newRel = Parser::getExternalLinkRel( $url, $title );
866 if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
867 $attribs['rel'] = $newRel;
868 } elseif ( $newRel !== '' ) {
869 // Merge the rel attributes.
870 $newRels = explode( ' ', $newRel );
871 $oldRels = explode( ' ', $attribs['rel'] );
872 $combined = array_unique( array_merge( $newRels, $oldRels ) );
873 $attribs['rel'] = implode( ' ', $combined );
874 }
875 $link = '';
876 $success = Hooks::run( 'LinkerMakeExternalLink',
877 [ &$url, &$text, &$link, &$attribs, $linktype ] );
878 if ( !$success ) {
879 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
880 . "with url {$url} and text {$text} to {$link}\n", true );
881 return $link;
882 }
883 $attribs['href'] = $url;
884 return Html::rawElement( 'a', $attribs, $text );
885 }
886
887 /**
888 * Make user link (or user contributions for unregistered users)
889 * @param int $userId User id in database.
890 * @param string $userName User name in database.
891 * @param string $altUserName Text to display instead of the user name (optional)
892 * @return string HTML fragment
893 * @since 1.16.3. $altUserName was added in 1.19.
894 */
895 public static function userLink( $userId, $userName, $altUserName = false ) {
896 $classes = 'mw-userlink';
897 $page = null;
898 if ( $userId == 0 ) {
899 $page = ExternalUserNames::getUserLinkTitle( $userName );
900
901 if ( ExternalUserNames::isExternal( $userName ) ) {
902 $classes .= ' mw-extuserlink';
903 } elseif ( $altUserName === false ) {
904 $altUserName = IP::prettifyIP( $userName );
905 }
906 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
907 } else {
908 $page = Title::makeTitle( NS_USER, $userName );
909 }
910
911 // Wrap the output with <bdi> tags for directionality isolation
912 $linkText =
913 '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>';
914
915 return $page
916 ? self::link( $page, $linkText, [ 'class' => $classes ] )
917 : Html::rawElement( 'span', [ 'class' => $classes ], $linkText );
918 }
919
920 /**
921 * Generate standard user tool links (talk, contributions, block link, etc.)
922 *
923 * @since 1.16.3
924 * @param int $userId User identifier
925 * @param string $userText User name or IP address
926 * @param bool $redContribsWhenNoEdits Should the contributions link be
927 * red if the user has no edits?
928 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
929 * and Linker::TOOL_LINKS_EMAIL).
930 * @param int $edits User edit count (optional, for performance)
931 * @return string HTML fragment
932 */
933 public static function userToolLinks(
934 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
935 ) {
936 global $wgUser, $wgDisableAnonTalk, $wgLang;
937 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
938 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
939 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
940
941 if ( $userId == 0 && ExternalUserNames::isExternal( $userText ) ) {
942 // No tools for an external user
943 return '';
944 }
945
946 $items = [];
947 if ( $talkable ) {
948 $items[] = self::userTalkLink( $userId, $userText );
949 }
950 if ( $userId ) {
951 // check if the user has an edit
952 $attribs = [];
953 $attribs['class'] = 'mw-usertoollinks-contribs';
954 if ( $redContribsWhenNoEdits ) {
955 if ( intval( $edits ) === 0 && $edits !== 0 ) {
956 $user = User::newFromId( $userId );
957 $edits = $user->getEditCount();
958 }
959 if ( $edits === 0 ) {
960 $attribs['class'] .= ' new';
961 }
962 }
963 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
964
965 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
966 }
967 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
968 $items[] = self::blockLink( $userId, $userText );
969 }
970
971 if ( $addEmailLink && $wgUser->canSendEmail() ) {
972 $items[] = self::emailLink( $userId, $userText );
973 }
974
975 Hooks::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
976
977 if ( $items ) {
978 return wfMessage( 'word-separator' )->escaped()
979 . '<span class="mw-usertoollinks">'
980 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
981 . '</span>';
982 } else {
983 return '';
984 }
985 }
986
987 /**
988 * Alias for userToolLinks( $userId, $userText, true );
989 * @since 1.16.3
990 * @param int $userId User identifier
991 * @param string $userText User name or IP address
992 * @param int $edits User edit count (optional, for performance)
993 * @return string
994 */
995 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
996 return self::userToolLinks( $userId, $userText, true, 0, $edits );
997 }
998
999 /**
1000 * @since 1.16.3
1001 * @param int $userId User id in database.
1002 * @param string $userText User name in database.
1003 * @return string HTML fragment with user talk link
1004 */
1005 public static function userTalkLink( $userId, $userText ) {
1006 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1007 $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
1008 $userTalkLink = self::link( $userTalkPage,
1009 wfMessage( 'talkpagelinktext' )->escaped(),
1010 $moreLinkAttribs );
1011 return $userTalkLink;
1012 }
1013
1014 /**
1015 * @since 1.16.3
1016 * @param int $userId
1017 * @param string $userText User name in database.
1018 * @return string HTML fragment with block link
1019 */
1020 public static function blockLink( $userId, $userText ) {
1021 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1022 $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1023 $blockLink = self::link( $blockPage,
1024 wfMessage( 'blocklink' )->escaped(),
1025 $moreLinkAttribs );
1026 return $blockLink;
1027 }
1028
1029 /**
1030 * @param int $userId
1031 * @param string $userText User name in database.
1032 * @return string HTML fragment with e-mail user link
1033 */
1034 public static function emailLink( $userId, $userText ) {
1035 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1036 $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1037 $emailLink = self::link( $emailPage,
1038 wfMessage( 'emaillink' )->escaped(),
1039 $moreLinkAttribs );
1040 return $emailLink;
1041 }
1042
1043 /**
1044 * Generate a user link if the current user is allowed to view it
1045 * @since 1.16.3
1046 * @param Revision $rev
1047 * @param bool $isPublic Show only if all users can see it
1048 * @return string HTML fragment
1049 */
1050 public static function revUserLink( $rev, $isPublic = false ) {
1051 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1052 $link = wfMessage( 'rev-deleted-user' )->escaped();
1053 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1054 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1055 $rev->getUserText( Revision::FOR_THIS_USER ) );
1056 } else {
1057 $link = wfMessage( 'rev-deleted-user' )->escaped();
1058 }
1059 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1060 return '<span class="history-deleted">' . $link . '</span>';
1061 }
1062 return $link;
1063 }
1064
1065 /**
1066 * Generate a user tool link cluster if the current user is allowed to view it
1067 * @since 1.16.3
1068 * @param Revision $rev
1069 * @param bool $isPublic Show only if all users can see it
1070 * @return string HTML
1071 */
1072 public static function revUserTools( $rev, $isPublic = false ) {
1073 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1074 $link = wfMessage( 'rev-deleted-user' )->escaped();
1075 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1076 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1077 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1078 $link = self::userLink( $userId, $userText )
1079 . self::userToolLinks( $userId, $userText );
1080 } else {
1081 $link = wfMessage( 'rev-deleted-user' )->escaped();
1082 }
1083 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1084 return ' <span class="history-deleted">' . $link . '</span>';
1085 }
1086 return $link;
1087 }
1088
1089 /**
1090 * This function is called by all recent changes variants, by the page history,
1091 * and by the user contributions list. It is responsible for formatting edit
1092 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1093 * auto-generated comments (from section editing) and formats [[wikilinks]].
1094 *
1095 * @author Erik Moeller <moeller@scireview.de>
1096 * @since 1.16.3. $wikiId added in 1.26
1097 *
1098 * Note: there's not always a title to pass to this function.
1099 * Since you can't set a default parameter for a reference, I've turned it
1100 * temporarily to a value pass. Should be adjusted further. --brion
1101 *
1102 * @param string $comment
1103 * @param Title|null $title Title object (to generate link to the section in autocomment)
1104 * or null
1105 * @param bool $local Whether section links should refer to local page
1106 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1107 * For use with external changes.
1108 *
1109 * @return mixed|string
1110 */
1111 public static function formatComment(
1112 $comment, $title = null, $local = false, $wikiId = null
1113 ) {
1114 # Sanitize text a bit:
1115 $comment = str_replace( "\n", " ", $comment );
1116 # Allow HTML entities (for T15815)
1117 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1118
1119 # Render autocomments and make links:
1120 $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1121 $comment = self::formatLinksInComment( $comment, $title, $local, $wikiId );
1122
1123 return $comment;
1124 }
1125
1126 /**
1127 * Converts autogenerated comments in edit summaries into section links.
1128 *
1129 * The pattern for autogen comments is / * foo * /, which makes for
1130 * some nasty regex.
1131 * We look for all comments, match any text before and after the comment,
1132 * add a separator where needed and format the comment itself with CSS
1133 * Called by Linker::formatComment.
1134 *
1135 * @param string $comment Comment text
1136 * @param Title|null $title An optional title object used to links to sections
1137 * @param bool $local Whether section links should refer to local page
1138 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1139 * as used by WikiMap.
1140 *
1141 * @return string Formatted comment (wikitext)
1142 */
1143 private static function formatAutocomments(
1144 $comment, $title = null, $local = false, $wikiId = null
1145 ) {
1146 // @todo $append here is something of a hack to preserve the status
1147 // quo. Someone who knows more about bidi and such should decide
1148 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1149 // wiki, both when autocomments exist and when they don't, and
1150 // (2) what markup will make that actually happen.
1151 $append = '';
1152 $comment = preg_replace_callback(
1153 // To detect the presence of content before or after the
1154 // auto-comment, we use capturing groups inside optional zero-width
1155 // assertions. But older versions of PCRE can't directly make
1156 // zero-width assertions optional, so wrap them in a non-capturing
1157 // group.
1158 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1159 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1160 global $wgLang;
1161
1162 // Ensure all match positions are defined
1163 $match += [ '', '', '', '' ];
1164
1165 $pre = $match[1] !== '';
1166 $auto = $match[2];
1167 $post = $match[3] !== '';
1168 $comment = null;
1169
1170 Hooks::run(
1171 'FormatAutocomments',
1172 [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1173 );
1174
1175 if ( $comment === null ) {
1176 $link = '';
1177 if ( $title ) {
1178 $section = $auto;
1179 # Remove links that a user may have manually put in the autosummary
1180 # This could be improved by copying as much of Parser::stripSectionName as desired.
1181 $section = str_replace( '[[:', '', $section );
1182 $section = str_replace( '[[', '', $section );
1183 $section = str_replace( ']]', '', $section );
1184
1185 $section = substr( Parser::guessSectionNameFromStrippedText( $section ), 1 );
1186 if ( $local ) {
1187 $sectionTitle = Title::makeTitleSafe( NS_MAIN, '', $section );
1188 } else {
1189 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1190 $title->getDBkey(), $section );
1191 }
1192 if ( $sectionTitle ) {
1193 $link = Linker::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1194 } else {
1195 $link = '';
1196 }
1197 }
1198 if ( $pre ) {
1199 # written summary $presep autocomment (summary /* section */)
1200 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1201 }
1202 if ( $post ) {
1203 # autocomment $postsep written summary (/* section */ summary)
1204 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1205 }
1206 $auto = '<span class="autocomment">' . $auto . '</span>';
1207 $comment = $pre . $link . $wgLang->getDirMark()
1208 . '<span dir="auto">' . $auto;
1209 $append .= '</span>';
1210 }
1211 return $comment;
1212 },
1213 $comment
1214 );
1215 return $comment . $append;
1216 }
1217
1218 /**
1219 * Formats wiki links and media links in text; all other wiki formatting
1220 * is ignored
1221 *
1222 * @since 1.16.3. $wikiId added in 1.26
1223 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1224 *
1225 * @param string $comment Text to format links in. WARNING! Since the output of this
1226 * function is html, $comment must be sanitized for use as html. You probably want
1227 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1228 * this function.
1229 * @param Title|null $title An optional title object used to links to sections
1230 * @param bool $local Whether section links should refer to local page
1231 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1232 * as used by WikiMap.
1233 *
1234 * @return string
1235 */
1236 public static function formatLinksInComment(
1237 $comment, $title = null, $local = false, $wikiId = null
1238 ) {
1239 return preg_replace_callback(
1240 '/
1241 \[\[
1242 :? # ignore optional leading colon
1243 ([^\]|]+) # 1. link target; page names cannot include ] or |
1244 (?:\|
1245 # 2. link text
1246 # Stop matching at ]] without relying on backtracking.
1247 ((?:]?[^\]])*+)
1248 )?
1249 \]\]
1250 ([^[]*) # 3. link trail (the text up until the next link)
1251 /x',
1252 function ( $match ) use ( $title, $local, $wikiId ) {
1253 global $wgContLang;
1254
1255 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1256 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1257
1258 $comment = $match[0];
1259
1260 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1261 if ( strpos( $match[1], '%' ) !== false ) {
1262 $match[1] = strtr(
1263 rawurldecode( $match[1] ),
1264 [ '<' => '&lt;', '>' => '&gt;' ]
1265 );
1266 }
1267
1268 # Handle link renaming [[foo|text]] will show link as "text"
1269 if ( $match[2] != "" ) {
1270 $text = $match[2];
1271 } else {
1272 $text = $match[1];
1273 }
1274 $submatch = [];
1275 $thelink = null;
1276 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1277 # Media link; trail not supported.
1278 $linkRegexp = '/\[\[(.*?)\]\]/';
1279 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1280 if ( $title ) {
1281 $thelink = Linker::makeMediaLinkObj( $title, $text );
1282 }
1283 } else {
1284 # Other kind of link
1285 # Make sure its target is non-empty
1286 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1287 $match[1] = substr( $match[1], 1 );
1288 }
1289 if ( $match[1] !== false && $match[1] !== '' ) {
1290 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1291 $trail = $submatch[1];
1292 } else {
1293 $trail = "";
1294 }
1295 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1296 list( $inside, $trail ) = Linker::splitTrail( $trail );
1297
1298 $linkText = $text;
1299 $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1300
1301 $target = Title::newFromText( $linkTarget );
1302 if ( $target ) {
1303 if ( $target->getText() == '' && !$target->isExternal()
1304 && !$local && $title
1305 ) {
1306 $target = $title->createFragmentTarget( $target->getFragment() );
1307 }
1308
1309 $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1310 }
1311 }
1312 }
1313 if ( $thelink ) {
1314 // If the link is still valid, go ahead and replace it in!
1315 $comment = preg_replace(
1316 $linkRegexp,
1317 StringUtils::escapeRegexReplacement( $thelink ),
1318 $comment,
1319 1
1320 );
1321 }
1322
1323 return $comment;
1324 },
1325 $comment
1326 );
1327 }
1328
1329 /**
1330 * Generates a link to the given Title
1331 *
1332 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1333 *
1334 * @param LinkTarget $linkTarget
1335 * @param string $text
1336 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1337 * as used by WikiMap.
1338 * @param string|string[] $options See the $options parameter in Linker::link.
1339 *
1340 * @return string HTML link
1341 */
1342 public static function makeCommentLink(
1343 LinkTarget $linkTarget, $text, $wikiId = null, $options = []
1344 ) {
1345 if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1346 $link = self::makeExternalLink(
1347 WikiMap::getForeignURL(
1348 $wikiId,
1349 $linkTarget->getNamespace() === 0
1350 ? $linkTarget->getDBkey()
1351 : MWNamespace::getCanonicalName( $linkTarget->getNamespace() ) . ':'
1352 . $linkTarget->getDBkey(),
1353 $linkTarget->getFragment()
1354 ),
1355 $text,
1356 /* escape = */ false // Already escaped
1357 );
1358 } else {
1359 $link = self::link( $linkTarget, $text, [], [], $options );
1360 }
1361
1362 return $link;
1363 }
1364
1365 /**
1366 * @param Title $contextTitle
1367 * @param string $target
1368 * @param string &$text
1369 * @return string
1370 */
1371 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1372 # Valid link forms:
1373 # Foobar -- normal
1374 # :Foobar -- override special treatment of prefix (images, language links)
1375 # /Foobar -- convert to CurrentPage/Foobar
1376 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1377 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1378 # ../Foobar -- convert to CurrentPage/Foobar,
1379 # (from CurrentPage/CurrentSubPage)
1380 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1381 # (from CurrentPage/CurrentSubPage)
1382
1383 $ret = $target; # default return value is no change
1384
1385 # Some namespaces don't allow subpages,
1386 # so only perform processing if subpages are allowed
1387 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1388 $hash = strpos( $target, '#' );
1389 if ( $hash !== false ) {
1390 $suffix = substr( $target, $hash );
1391 $target = substr( $target, 0, $hash );
1392 } else {
1393 $suffix = '';
1394 }
1395 # T9425
1396 $target = trim( $target );
1397 # Look at the first character
1398 if ( $target != '' && $target[0] === '/' ) {
1399 # / at end means we don't want the slash to be shown
1400 $m = [];
1401 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1402 if ( $trailingSlashes ) {
1403 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1404 } else {
1405 $noslash = substr( $target, 1 );
1406 }
1407
1408 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1409 if ( $text === '' ) {
1410 $text = $target . $suffix;
1411 } # this might be changed for ugliness reasons
1412 } else {
1413 # check for .. subpage backlinks
1414 $dotdotcount = 0;
1415 $nodotdot = $target;
1416 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1417 ++$dotdotcount;
1418 $nodotdot = substr( $nodotdot, 3 );
1419 }
1420 if ( $dotdotcount > 0 ) {
1421 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1422 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1423 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1424 # / at the end means don't show full path
1425 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1426 $nodotdot = rtrim( $nodotdot, '/' );
1427 if ( $text === '' ) {
1428 $text = $nodotdot . $suffix;
1429 }
1430 }
1431 $nodotdot = trim( $nodotdot );
1432 if ( $nodotdot != '' ) {
1433 $ret .= '/' . $nodotdot;
1434 }
1435 $ret .= $suffix;
1436 }
1437 }
1438 }
1439 }
1440
1441 return $ret;
1442 }
1443
1444 /**
1445 * Wrap a comment in standard punctuation and formatting if
1446 * it's non-empty, otherwise return empty string.
1447 *
1448 * @since 1.16.3. $wikiId added in 1.26
1449 * @param string $comment
1450 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1451 * @param bool $local Whether section links should refer to local page
1452 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1453 * For use with external changes.
1454 *
1455 * @return string
1456 */
1457 public static function commentBlock(
1458 $comment, $title = null, $local = false, $wikiId = null
1459 ) {
1460 // '*' used to be the comment inserted by the software way back
1461 // in antiquity in case none was provided, here for backwards
1462 // compatibility, acc. to brion -ævar
1463 if ( $comment == '' || $comment == '*' ) {
1464 return '';
1465 } else {
1466 $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1467 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1468 return " <span class=\"comment\">$formatted</span>";
1469 }
1470 }
1471
1472 /**
1473 * Wrap and format the given revision's comment block, if the current
1474 * user is allowed to view it.
1475 *
1476 * @since 1.16.3
1477 * @param Revision $rev
1478 * @param bool $local Whether section links should refer to local page
1479 * @param bool $isPublic Show only if all users can see it
1480 * @return string HTML fragment
1481 */
1482 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1483 if ( $rev->getComment( Revision::RAW ) == "" ) {
1484 return "";
1485 }
1486 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1487 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1488 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1489 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1490 $rev->getTitle(), $local );
1491 } else {
1492 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1493 }
1494 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1495 return " <span class=\"history-deleted\">$block</span>";
1496 }
1497 return $block;
1498 }
1499
1500 /**
1501 * @since 1.16.3
1502 * @param int $size
1503 * @return string
1504 */
1505 public static function formatRevisionSize( $size ) {
1506 if ( $size == 0 ) {
1507 $stxt = wfMessage( 'historyempty' )->escaped();
1508 } else {
1509 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1510 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1511 }
1512 return "<span class=\"history-size\">$stxt</span>";
1513 }
1514
1515 /**
1516 * Add another level to the Table of Contents
1517 *
1518 * @since 1.16.3
1519 * @return string
1520 */
1521 public static function tocIndent() {
1522 return "\n<ul>";
1523 }
1524
1525 /**
1526 * Finish one or more sublevels on the Table of Contents
1527 *
1528 * @since 1.16.3
1529 * @param int $level
1530 * @return string
1531 */
1532 public static function tocUnindent( $level ) {
1533 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1534 }
1535
1536 /**
1537 * parameter level defines if we are on an indentation level
1538 *
1539 * @since 1.16.3
1540 * @param string $anchor
1541 * @param string $tocline
1542 * @param string $tocnumber
1543 * @param string $level
1544 * @param string|bool $sectionIndex
1545 * @return string
1546 */
1547 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1548 $classes = "toclevel-$level";
1549 if ( $sectionIndex !== false ) {
1550 $classes .= " tocsection-$sectionIndex";
1551 }
1552
1553 // \n<li class="$classes"><a href="#$anchor"><span class="tocnumber">
1554 // $tocnumber</span> <span class="toctext">$tocline</span></a>
1555 return "\n" . Html::openElement( 'li', [ 'class' => $classes ] )
1556 . Html::rawElement( 'a',
1557 [ 'href' => "#$anchor" ],
1558 Html::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1559 . ' '
1560 . Html::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1561 );
1562 }
1563
1564 /**
1565 * End a Table Of Contents line.
1566 * tocUnindent() will be used instead if we're ending a line below
1567 * the new level.
1568 * @since 1.16.3
1569 * @return string
1570 */
1571 public static function tocLineEnd() {
1572 return "</li>\n";
1573 }
1574
1575 /**
1576 * Wraps the TOC in a table and provides the hide/collapse javascript.
1577 *
1578 * @since 1.16.3
1579 * @param string $toc Html of the Table Of Contents
1580 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1581 * @return string Full html of the TOC
1582 */
1583 public static function tocList( $toc, $lang = false ) {
1584 $lang = wfGetLangObj( $lang );
1585 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1586
1587 return '<div id="toc" class="toc">'
1588 . Html::openElement( 'div', [
1589 'class' => 'toctitle',
1590 'lang' => $lang->getHtmlCode(),
1591 'dir' => $lang->getDir(),
1592 ] )
1593 . '<h2>' . $title . "</h2></div>\n"
1594 . $toc
1595 . "</ul>\n</div>\n";
1596 }
1597
1598 /**
1599 * Generate a table of contents from a section tree.
1600 *
1601 * @since 1.16.3. $lang added in 1.17
1602 * @param array $tree Return value of ParserOutput::getSections()
1603 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1604 * @return string HTML fragment
1605 */
1606 public static function generateTOC( $tree, $lang = false ) {
1607 $toc = '';
1608 $lastLevel = 0;
1609 foreach ( $tree as $section ) {
1610 if ( $section['toclevel'] > $lastLevel ) {
1611 $toc .= self::tocIndent();
1612 } elseif ( $section['toclevel'] < $lastLevel ) {
1613 $toc .= self::tocUnindent(
1614 $lastLevel - $section['toclevel'] );
1615 } else {
1616 $toc .= self::tocLineEnd();
1617 }
1618
1619 $toc .= self::tocLine( $section['anchor'],
1620 $section['line'], $section['number'],
1621 $section['toclevel'], $section['index'] );
1622 $lastLevel = $section['toclevel'];
1623 }
1624 $toc .= self::tocLineEnd();
1625 return self::tocList( $toc, $lang );
1626 }
1627
1628 /**
1629 * Create a headline for content
1630 *
1631 * @since 1.16.3
1632 * @param int $level The level of the headline (1-6)
1633 * @param string $attribs Any attributes for the headline, starting with
1634 * a space and ending with '>'
1635 * This *must* be at least '>' for no attribs
1636 * @param string $anchor The anchor to give the headline (the bit after the #)
1637 * @param string $html HTML for the text of the header
1638 * @param string $link HTML to add for the section edit link
1639 * @param string|bool $fallbackAnchor A second, optional anchor to give for
1640 * backward compatibility (false to omit)
1641 *
1642 * @return string HTML headline
1643 */
1644 public static function makeHeadline( $level, $attribs, $anchor, $html,
1645 $link, $fallbackAnchor = false
1646 ) {
1647 $anchorEscaped = htmlspecialchars( $anchor );
1648 $fallback = '';
1649 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1650 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1651 $fallback = "<span id=\"$fallbackAnchor\"></span>";
1652 }
1653 $ret = "<h$level$attribs"
1654 . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1655 . $link
1656 . "</h$level>";
1657
1658 return $ret;
1659 }
1660
1661 /**
1662 * Split a link trail, return the "inside" portion and the remainder of the trail
1663 * as a two-element array
1664 * @param string $trail
1665 * @return array
1666 */
1667 static function splitTrail( $trail ) {
1668 global $wgContLang;
1669 $regex = $wgContLang->linkTrail();
1670 $inside = '';
1671 if ( $trail !== '' ) {
1672 $m = [];
1673 if ( preg_match( $regex, $trail, $m ) ) {
1674 $inside = $m[1];
1675 $trail = $m[2];
1676 }
1677 }
1678 return [ $inside, $trail ];
1679 }
1680
1681 /**
1682 * Generate a rollback link for a given revision. Currently it's the
1683 * caller's responsibility to ensure that the revision is the top one. If
1684 * it's not, of course, the user will get an error message.
1685 *
1686 * If the calling page is called with the parameter &bot=1, all rollback
1687 * links also get that parameter. It causes the edit itself and the rollback
1688 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1689 * changes, so this allows sysops to combat a busy vandal without bothering
1690 * other users.
1691 *
1692 * If the option verify is set this function will return the link only in case the
1693 * revision can be reverted. Please note that due to performance limitations
1694 * it might be assumed that a user isn't the only contributor of a page while
1695 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1696 * work if $wgShowRollbackEditCount is disabled, so this can only function
1697 * as an additional check.
1698 *
1699 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1700 *
1701 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1702 *
1703 * @param Revision $rev
1704 * @param IContextSource $context Context to use or null for the main context.
1705 * @param array $options
1706 * @return string
1707 */
1708 public static function generateRollback( $rev, IContextSource $context = null,
1709 $options = [ 'verify' ]
1710 ) {
1711 if ( $context === null ) {
1712 $context = RequestContext::getMain();
1713 }
1714
1715 $editCount = false;
1716 if ( in_array( 'verify', $options, true ) ) {
1717 $editCount = self::getRollbackEditCount( $rev, true );
1718 if ( $editCount === false ) {
1719 return '';
1720 }
1721 }
1722
1723 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1724
1725 if ( !in_array( 'noBrackets', $options, true ) ) {
1726 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1727 }
1728
1729 return '<span class="mw-rollback-link">' . $inner . '</span>';
1730 }
1731
1732 /**
1733 * This function will return the number of revisions which a rollback
1734 * would revert and, if $verify is set it will verify that a revision
1735 * can be reverted (that the user isn't the only contributor and the
1736 * revision we might rollback to isn't deleted). These checks can only
1737 * function as an additional check as this function only checks against
1738 * the last $wgShowRollbackEditCount edits.
1739 *
1740 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1741 * is set and the user is the only contributor of the page.
1742 *
1743 * @param Revision $rev
1744 * @param bool $verify Try to verify that this revision can really be rolled back
1745 * @return int|bool|null
1746 */
1747 public static function getRollbackEditCount( $rev, $verify ) {
1748 global $wgShowRollbackEditCount;
1749 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1750 // Nothing has happened, indicate this by returning 'null'
1751 return null;
1752 }
1753
1754 $dbr = wfGetDB( DB_REPLICA );
1755
1756 // Up to the value of $wgShowRollbackEditCount revisions are counted
1757 $revQuery = Revision::getQueryInfo();
1758 $res = $dbr->select(
1759 $revQuery['tables'],
1760 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1761 // $rev->getPage() returns null sometimes
1762 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1763 __METHOD__,
1764 [
1765 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1766 'ORDER BY' => 'rev_timestamp DESC',
1767 'LIMIT' => $wgShowRollbackEditCount + 1
1768 ],
1769 $revQuery['joins']
1770 );
1771
1772 $editCount = 0;
1773 $moreRevs = false;
1774 foreach ( $res as $row ) {
1775 if ( $rev->getUserText( Revision::RAW ) != $row->rev_user_text ) {
1776 if ( $verify &&
1777 ( $row->rev_deleted & Revision::DELETED_TEXT
1778 || $row->rev_deleted & Revision::DELETED_USER
1779 ) ) {
1780 // If the user or the text of the revision we might rollback
1781 // to is deleted in some way we can't rollback. Similar to
1782 // the sanity checks in WikiPage::commitRollback.
1783 return false;
1784 }
1785 $moreRevs = true;
1786 break;
1787 }
1788 $editCount++;
1789 }
1790
1791 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1792 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1793 // and there weren't any other revisions. That means that the current user is the only
1794 // editor, so we can't rollback
1795 return false;
1796 }
1797 return $editCount;
1798 }
1799
1800 /**
1801 * Build a raw rollback link, useful for collections of "tool" links
1802 *
1803 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1804 * @param Revision $rev
1805 * @param IContextSource|null $context Context to use or null for the main context.
1806 * @param int $editCount Number of edits that would be reverted
1807 * @return string HTML fragment
1808 */
1809 public static function buildRollbackLink( $rev, IContextSource $context = null,
1810 $editCount = false
1811 ) {
1812 global $wgShowRollbackEditCount, $wgMiserMode;
1813
1814 // To config which pages are affected by miser mode
1815 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1816
1817 if ( $context === null ) {
1818 $context = RequestContext::getMain();
1819 }
1820
1821 $title = $rev->getTitle();
1822 $query = [
1823 'action' => 'rollback',
1824 'from' => $rev->getUserText(),
1825 'token' => $context->getUser()->getEditToken( 'rollback' ),
1826 ];
1827 $attrs = [
1828 'data-mw' => 'interface',
1829 'title' => $context->msg( 'tooltip-rollback' )->text(),
1830 ];
1831 $options = [ 'known', 'noclasses' ];
1832
1833 if ( $context->getRequest()->getBool( 'bot' ) ) {
1834 $query['bot'] = '1';
1835 $query['hidediff'] = '1'; // T17999
1836 }
1837
1838 $disableRollbackEditCount = false;
1839 if ( $wgMiserMode ) {
1840 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1841 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1842 $disableRollbackEditCount = true;
1843 break;
1844 }
1845 }
1846 }
1847
1848 if ( !$disableRollbackEditCount
1849 && is_int( $wgShowRollbackEditCount )
1850 && $wgShowRollbackEditCount > 0
1851 ) {
1852 if ( !is_numeric( $editCount ) ) {
1853 $editCount = self::getRollbackEditCount( $rev, false );
1854 }
1855
1856 if ( $editCount > $wgShowRollbackEditCount ) {
1857 $html = $context->msg( 'rollbacklinkcount-morethan' )
1858 ->numParams( $wgShowRollbackEditCount )->parse();
1859 } else {
1860 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1861 }
1862
1863 return self::link( $title, $html, $attrs, $query, $options );
1864 } else {
1865 $html = $context->msg( 'rollbacklink' )->escaped();
1866 return self::link( $title, $html, $attrs, $query, $options );
1867 }
1868 }
1869
1870 /**
1871 * @deprecated since 1.28, use TemplatesOnThisPageFormatter directly
1872 *
1873 * Returns HTML for the "templates used on this page" list.
1874 *
1875 * Make an HTML list of templates, and then add a "More..." link at
1876 * the bottom. If $more is null, do not add a "More..." link. If $more
1877 * is a Title, make a link to that title and use it. If $more is a string,
1878 * directly paste it in as the link (escaping needs to be done manually).
1879 * Finally, if $more is a Message, call toString().
1880 *
1881 * @since 1.16.3. $more added in 1.21
1882 * @param Title[] $templates Array of templates
1883 * @param bool $preview Whether this is for a preview
1884 * @param bool $section Whether this is for a section edit
1885 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1886 * @return string HTML output
1887 */
1888 public static function formatTemplates( $templates, $preview = false,
1889 $section = false, $more = null
1890 ) {
1891 wfDeprecated( __METHOD__, '1.28' );
1892
1893 $type = false;
1894 if ( $preview ) {
1895 $type = 'preview';
1896 } elseif ( $section ) {
1897 $type = 'section';
1898 }
1899
1900 if ( $more instanceof Message ) {
1901 $more = $more->toString();
1902 }
1903
1904 $formatter = new TemplatesOnThisPageFormatter(
1905 RequestContext::getMain(),
1906 MediaWikiServices::getInstance()->getLinkRenderer()
1907 );
1908 return $formatter->format( $templates, $type, $more );
1909 }
1910
1911 /**
1912 * Returns HTML for the "hidden categories on this page" list.
1913 *
1914 * @since 1.16.3
1915 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1916 * or similar
1917 * @return string HTML output
1918 */
1919 public static function formatHiddenCategories( $hiddencats ) {
1920 $outText = '';
1921 if ( count( $hiddencats ) > 0 ) {
1922 # Construct the HTML
1923 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1924 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1925 $outText .= "</div><ul>\n";
1926
1927 foreach ( $hiddencats as $titleObj ) {
1928 # If it's hidden, it must exist - no need to check with a LinkBatch
1929 $outText .= '<li>'
1930 . self::link( $titleObj, null, [], [], 'known' )
1931 . "</li>\n";
1932 }
1933 $outText .= '</ul>';
1934 }
1935 return $outText;
1936 }
1937
1938 /**
1939 * @deprecated since 1.28, use Language::formatSize() directly
1940 *
1941 * Format a size in bytes for output, using an appropriate
1942 * unit (B, KB, MB or GB) according to the magnitude in question
1943 *
1944 * @since 1.16.3
1945 * @param int $size Size to format
1946 * @return string
1947 */
1948 public static function formatSize( $size ) {
1949 wfDeprecated( __METHOD__, '1.28' );
1950
1951 global $wgLang;
1952 return htmlspecialchars( $wgLang->formatSize( $size ) );
1953 }
1954
1955 /**
1956 * Given the id of an interface element, constructs the appropriate title
1957 * attribute from the system messages. (Note, this is usually the id but
1958 * isn't always, because sometimes the accesskey needs to go on a different
1959 * element than the id, for reverse-compatibility, etc.)
1960 *
1961 * @since 1.16.3 $msgParams added in 1.27
1962 * @param string $name Id of the element, minus prefixes.
1963 * @param string|array|null $options Null, string or array with some of the following options:
1964 * - 'withaccess' to add an access-key hint
1965 * - 'nonexisting' to add an accessibility hint that page does not exist
1966 * @param array $msgParams Parameters to pass to the message
1967 *
1968 * @return string Contents of the title attribute (which you must HTML-
1969 * escape), or false for no title attribute
1970 */
1971 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
1972 $message = wfMessage( "tooltip-$name", $msgParams );
1973 if ( !$message->exists() ) {
1974 $tooltip = false;
1975 } else {
1976 $tooltip = $message->text();
1977 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1978 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1979 # Message equal to '-' means suppress it.
1980 if ( $tooltip == '-' ) {
1981 $tooltip = false;
1982 }
1983 }
1984
1985 $options = (array)$options;
1986
1987 if ( in_array( 'nonexisting', $options ) ) {
1988 $tooltip = wfMessage( 'red-link-title', $tooltip ?: '' )->text();
1989 }
1990 if ( in_array( 'withaccess', $options ) ) {
1991 $accesskey = self::accesskey( $name );
1992 if ( $accesskey !== false ) {
1993 // Should be build the same as in jquery.accessKeyLabel.js
1994 if ( $tooltip === false || $tooltip === '' ) {
1995 $tooltip = wfMessage( 'brackets', $accesskey )->text();
1996 } else {
1997 $tooltip .= wfMessage( 'word-separator' )->text();
1998 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
1999 }
2000 }
2001 }
2002
2003 return $tooltip;
2004 }
2005
2006 public static $accesskeycache;
2007
2008 /**
2009 * Given the id of an interface element, constructs the appropriate
2010 * accesskey attribute from the system messages. (Note, this is usually
2011 * the id but isn't always, because sometimes the accesskey needs to go on
2012 * a different element than the id, for reverse-compatibility, etc.)
2013 *
2014 * @since 1.16.3
2015 * @param string $name Id of the element, minus prefixes.
2016 * @return string Contents of the accesskey attribute (which you must HTML-
2017 * escape), or false for no accesskey attribute
2018 */
2019 public static function accesskey( $name ) {
2020 if ( isset( self::$accesskeycache[$name] ) ) {
2021 return self::$accesskeycache[$name];
2022 }
2023
2024 $message = wfMessage( "accesskey-$name" );
2025
2026 if ( !$message->exists() ) {
2027 $accesskey = false;
2028 } else {
2029 $accesskey = $message->plain();
2030 if ( $accesskey === '' || $accesskey === '-' ) {
2031 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2032 # attribute, but this is broken for accesskey: that might be a useful
2033 # value.
2034 $accesskey = false;
2035 }
2036 }
2037
2038 self::$accesskeycache[$name] = $accesskey;
2039 return self::$accesskeycache[$name];
2040 }
2041
2042 /**
2043 * Get a revision-deletion link, or disabled link, or nothing, depending
2044 * on user permissions & the settings on the revision.
2045 *
2046 * Will use forward-compatible revision ID in the Special:RevDelete link
2047 * if possible, otherwise the timestamp-based ID which may break after
2048 * undeletion.
2049 *
2050 * @param User $user
2051 * @param Revision $rev
2052 * @param Title $title
2053 * @return string HTML fragment
2054 */
2055 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2056 $canHide = $user->isAllowed( 'deleterevision' );
2057 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2058 return '';
2059 }
2060
2061 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2062 return self::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2063 } else {
2064 if ( $rev->getId() ) {
2065 // RevDelete links using revision ID are stable across
2066 // page deletion and undeletion; use when possible.
2067 $query = [
2068 'type' => 'revision',
2069 'target' => $title->getPrefixedDBkey(),
2070 'ids' => $rev->getId()
2071 ];
2072 } else {
2073 // Older deleted entries didn't save a revision ID.
2074 // We have to refer to these by timestamp, ick!
2075 $query = [
2076 'type' => 'archive',
2077 'target' => $title->getPrefixedDBkey(),
2078 'ids' => $rev->getTimestamp()
2079 ];
2080 }
2081 return self::revDeleteLink( $query,
2082 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2083 }
2084 }
2085
2086 /**
2087 * Creates a (show/hide) link for deleting revisions/log entries
2088 *
2089 * @param array $query Query parameters to be passed to link()
2090 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2091 * @param bool $delete Set to true to use (show/hide) rather than (show)
2092 *
2093 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2094 * span to allow for customization of appearance with CSS
2095 */
2096 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2097 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2098 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2099 $html = wfMessage( $msgKey )->escaped();
2100 $tag = $restricted ? 'strong' : 'span';
2101 $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2102 return Xml::tags(
2103 $tag,
2104 [ 'class' => 'mw-revdelundel-link' ],
2105 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2106 );
2107 }
2108
2109 /**
2110 * Creates a dead (show/hide) link for deleting revisions/log entries
2111 *
2112 * @since 1.16.3
2113 * @param bool $delete Set to true to use (show/hide) rather than (show)
2114 *
2115 * @return string HTML text wrapped in a span to allow for customization
2116 * of appearance with CSS
2117 */
2118 public static function revDeleteLinkDisabled( $delete = true ) {
2119 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2120 $html = wfMessage( $msgKey )->escaped();
2121 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2122 return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2123 }
2124
2125 /**
2126 * Returns the attributes for the tooltip and access key.
2127 *
2128 * @since 1.16.3. $msgParams introduced in 1.27
2129 * @param string $name
2130 * @param array $msgParams Params for constructing the message
2131 * @param string|array|null $options Options to be passed to titleAttrib.
2132 *
2133 * @see Linker::titleAttrib for what options could be passed to $options.
2134 *
2135 * @return array
2136 */
2137 public static function tooltipAndAccesskeyAttribs(
2138 $name,
2139 array $msgParams = [],
2140 $options = null
2141 ) {
2142 $options = (array)$options;
2143 $options[] = 'withaccess';
2144
2145 $attribs = [
2146 'title' => self::titleAttrib( $name, $options, $msgParams ),
2147 'accesskey' => self::accesskey( $name )
2148 ];
2149 if ( $attribs['title'] === false ) {
2150 unset( $attribs['title'] );
2151 }
2152 if ( $attribs['accesskey'] === false ) {
2153 unset( $attribs['accesskey'] );
2154 }
2155 return $attribs;
2156 }
2157
2158 /**
2159 * Returns raw bits of HTML, use titleAttrib()
2160 * @since 1.16.3
2161 * @param string $name
2162 * @param array|null $options
2163 * @return null|string
2164 */
2165 public static function tooltip( $name, $options = null ) {
2166 $tooltip = self::titleAttrib( $name, $options );
2167 if ( $tooltip === false ) {
2168 return '';
2169 }
2170 return Xml::expandAttributes( [
2171 'title' => $tooltip
2172 ] );
2173 }
2174
2175 }