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