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