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