Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[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 = 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 *
827 * @since 1.16.3. $title added in 1.21
828 * @param string $url URL to link to
829 * @param-taint $url escapes_html
830 * @param string $text Text of link
831 * @param-taint $text escapes_html
832 * @param bool $escape Do we escape the link text?
833 * @param-taint $escape none
834 * @param string $linktype Type of external link. Gets added to the classes
835 * @param-taint $linktype escapes_html
836 * @param array $attribs Array of extra attributes to <a>
837 * @param-taint $attribs escapes_html
838 * @param Title|null $title Title object used for title specific link attributes
839 * @param-taint $title none
840 * @return string
841 */
842 public static function makeExternalLink( $url, $text, $escape = true,
843 $linktype = '', $attribs = [], $title = null
844 ) {
845 global $wgTitle;
846 $class = "external";
847 if ( $linktype ) {
848 $class .= " $linktype";
849 }
850 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
851 $class .= " {$attribs['class']}";
852 }
853 $attribs['class'] = $class;
854
855 if ( $escape ) {
856 $text = htmlspecialchars( $text );
857 }
858
859 if ( !$title ) {
860 $title = $wgTitle;
861 }
862 $newRel = Parser::getExternalLinkRel( $url, $title );
863 if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
864 $attribs['rel'] = $newRel;
865 } elseif ( $newRel !== '' ) {
866 // Merge the rel attributes.
867 $newRels = explode( ' ', $newRel );
868 $oldRels = explode( ' ', $attribs['rel'] );
869 $combined = array_unique( array_merge( $newRels, $oldRels ) );
870 $attribs['rel'] = implode( ' ', $combined );
871 }
872 $link = '';
873 $success = Hooks::run( 'LinkerMakeExternalLink',
874 [ &$url, &$text, &$link, &$attribs, $linktype ] );
875 if ( !$success ) {
876 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
877 . "with url {$url} and text {$text} to {$link}\n", true );
878 return $link;
879 }
880 $attribs['href'] = $url;
881 return Html::rawElement( 'a', $attribs, $text );
882 }
883
884 /**
885 * Make user link (or user contributions for unregistered users)
886 * @param int $userId User id in database.
887 * @param string $userName User name in database.
888 * @param string $altUserName Text to display instead of the user name (optional)
889 * @return string HTML fragment
890 * @since 1.16.3. $altUserName was added in 1.19.
891 */
892 public static function userLink( $userId, $userName, $altUserName = false ) {
893 $classes = 'mw-userlink';
894 $page = null;
895 if ( $userId == 0 ) {
896 $page = ExternalUserNames::getUserLinkTitle( $userName );
897
898 if ( ExternalUserNames::isExternal( $userName ) ) {
899 $classes .= ' mw-extuserlink';
900 } elseif ( $altUserName === false ) {
901 $altUserName = IP::prettifyIP( $userName );
902 }
903 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
904 } else {
905 $page = Title::makeTitle( NS_USER, $userName );
906 }
907
908 // Wrap the output with <bdi> tags for directionality isolation
909 $linkText =
910 '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>';
911
912 return $page
913 ? self::link( $page, $linkText, [ 'class' => $classes ] )
914 : Html::rawElement( 'span', [ 'class' => $classes ], $linkText );
915 }
916
917 /**
918 * Generate standard user tool links (talk, contributions, block link, etc.)
919 *
920 * @since 1.16.3
921 * @param int $userId User identifier
922 * @param string $userText User name or IP address
923 * @param bool $redContribsWhenNoEdits Should the contributions link be
924 * red if the user has no edits?
925 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
926 * and Linker::TOOL_LINKS_EMAIL).
927 * @param int|null $edits User edit count (optional, for performance)
928 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
929 * @return string HTML fragment
930 */
931 public static function userToolLinks(
932 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
933 $useParentheses = true
934 ) {
935 global $wgUser, $wgDisableAnonTalk, $wgLang;
936 $talkable = !( $wgDisableAnonTalk && $userId == 0 );
937 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
938 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
939
940 if ( $userId == 0 && ExternalUserNames::isExternal( $userText ) ) {
941 // No tools for an external user
942 return '';
943 }
944
945 $items = [];
946 if ( $talkable ) {
947 $items[] = self::userTalkLink( $userId, $userText );
948 }
949 if ( $userId ) {
950 // check if the user has an edit
951 $attribs = [];
952 $attribs['class'] = 'mw-usertoollinks-contribs';
953 if ( $redContribsWhenNoEdits ) {
954 if ( intval( $edits ) === 0 && $edits !== 0 ) {
955 $user = User::newFromId( $userId );
956 $edits = $user->getEditCount();
957 }
958 if ( $edits === 0 ) {
959 $attribs['class'] .= ' new';
960 }
961 }
962 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
963
964 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
965 }
966 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
967 $items[] = self::blockLink( $userId, $userText );
968 }
969
970 if ( $addEmailLink && $wgUser->canSendEmail() ) {
971 $items[] = self::emailLink( $userId, $userText );
972 }
973
974 Hooks::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
975
976 if ( !$items ) {
977 return '';
978 }
979
980 if ( $useParentheses ) {
981 return wfMessage( 'word-separator' )->escaped()
982 . '<span class="mw-usertoollinks">'
983 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
984 . '</span>';
985 }
986
987 $tools = [];
988 foreach ( $items as $tool ) {
989 $tools[] = Html::rawElement( 'span', [], $tool );
990 }
991 return ' <span class="mw-usertoollinks mw-changeslist-links">' .
992 implode( ' ', $tools ) . '</span>';
993 }
994
995 /**
996 * Alias for userToolLinks( $userId, $userText, true );
997 * @since 1.16.3
998 * @param int $userId User identifier
999 * @param string $userText User name or IP address
1000 * @param int|null $edits User edit count (optional, for performance)
1001 * @return string
1002 */
1003 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1004 return self::userToolLinks( $userId, $userText, true, 0, $edits, false );
1005 }
1006
1007 /**
1008 * @since 1.16.3
1009 * @param int $userId User id in database.
1010 * @param string $userText User name in database.
1011 * @return string HTML fragment with user talk link
1012 */
1013 public static function userTalkLink( $userId, $userText ) {
1014 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1015 $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
1016
1017 return self::link( $userTalkPage,
1018 wfMessage( 'talkpagelinktext' )->escaped(),
1019 $moreLinkAttribs
1020 );
1021 }
1022
1023 /**
1024 * @since 1.16.3
1025 * @param int $userId
1026 * @param string $userText User name in database.
1027 * @return string HTML fragment with block link
1028 */
1029 public static function blockLink( $userId, $userText ) {
1030 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1031 $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1032
1033 return self::link( $blockPage,
1034 wfMessage( 'blocklink' )->escaped(),
1035 $moreLinkAttribs
1036 );
1037 }
1038
1039 /**
1040 * @param int $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 return self::link( $emailPage,
1048 wfMessage( 'emaillink' )->escaped(),
1049 $moreLinkAttribs
1050 );
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 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1081 * @return string HTML
1082 */
1083 public static function revUserTools( $rev, $isPublic = false, $useParentheses = true ) {
1084 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1085 $link = wfMessage( 'rev-deleted-user' )->escaped();
1086 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1087 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1088 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1089 $link = self::userLink( $userId, $userText )
1090 . self::userToolLinks( $userId, $userText, false, 0, null,
1091 $useParentheses );
1092 } else {
1093 $link = wfMessage( 'rev-deleted-user' )->escaped();
1094 }
1095 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1096 return ' <span class="history-deleted mw-userlink">' . $link . '</span>';
1097 }
1098 return $link;
1099 }
1100
1101 /**
1102 * This function is called by all recent changes variants, by the page history,
1103 * and by the user contributions list. It is responsible for formatting edit
1104 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1105 * auto-generated comments (from section editing) and formats [[wikilinks]].
1106 *
1107 * @author Erik Moeller <moeller@scireview.de>
1108 * @since 1.16.3. $wikiId added in 1.26
1109 *
1110 * @param string $comment
1111 * @param Title|null $title Title object (to generate link to the section in autocomment)
1112 * or null
1113 * @param bool $local Whether section links should refer to local page
1114 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1115 * For use with external changes.
1116 *
1117 * @return string HTML
1118 */
1119 public static function formatComment(
1120 $comment, $title = null, $local = false, $wikiId = null
1121 ) {
1122 # Sanitize text a bit:
1123 $comment = str_replace( "\n", " ", $comment );
1124 # Allow HTML entities (for T15815)
1125 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1126
1127 # Render autocomments and make links:
1128 $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1129 return self::formatLinksInComment( $comment, $title, $local, $wikiId );
1130 }
1131
1132 /**
1133 * Converts autogenerated comments in edit summaries into section links.
1134 *
1135 * The pattern for autogen comments is / * foo * /, which makes for
1136 * some nasty regex.
1137 * We look for all comments, match any text before and after the comment,
1138 * add a separator where needed and format the comment itself with CSS
1139 * Called by Linker::formatComment.
1140 *
1141 * @param string $comment Comment text
1142 * @param Title|null $title An optional title object used to links to sections
1143 * @param bool $local Whether section links should refer to local page
1144 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1145 * as used by WikiMap.
1146 *
1147 * @return string Formatted comment (wikitext)
1148 */
1149 private static function formatAutocomments(
1150 $comment, $title = null, $local = false, $wikiId = null
1151 ) {
1152 // @todo $append here is something of a hack to preserve the status
1153 // quo. Someone who knows more about bidi and such should decide
1154 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1155 // wiki, both when autocomments exist and when they don't, and
1156 // (2) what markup will make that actually happen.
1157 $append = '';
1158 $comment = preg_replace_callback(
1159 // To detect the presence of content before or after the
1160 // auto-comment, we use capturing groups inside optional zero-width
1161 // assertions. But older versions of PCRE can't directly make
1162 // zero-width assertions optional, so wrap them in a non-capturing
1163 // group.
1164 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1165 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1166 global $wgLang;
1167
1168 // Ensure all match positions are defined
1169 $match += [ '', '', '', '' ];
1170
1171 $pre = $match[1] !== '';
1172 $auto = $match[2];
1173 $post = $match[3] !== '';
1174 $comment = null;
1175
1176 Hooks::run(
1177 'FormatAutocomments',
1178 [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1179 );
1180
1181 if ( $comment === null ) {
1182 if ( $title ) {
1183 $section = $auto;
1184 # Remove links that a user may have manually put in the autosummary
1185 # This could be improved by copying as much of Parser::stripSectionName as desired.
1186 $section = str_replace( [
1187 '[[:',
1188 '[[',
1189 ']]'
1190 ], '', $section );
1191
1192 // We don't want any links in the auto text to be linked, but we still
1193 // want to show any [[ ]]
1194 $sectionText = str_replace( '[[', '&#91;[', $auto );
1195
1196 $section = substr( Parser::guessSectionNameFromStrippedText( $section ), 1 );
1197 if ( $local ) {
1198 $sectionTitle = Title::makeTitleSafe( NS_MAIN, '', $section );
1199 } else {
1200 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1201 $title->getDBkey(), $section );
1202 }
1203 if ( $sectionTitle ) {
1204 $auto = Linker::makeCommentLink(
1205 $sectionTitle, $wgLang->getArrow() . $wgLang->getDirMark() . $sectionText,
1206 $wikiId, 'noclasses'
1207 );
1208 }
1209 }
1210 if ( $pre ) {
1211 # written summary $presep autocomment (summary /* section */)
1212 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1213 }
1214 if ( $post ) {
1215 # autocomment $postsep written summary (/* section */ summary)
1216 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1217 }
1218 if ( $auto ) {
1219 $auto = '<span dir="auto"><span class="autocomment">' . $auto . '</span>';
1220 $append .= '</span>';
1221 }
1222 $comment = $pre . $auto;
1223 }
1224 return $comment;
1225 },
1226 $comment
1227 );
1228 return $comment . $append;
1229 }
1230
1231 /**
1232 * Formats wiki links and media links in text; all other wiki formatting
1233 * is ignored
1234 *
1235 * @since 1.16.3. $wikiId added in 1.26
1236 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1237 *
1238 * @param string $comment Text to format links in. WARNING! Since the output of this
1239 * function is html, $comment must be sanitized for use as html. You probably want
1240 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1241 * this function.
1242 * @param Title|null $title An optional title object used to links to sections
1243 * @param bool $local Whether section links should refer to local page
1244 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1245 * as used by WikiMap.
1246 *
1247 * @return string HTML
1248 * @return-taint onlysafefor_html
1249 */
1250 public static function formatLinksInComment(
1251 $comment, $title = null, $local = false, $wikiId = null
1252 ) {
1253 return preg_replace_callback(
1254 '/
1255 \[\[
1256 \s*+ # ignore leading whitespace, the *+ quantifier disallows backtracking
1257 :? # ignore optional leading colon
1258 ([^\]|]+) # 1. link target; page names cannot include ] or |
1259 (?:\|
1260 # 2. link text
1261 # Stop matching at ]] without relying on backtracking.
1262 ((?:]?[^\]])*+)
1263 )?
1264 \]\]
1265 ([^[]*) # 3. link trail (the text up until the next link)
1266 /x',
1267 function ( $match ) use ( $title, $local, $wikiId ) {
1268 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1269 $medians .= preg_quote(
1270 MediaWikiServices::getInstance()->getContentLanguage()->getNsText( NS_MEDIA ),
1271 '/'
1272 ) . '):';
1273
1274 $comment = $match[0];
1275
1276 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1277 if ( strpos( $match[1], '%' ) !== false ) {
1278 $match[1] = strtr(
1279 rawurldecode( $match[1] ),
1280 [ '<' => '&lt;', '>' => '&gt;' ]
1281 );
1282 }
1283
1284 # Handle link renaming [[foo|text]] will show link as "text"
1285 if ( $match[2] != "" ) {
1286 $text = $match[2];
1287 } else {
1288 $text = $match[1];
1289 }
1290 $submatch = [];
1291 $thelink = null;
1292 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1293 # Media link; trail not supported.
1294 $linkRegexp = '/\[\[(.*?)\]\]/';
1295 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1296 if ( $title ) {
1297 $thelink = Linker::makeMediaLinkObj( $title, $text );
1298 }
1299 } else {
1300 # Other kind of link
1301 # Make sure its target is non-empty
1302 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1303 $match[1] = substr( $match[1], 1 );
1304 }
1305 if ( $match[1] !== false && $match[1] !== '' ) {
1306 if ( preg_match(
1307 MediaWikiServices::getInstance()->getContentLanguage()->linkTrail(),
1308 $match[3],
1309 $submatch
1310 ) ) {
1311 $trail = $submatch[1];
1312 } else {
1313 $trail = "";
1314 }
1315 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1316 list( $inside, $trail ) = Linker::splitTrail( $trail );
1317
1318 $linkText = $text;
1319 $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1320
1321 $target = Title::newFromText( $linkTarget );
1322 if ( $target ) {
1323 if ( $target->getText() == '' && !$target->isExternal()
1324 && !$local && $title
1325 ) {
1326 $target = $title->createFragmentTarget( $target->getFragment() );
1327 }
1328
1329 $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1330 }
1331 }
1332 }
1333 if ( $thelink ) {
1334 // If the link is still valid, go ahead and replace it in!
1335 $comment = preg_replace(
1336 $linkRegexp,
1337 StringUtils::escapeRegexReplacement( $thelink ),
1338 $comment,
1339 1
1340 );
1341 }
1342
1343 return $comment;
1344 },
1345 $comment
1346 );
1347 }
1348
1349 /**
1350 * Generates a link to the given Title
1351 *
1352 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1353 *
1354 * @param LinkTarget $linkTarget
1355 * @param string $text
1356 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1357 * as used by WikiMap.
1358 * @param string|string[] $options See the $options parameter in Linker::link.
1359 *
1360 * @return string HTML link
1361 */
1362 public static function makeCommentLink(
1363 LinkTarget $linkTarget, $text, $wikiId = null, $options = []
1364 ) {
1365 if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1366 $link = self::makeExternalLink(
1367 WikiMap::getForeignURL(
1368 $wikiId,
1369 $linkTarget->getNamespace() === 0
1370 ? $linkTarget->getDBkey()
1371 : MWNamespace::getCanonicalName( $linkTarget->getNamespace() ) . ':'
1372 . $linkTarget->getDBkey(),
1373 $linkTarget->getFragment()
1374 ),
1375 $text,
1376 /* escape = */ false // Already escaped
1377 );
1378 } else {
1379 $link = self::link( $linkTarget, $text, [], [], $options );
1380 }
1381
1382 return $link;
1383 }
1384
1385 /**
1386 * @param Title $contextTitle
1387 * @param string $target
1388 * @param string &$text
1389 * @return string
1390 */
1391 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1392 # Valid link forms:
1393 # Foobar -- normal
1394 # :Foobar -- override special treatment of prefix (images, language links)
1395 # /Foobar -- convert to CurrentPage/Foobar
1396 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1397 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1398 # ../Foobar -- convert to CurrentPage/Foobar,
1399 # (from CurrentPage/CurrentSubPage)
1400 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1401 # (from CurrentPage/CurrentSubPage)
1402
1403 $ret = $target; # default return value is no change
1404
1405 # Some namespaces don't allow subpages,
1406 # so only perform processing if subpages are allowed
1407 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1408 $hash = strpos( $target, '#' );
1409 if ( $hash !== false ) {
1410 $suffix = substr( $target, $hash );
1411 $target = substr( $target, 0, $hash );
1412 } else {
1413 $suffix = '';
1414 }
1415 # T9425
1416 $target = trim( $target );
1417 # Look at the first character
1418 if ( $target != '' && $target[0] === '/' ) {
1419 # / at end means we don't want the slash to be shown
1420 $m = [];
1421 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1422 if ( $trailingSlashes ) {
1423 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1424 } else {
1425 $noslash = substr( $target, 1 );
1426 }
1427
1428 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1429 if ( $text === '' ) {
1430 $text = $target . $suffix;
1431 } # this might be changed for ugliness reasons
1432 } else {
1433 # check for .. subpage backlinks
1434 $dotdotcount = 0;
1435 $nodotdot = $target;
1436 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1437 ++$dotdotcount;
1438 $nodotdot = substr( $nodotdot, 3 );
1439 }
1440 if ( $dotdotcount > 0 ) {
1441 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1442 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1443 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1444 # / at the end means don't show full path
1445 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1446 $nodotdot = rtrim( $nodotdot, '/' );
1447 if ( $text === '' ) {
1448 $text = $nodotdot . $suffix;
1449 }
1450 }
1451 $nodotdot = trim( $nodotdot );
1452 if ( $nodotdot != '' ) {
1453 $ret .= '/' . $nodotdot;
1454 }
1455 $ret .= $suffix;
1456 }
1457 }
1458 }
1459 }
1460
1461 return $ret;
1462 }
1463
1464 /**
1465 * Wrap a comment in standard punctuation and formatting if
1466 * it's non-empty, otherwise return empty string.
1467 *
1468 * @since 1.16.3. $wikiId added in 1.26
1469 * @param string $comment
1470 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1471 * @param bool $local Whether section links should refer to local page
1472 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1473 * For use with external changes.
1474 *
1475 * @return string
1476 */
1477 public static function commentBlock(
1478 $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1479 ) {
1480 // '*' used to be the comment inserted by the software way back
1481 // in antiquity in case none was provided, here for backwards
1482 // compatibility, acc. to brion -ævar
1483 if ( $comment == '' || $comment == '*' ) {
1484 return '';
1485 }
1486 $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1487 if ( $useParentheses ) {
1488 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1489 $classNames = 'comment';
1490 } else {
1491 $classNames = 'comment comment--without-parentheses';
1492 }
1493 return " <span class=\"$classNames\">$formatted</span>";
1494 }
1495
1496 /**
1497 * Wrap and format the given revision's comment block, if the current
1498 * user is allowed to view it.
1499 *
1500 * @since 1.16.3
1501 * @param Revision $rev
1502 * @param bool $local Whether section links should refer to local page
1503 * @param bool $isPublic Show only if all users can see it
1504 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1505 * @return string HTML fragment
1506 */
1507 public static function revComment( Revision $rev, $local = false, $isPublic = false,
1508 $useParentheses = true
1509 ) {
1510 if ( $rev->getComment( Revision::RAW ) == "" ) {
1511 return "";
1512 }
1513 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1514 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1515 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1516 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1517 $rev->getTitle(), $local, null, $useParentheses );
1518 } else {
1519 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1520 }
1521 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1522 return " <span class=\"history-deleted comment\">$block</span>";
1523 }
1524 return $block;
1525 }
1526
1527 /**
1528 * @since 1.16.3
1529 * @param int $size
1530 * @return string
1531 */
1532 public static function formatRevisionSize( $size ) {
1533 if ( $size == 0 ) {
1534 $stxt = wfMessage( 'historyempty' )->escaped();
1535 } else {
1536 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1537 }
1538 return "<span class=\"history-size mw-diff-bytes\">$stxt</span>";
1539 }
1540
1541 /**
1542 * Add another level to the Table of Contents
1543 *
1544 * @since 1.16.3
1545 * @return string
1546 */
1547 public static function tocIndent() {
1548 return "\n<ul>\n";
1549 }
1550
1551 /**
1552 * Finish one or more sublevels on the Table of Contents
1553 *
1554 * @since 1.16.3
1555 * @param int $level
1556 * @return string
1557 */
1558 public static function tocUnindent( $level ) {
1559 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1560 }
1561
1562 /**
1563 * parameter level defines if we are on an indentation level
1564 *
1565 * @since 1.16.3
1566 * @param string $anchor
1567 * @param string $tocline
1568 * @param string $tocnumber
1569 * @param string $level
1570 * @param string|bool $sectionIndex
1571 * @return string
1572 */
1573 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1574 $classes = "toclevel-$level";
1575 if ( $sectionIndex !== false ) {
1576 $classes .= " tocsection-$sectionIndex";
1577 }
1578
1579 // <li class="$classes"><a href="#$anchor"><span class="tocnumber">
1580 // $tocnumber</span> <span class="toctext">$tocline</span></a>
1581 return Html::openElement( 'li', [ 'class' => $classes ] )
1582 . Html::rawElement( 'a',
1583 [ 'href' => "#$anchor" ],
1584 Html::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1585 . ' '
1586 . Html::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1587 );
1588 }
1589
1590 /**
1591 * End a Table Of Contents line.
1592 * tocUnindent() will be used instead if we're ending a line below
1593 * the new level.
1594 * @since 1.16.3
1595 * @return string
1596 */
1597 public static function tocLineEnd() {
1598 return "</li>\n";
1599 }
1600
1601 /**
1602 * Wraps the TOC in a table and provides the hide/collapse javascript.
1603 *
1604 * @since 1.16.3
1605 * @param string $toc Html of the Table Of Contents
1606 * @param string|Language|bool|null $lang Language for the toc title, defaults to user language.
1607 * The types string and bool are deprecated.
1608 * @return string Full html of the TOC
1609 */
1610 public static function tocList( $toc, $lang = null ) {
1611 $lang = $lang ?? RequestContext::getMain()->getLanguage();
1612 if ( !$lang instanceof Language ) {
1613 wfDeprecated( __METHOD__ . ' with type other than Language for $lang', '1.33' );
1614 $lang = wfGetLangObj( $lang );
1615 }
1616
1617 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1618
1619 return '<div id="toc" class="toc">'
1620 . Html::element( 'input', [
1621 'type' => 'checkbox',
1622 'role' => 'button',
1623 'id' => 'toctogglecheckbox',
1624 'class' => 'toctogglecheckbox',
1625 'style' => 'display:none',
1626 ] )
1627 . Html::openElement( 'div', [
1628 'class' => 'toctitle',
1629 'lang' => $lang->getHtmlCode(),
1630 'dir' => $lang->getDir(),
1631 ] )
1632 . "<h2>$title</h2>"
1633 . '<span class="toctogglespan">'
1634 . Html::label( '', 'toctogglecheckbox', [
1635 'class' => 'toctogglelabel',
1636 ] )
1637 . '</span>'
1638 . "</div>\n"
1639 . $toc
1640 . "</ul>\n</div>\n";
1641 }
1642
1643 /**
1644 * Generate a table of contents from a section tree.
1645 *
1646 * @since 1.16.3. $lang added in 1.17
1647 * @param array $tree Return value of ParserOutput::getSections()
1648 * @param string|Language|bool|null $lang Language for the toc title, defaults to user language.
1649 * The types string and bool are deprecated.
1650 * @return string HTML fragment
1651 */
1652 public static function generateTOC( $tree, $lang = null ) {
1653 $toc = '';
1654 $lastLevel = 0;
1655 foreach ( $tree as $section ) {
1656 if ( $section['toclevel'] > $lastLevel ) {
1657 $toc .= self::tocIndent();
1658 } elseif ( $section['toclevel'] < $lastLevel ) {
1659 $toc .= self::tocUnindent(
1660 $lastLevel - $section['toclevel'] );
1661 } else {
1662 $toc .= self::tocLineEnd();
1663 }
1664
1665 $toc .= self::tocLine( $section['anchor'],
1666 $section['line'], $section['number'],
1667 $section['toclevel'], $section['index'] );
1668 $lastLevel = $section['toclevel'];
1669 }
1670 $toc .= self::tocLineEnd();
1671 return self::tocList( $toc, $lang );
1672 }
1673
1674 /**
1675 * Create a headline for content
1676 *
1677 * @since 1.16.3
1678 * @param int $level The level of the headline (1-6)
1679 * @param string $attribs Any attributes for the headline, starting with
1680 * a space and ending with '>'
1681 * This *must* be at least '>' for no attribs
1682 * @param string $anchor The anchor to give the headline (the bit after the #)
1683 * @param string $html HTML for the text of the header
1684 * @param string $link HTML to add for the section edit link
1685 * @param string|bool $fallbackAnchor A second, optional anchor to give for
1686 * backward compatibility (false to omit)
1687 *
1688 * @return string HTML headline
1689 */
1690 public static function makeHeadline( $level, $attribs, $anchor, $html,
1691 $link, $fallbackAnchor = false
1692 ) {
1693 $anchorEscaped = htmlspecialchars( $anchor );
1694 $fallback = '';
1695 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1696 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1697 $fallback = "<span id=\"$fallbackAnchor\"></span>";
1698 }
1699 return "<h$level$attribs"
1700 . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1701 . $link
1702 . "</h$level>";
1703 }
1704
1705 /**
1706 * Split a link trail, return the "inside" portion and the remainder of the trail
1707 * as a two-element array
1708 * @param string $trail
1709 * @return array
1710 */
1711 static function splitTrail( $trail ) {
1712 $regex = MediaWikiServices::getInstance()->getContentLanguage()->linkTrail();
1713 $inside = '';
1714 if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1715 list( , $inside, $trail ) = $m;
1716 }
1717 return [ $inside, $trail ];
1718 }
1719
1720 /**
1721 * Generate a rollback link for a given revision. Currently it's the
1722 * caller's responsibility to ensure that the revision is the top one. If
1723 * it's not, of course, the user will get an error message.
1724 *
1725 * If the calling page is called with the parameter &bot=1, all rollback
1726 * links also get that parameter. It causes the edit itself and the rollback
1727 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1728 * changes, so this allows sysops to combat a busy vandal without bothering
1729 * other users.
1730 *
1731 * If the option verify is set this function will return the link only in case the
1732 * revision can be reverted. Please note that due to performance limitations
1733 * it might be assumed that a user isn't the only contributor of a page while
1734 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1735 * work if $wgShowRollbackEditCount is disabled, so this can only function
1736 * as an additional check.
1737 *
1738 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1739 *
1740 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1741 *
1742 * @param Revision $rev
1743 * @param IContextSource|null $context Context to use or null for the main context.
1744 * @param array $options
1745 * @return string
1746 */
1747 public static function generateRollback( $rev, IContextSource $context = null,
1748 $options = [ 'verify' ]
1749 ) {
1750 if ( $context === null ) {
1751 $context = RequestContext::getMain();
1752 }
1753
1754 $editCount = false;
1755 if ( in_array( 'verify', $options, true ) ) {
1756 $editCount = self::getRollbackEditCount( $rev, true );
1757 if ( $editCount === false ) {
1758 return '';
1759 }
1760 }
1761
1762 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1763
1764 if ( !in_array( 'noBrackets', $options, true ) ) {
1765 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1766 }
1767
1768 if ( $context->getUser()->getBoolOption( 'showrollbackconfirmation' ) ) {
1769 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1770 $stats->increment( 'rollbackconfirmation.event.load' );
1771 $context->getOutput()->addModules( 'mediawiki.page.rollback.confirmation' );
1772 }
1773
1774 return '<span class="mw-rollback-link">' . $inner . '</span>';
1775 }
1776
1777 /**
1778 * This function will return the number of revisions which a rollback
1779 * would revert and, if $verify is set it will verify that a revision
1780 * can be reverted (that the user isn't the only contributor and the
1781 * revision we might rollback to isn't deleted). These checks can only
1782 * function as an additional check as this function only checks against
1783 * the last $wgShowRollbackEditCount edits.
1784 *
1785 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1786 * is set and the user is the only contributor of the page.
1787 *
1788 * @param Revision $rev
1789 * @param bool $verify Try to verify that this revision can really be rolled back
1790 * @return int|bool|null
1791 */
1792 public static function getRollbackEditCount( $rev, $verify ) {
1793 global $wgShowRollbackEditCount;
1794 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1795 // Nothing has happened, indicate this by returning 'null'
1796 return null;
1797 }
1798
1799 $dbr = wfGetDB( DB_REPLICA );
1800
1801 // Up to the value of $wgShowRollbackEditCount revisions are counted
1802 $revQuery = Revision::getQueryInfo();
1803 $res = $dbr->select(
1804 $revQuery['tables'],
1805 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1806 // $rev->getPage() returns null sometimes
1807 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1808 __METHOD__,
1809 [
1810 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1811 'ORDER BY' => 'rev_timestamp DESC',
1812 'LIMIT' => $wgShowRollbackEditCount + 1
1813 ],
1814 $revQuery['joins']
1815 );
1816
1817 $editCount = 0;
1818 $moreRevs = false;
1819 foreach ( $res as $row ) {
1820 if ( $rev->getUserText( Revision::RAW ) != $row->rev_user_text ) {
1821 if ( $verify &&
1822 ( $row->rev_deleted & Revision::DELETED_TEXT
1823 || $row->rev_deleted & Revision::DELETED_USER
1824 ) ) {
1825 // If the user or the text of the revision we might rollback
1826 // to is deleted in some way we can't rollback. Similar to
1827 // the sanity checks in WikiPage::commitRollback.
1828 return false;
1829 }
1830 $moreRevs = true;
1831 break;
1832 }
1833 $editCount++;
1834 }
1835
1836 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1837 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1838 // and there weren't any other revisions. That means that the current user is the only
1839 // editor, so we can't rollback
1840 return false;
1841 }
1842 return $editCount;
1843 }
1844
1845 /**
1846 * Build a raw rollback link, useful for collections of "tool" links
1847 *
1848 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1849 * @param Revision $rev
1850 * @param IContextSource|null $context Context to use or null for the main context.
1851 * @param int $editCount Number of edits that would be reverted
1852 * @return string HTML fragment
1853 */
1854 public static function buildRollbackLink( $rev, IContextSource $context = null,
1855 $editCount = false
1856 ) {
1857 global $wgShowRollbackEditCount, $wgMiserMode;
1858
1859 // To config which pages are affected by miser mode
1860 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1861
1862 if ( $context === null ) {
1863 $context = RequestContext::getMain();
1864 }
1865
1866 $title = $rev->getTitle();
1867
1868 $query = [
1869 'action' => 'rollback',
1870 'from' => $rev->getUserText(),
1871 'token' => $context->getUser()->getEditToken( 'rollback' ),
1872 ];
1873
1874 $attrs = [
1875 'data-mw' => 'interface',
1876 'title' => $context->msg( 'tooltip-rollback' )->text()
1877 ];
1878
1879 $options = [ 'known', 'noclasses' ];
1880
1881 if ( $context->getRequest()->getBool( 'bot' ) ) {
1882 //T17999
1883 $query['hidediff'] = '1';
1884 $query['bot'] = '1';
1885 }
1886
1887 $disableRollbackEditCount = false;
1888 if ( $wgMiserMode ) {
1889 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1890 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1891 $disableRollbackEditCount = true;
1892 break;
1893 }
1894 }
1895 }
1896
1897 if ( !$disableRollbackEditCount
1898 && is_int( $wgShowRollbackEditCount )
1899 && $wgShowRollbackEditCount > 0
1900 ) {
1901 if ( !is_numeric( $editCount ) ) {
1902 $editCount = self::getRollbackEditCount( $rev, false );
1903 }
1904
1905 if ( $editCount > $wgShowRollbackEditCount ) {
1906 $html = $context->msg( 'rollbacklinkcount-morethan' )
1907 ->numParams( $wgShowRollbackEditCount )->parse();
1908 } else {
1909 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1910 }
1911
1912 return self::link( $title, $html, $attrs, $query, $options );
1913 }
1914
1915 $html = $context->msg( 'rollbacklink' )->escaped();
1916 return self::link( $title, $html, $attrs, $query, $options );
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 * Given the id of an interface element, constructs the appropriate title
1948 * attribute from the system messages. (Note, this is usually the id but
1949 * isn't always, because sometimes the accesskey needs to go on a different
1950 * element than the id, for reverse-compatibility, etc.)
1951 *
1952 * @since 1.16.3 $msgParams added in 1.27
1953 * @param string $name Id of the element, minus prefixes.
1954 * @param string|array|null $options Null, string or array with some of the following options:
1955 * - 'withaccess' to add an access-key hint
1956 * - 'nonexisting' to add an accessibility hint that page does not exist
1957 * @param array $msgParams Parameters to pass to the message
1958 *
1959 * @return string Contents of the title attribute (which you must HTML-
1960 * escape), or false for no title attribute
1961 */
1962 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
1963 $message = wfMessage( "tooltip-$name", $msgParams );
1964 if ( !$message->exists() ) {
1965 $tooltip = false;
1966 } else {
1967 $tooltip = $message->text();
1968 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1969 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1970 # Message equal to '-' means suppress it.
1971 if ( $tooltip == '-' ) {
1972 $tooltip = false;
1973 }
1974 }
1975
1976 $options = (array)$options;
1977
1978 if ( in_array( 'nonexisting', $options ) ) {
1979 $tooltip = wfMessage( 'red-link-title', $tooltip ?: '' )->text();
1980 }
1981 if ( in_array( 'withaccess', $options ) ) {
1982 $accesskey = self::accesskey( $name );
1983 if ( $accesskey !== false ) {
1984 // Should be build the same as in jquery.accessKeyLabel.js
1985 if ( $tooltip === false || $tooltip === '' ) {
1986 $tooltip = wfMessage( 'brackets', $accesskey )->text();
1987 } else {
1988 $tooltip .= wfMessage( 'word-separator' )->text();
1989 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
1990 }
1991 }
1992 }
1993
1994 return $tooltip;
1995 }
1996
1997 public static $accesskeycache;
1998
1999 /**
2000 * Given the id of an interface element, constructs the appropriate
2001 * accesskey attribute from the system messages. (Note, this is usually
2002 * the id but isn't always, because sometimes the accesskey needs to go on
2003 * a different element than the id, for reverse-compatibility, etc.)
2004 *
2005 * @since 1.16.3
2006 * @param string $name Id of the element, minus prefixes.
2007 * @return string Contents of the accesskey attribute (which you must HTML-
2008 * escape), or false for no accesskey attribute
2009 */
2010 public static function accesskey( $name ) {
2011 if ( isset( self::$accesskeycache[$name] ) ) {
2012 return self::$accesskeycache[$name];
2013 }
2014
2015 $message = wfMessage( "accesskey-$name" );
2016
2017 if ( !$message->exists() ) {
2018 $accesskey = false;
2019 } else {
2020 $accesskey = $message->plain();
2021 if ( $accesskey === '' || $accesskey === '-' ) {
2022 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2023 # attribute, but this is broken for accesskey: that might be a useful
2024 # value.
2025 $accesskey = false;
2026 }
2027 }
2028
2029 self::$accesskeycache[$name] = $accesskey;
2030 return self::$accesskeycache[$name];
2031 }
2032
2033 /**
2034 * Get a revision-deletion link, or disabled link, or nothing, depending
2035 * on user permissions & the settings on the revision.
2036 *
2037 * Will use forward-compatible revision ID in the Special:RevDelete link
2038 * if possible, otherwise the timestamp-based ID which may break after
2039 * undeletion.
2040 *
2041 * @param User $user
2042 * @param Revision $rev
2043 * @param Title $title
2044 * @return string HTML fragment
2045 */
2046 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2047 $canHide = $user->isAllowed( 'deleterevision' );
2048 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2049 return '';
2050 }
2051
2052 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2053 return self::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2054 }
2055 if ( $rev->getId() ) {
2056 // RevDelete links using revision ID are stable across
2057 // page deletion and undeletion; use when possible.
2058 $query = [
2059 'type' => 'revision',
2060 'target' => $title->getPrefixedDBkey(),
2061 'ids' => $rev->getId()
2062 ];
2063 } else {
2064 // Older deleted entries didn't save a revision ID.
2065 // We have to refer to these by timestamp, ick!
2066 $query = [
2067 'type' => 'archive',
2068 'target' => $title->getPrefixedDBkey(),
2069 'ids' => $rev->getTimestamp()
2070 ];
2071 }
2072 return self::revDeleteLink( $query,
2073 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2074 }
2075
2076 /**
2077 * Creates a (show/hide) link for deleting revisions/log entries
2078 *
2079 * @param array $query Query parameters to be passed to link()
2080 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2081 * @param bool $delete Set to true to use (show/hide) rather than (show)
2082 *
2083 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2084 * span to allow for customization of appearance with CSS
2085 */
2086 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2087 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2088 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2089 $html = wfMessage( $msgKey )->escaped();
2090 $tag = $restricted ? 'strong' : 'span';
2091 $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2092 return Xml::tags(
2093 $tag,
2094 [ 'class' => 'mw-revdelundel-link' ],
2095 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2096 );
2097 }
2098
2099 /**
2100 * Creates a dead (show/hide) link for deleting revisions/log entries
2101 *
2102 * @since 1.16.3
2103 * @param bool $delete Set to true to use (show/hide) rather than (show)
2104 *
2105 * @return string HTML text wrapped in a span to allow for customization
2106 * of appearance with CSS
2107 */
2108 public static function revDeleteLinkDisabled( $delete = true ) {
2109 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2110 $html = wfMessage( $msgKey )->escaped();
2111 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2112 return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2113 }
2114
2115 /**
2116 * Returns the attributes for the tooltip and access key.
2117 *
2118 * @since 1.16.3. $msgParams introduced in 1.27
2119 * @param string $name
2120 * @param array $msgParams Params for constructing the message
2121 * @param string|array|null $options Options to be passed to titleAttrib.
2122 *
2123 * @see Linker::titleAttrib for what options could be passed to $options.
2124 *
2125 * @return array
2126 */
2127 public static function tooltipAndAccesskeyAttribs(
2128 $name,
2129 array $msgParams = [],
2130 $options = null
2131 ) {
2132 $options = (array)$options;
2133 $options[] = 'withaccess';
2134
2135 $attribs = [
2136 'title' => self::titleAttrib( $name, $options, $msgParams ),
2137 'accesskey' => self::accesskey( $name )
2138 ];
2139 if ( $attribs['title'] === false ) {
2140 unset( $attribs['title'] );
2141 }
2142 if ( $attribs['accesskey'] === false ) {
2143 unset( $attribs['accesskey'] );
2144 }
2145 return $attribs;
2146 }
2147
2148 /**
2149 * Returns raw bits of HTML, use titleAttrib()
2150 * @since 1.16.3
2151 * @param string $name
2152 * @param array|null $options
2153 * @return null|string
2154 */
2155 public static function tooltip( $name, $options = null ) {
2156 $tooltip = self::titleAttrib( $name, $options );
2157 if ( $tooltip === false ) {
2158 return '';
2159 }
2160 return Xml::expandAttributes( [
2161 'title' => $tooltip
2162 ] );
2163 }
2164
2165 }