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