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