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