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