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