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