Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
8.72% covered (danger)
8.72%
72 / 826
8.89% covered (danger)
8.89%
4 / 45
CRAP
0.00% covered (danger)
0.00%
0 / 1
Linker
8.72% covered (danger)
8.72%
72 / 826
8.89% covered (danger)
8.89%
4 / 45
72934.79
0.00% covered (danger)
0.00%
0 / 1
 link
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
42
 linkKnown
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 makeSelfLinkObj
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 getInvalidTitleDescription
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 fnamePart
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 makeExternalImage
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 makeImageLink
0.00% covered (danger)
0.00%
0 / 119
0.00% covered (danger)
0.00%
0 / 1
3306
 getImageLinkMTOParams
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
110
 makeThumbLinkObj
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
 makeThumbLink2
0.00% covered (danger)
0.00%
0 / 123
0.00% covered (danger)
0.00%
0 / 1
2450
 processResponsiveImages
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
72
 makeBrokenImageLinkObj
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
156
 getUploadUrl
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
 makeMediaLinkObj
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 makeMediaLinkFile
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
30
 specialLink
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
4
 makeExternalLink
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 userLink
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 userToolLinkArray
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
240
 renderUserToolLinksArray
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 userToolLinks
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 userToolLinksRedContribs
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 userTalkLink
40.00% covered (danger)
40.00%
4 / 10
0.00% covered (danger)
0.00%
0 / 1
4.94
 blockLink
40.00% covered (danger)
40.00%
4 / 10
0.00% covered (danger)
0.00%
0 / 1
2.86
 emailLink
40.00% covered (danger)
40.00%
4 / 10
0.00% covered (danger)
0.00%
0 / 1
2.86
 revUserLink
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 getRevisionDeletedClass
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 revUserTools
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
20
 expandLocalLinks
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 normalizeSubpageLink
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
210
 formatRevisionSize
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 splitTrail
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 generateRollback
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
5.06
 getRollbackEditCount
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
132
 buildRollbackLink
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
132
 formatHiddenCategories
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 getContextFromMain
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 titleAttrib
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
132
 accesskey
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
 getRevDeleteLink
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
42
 revDeleteLink
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 revDeleteLinkDisabled
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 tooltipAndAccesskeyAttribs
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 tooltip
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 getLinkRenderer
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * Methods to make links and related items.
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace MediaWiki\Linker;
10
11use MediaWiki\Context\ContextSource;
12use MediaWiki\Context\DerivativeContext;
13use MediaWiki\Context\IContextSource;
14use MediaWiki\Context\RequestContext;
15use MediaWiki\FileRepo\File\File;
16use MediaWiki\HookContainer\HookRunner;
17use MediaWiki\Html\Html;
18use MediaWiki\Html\HtmlHelper;
19use MediaWiki\Language\MessageLocalizer;
20use MediaWiki\MainConfigNames;
21use MediaWiki\Media\MediaTransformError;
22use MediaWiki\Media\MediaTransformOutput;
23use MediaWiki\MediaWikiServices;
24use MediaWiki\Message\Message;
25use MediaWiki\Parser\Parser;
26use MediaWiki\Permissions\Authority;
27use MediaWiki\Revision\RevisionRecord;
28use MediaWiki\SpecialPage\SpecialPage;
29use MediaWiki\Title\Title;
30use MediaWiki\Title\TitleValue;
31use MediaWiki\User\ExternalUserNames;
32use MediaWiki\User\UserIdentityValue;
33use Wikimedia\Assert\Assert;
34use Wikimedia\HtmlArmor\HtmlArmor;
35use Wikimedia\Parsoid\Core\LinkTarget as ParsoidLinkTarget;
36use Wikimedia\Rdbms\SelectQueryBuilder;
37use Wikimedia\RemexHtml\Serializer\SerializerNode;
38
39/**
40 * Some internal bits split of from Skin.php. These functions are used
41 * for primarily page content: links, embedded images, table of contents. Links
42 * are also used in the skin.
43 *
44 * @todo turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
45 *
46 * @ingroup Skins
47 */
48class Linker {
49    /**
50     * Flags for userToolLinks()
51     */
52    public const TOOL_LINKS_NOBLOCK = 1;
53    public const TOOL_LINKS_EMAIL = 2;
54
55    /**
56     * This function returns an HTML link to the given target.  It serves a few
57     * purposes:
58     *   1) If $target is a LinkTarget, the correct URL to link to will be figured
59     *      out automatically.
60     *   2) It automatically adds the usual classes for various types of link
61     *      targets: "new" for red links, "stub" for short articles, etc.
62     *   3) It escapes all attribute values safely so there's no risk of XSS.
63     *   4) It provides a default tooltip if the target is a LinkTarget (the page
64     *      name of the target).
65     * link() replaces the old functions in the makeLink() family.
66     *
67     * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
68     * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
69     *
70     * @param LinkTarget $target Can currently only be a LinkTarget, but this may
71     *   change to support Images, literal URLs, etc.
72     * @param string|null $html The HTML contents of the <a> element, i.e.,
73     *   the link text.  This is raw HTML and will not be escaped.  If null,
74     *   defaults to the prefixed text of the LinkTarget; or if the LinkTarget is just a
75     *   fragment, the contents of the fragment.
76     * @param array $customAttribs A key => value array of extra HTML attributes,
77     *   such as title and class.  (href is ignored.)  Classes will be
78     *   merged with the default classes, while other attributes will replace
79     *   default attributes.  All passed attribute values will be HTML-escaped.
80     *   A false attribute value means to suppress that attribute.
81     * @param array $query The query string to append to the URL
82     *   you're linking to, in key => value array form.  Query keys and values
83     *   will be URL-encoded.
84     * @param string|array $options String or array of strings:
85     *     'known': Page is known to exist, so don't check if it does.
86     *     'broken': Page is known not to exist, so don't check if it does.
87     *     'noclasses': Don't add any classes automatically (includes "new",
88     *       "stub", "mw-redirect", "extiw").  Only use the class attribute
89     *       provided, if any, so you get a simple blue link with no icons.
90     *     'forcearticlepath': Use the article path always, even with a querystring.
91     *       Has compatibility issues on some setups, so avoid wherever possible.
92     *     'http': Force a full URL with http:// as the scheme.
93     *     'https': Force a full URL with https:// as the scheme.
94     * @return string HTML <a> attribute
95     */
96    public static function link(
97        $target, $html = null, $customAttribs = [], $query = [], $options = []
98    ) {
99        if ( !$target instanceof LinkTarget ) {
100            wfWarn( __METHOD__ . ': Requires $target to be a LinkTarget object.', 2 );
101            return "<!-- ERROR -->$html";
102        }
103
104        $options = (array)$options;
105        $linkRenderer = self::getLinkRenderer( $options );
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-taint $target none
136     * @param string|null $html
137     * @param-taint $html exec_html
138     * @param array $customAttribs
139     * @param-taint $customAttribs none
140     * @param array $query
141     * @param-taint $query none
142     * @param string|array $options
143     * @param-taint $options none
144     * @return string
145     * @return-taint escaped
146     */
147    public static function linkKnown(
148        $target, $html = null, $customAttribs = [], $query = [], $options = [ 'known' ]
149    ) {
150        wfDeprecated( __METHOD__, '1.28' ); // since 1.47
151        return self::getLinkRenderer( $options )->makeKnownLink( $target, $html, $customAttribs, $query );
152    }
153
154    /**
155     * Make appropriate markup for a link to the current article. This is since
156     * MediaWiki 1.29.0 rendered as an <a> tag without an href and with a class
157     * showing the link text. The calling sequence is the same as for the other
158     * make*LinkObj static functions, but $query is not used.
159     *
160     * @since 1.16.3
161     * @param LinkTarget $nt
162     * @param string $html
163     * @param string $query
164     * @param string $trail
165     * @param string $prefix
166     * @param string $hash hash fragment since 1.40. Should be properly escaped using
167     *   Sanitizer::escapeIdForLink before being passed to this function.
168     *
169     * @return string
170     */
171    public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '', $hash = '' ) {
172        $nt = Title::newFromLinkTarget( $nt );
173        $attrs = [];
174        if ( $hash ) {
175            $attrs['class'] = 'mw-selflink-fragment';
176            $attrs['href'] = '#' . $hash;
177        } else {
178            // For backwards compatibility with gadgets we add selflink as well.
179            $attrs['class'] = 'mw-selflink selflink';
180        }
181        $ret = Html::rawElement( 'a', $attrs, $prefix . $html ) . $trail;
182        $hookRunner = new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
183        if ( !$hookRunner->onSelfLinkBegin( $nt, $html, $trail, $prefix, $ret ) ) {
184            return $ret;
185        }
186
187        if ( $html == '' ) {
188            $html = htmlspecialchars( $nt->getPrefixedText() );
189        }
190        [ $inside, $trail ] = self::splitTrail( $trail );
191        return Html::rawElement( 'a', $attrs, $prefix . $html . $inside ) . $trail;
192    }
193
194    /**
195     * Get a message saying that an invalid title was encountered.
196     * This should be called after a method like Title::makeTitleSafe() returned
197     * a value indicating that the title object is invalid.
198     *
199     * @param IContextSource $context Context to use to get the messages
200     * @param int $namespace Namespace number
201     * @param string $title Text of the title, without the namespace part
202     * @return string
203     */
204    public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
205        // First we check whether the namespace exists or not.
206        if ( MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $namespace ) ) {
207            if ( $namespace == NS_MAIN ) {
208                $name = $context->msg( 'blanknamespace' )->text();
209            } else {
210                $name = MediaWikiServices::getInstance()->getContentLanguage()->
211                    getFormattedNsText( $namespace );
212            }
213            return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
214        }
215
216        return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
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 = ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
253            ->onLinkerMakeExternalImage( $url, $alt, $img );
254        if ( !$success ) {
255            wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
256                . "with url {$url} and alt text {$alt} to {$img}" );
257            return $img;
258        }
259        return Html::element( 'img',
260            [
261                'src' => $url,
262                'alt' => $alt
263            ]
264        );
265    }
266
267    /**
268     * Given parameters derived from [[Image:Foo|options...]], generate the
269     * HTML that that syntax inserts in the page.
270     *
271     * @param Parser $parser
272     * @param LinkTarget $title LinkTarget object of the file (not the currently viewed page)
273     * @param File|false $file File object, or false if it doesn't exist
274     * @param array $frameParams Associative array of parameters external to the media handler.
275     *     Boolean parameters are indicated by presence or absence, the value is arbitrary and
276     *     will often be false.
277     *          thumbnail       If present, downscale and frame
278     *          manualthumb     Image name to use as a thumbnail, instead of automatic scaling
279     *          framed          Shows image in original size in a frame
280     *          frameless       Downscale but don't frame
281     *          upright         If present, tweak default sizes for portrait orientation
282     *          upright_factor  Fudge factor for "upright" tweak (default 0.75)
283     *          border          If present, show a border around the image
284     *          align           Horizontal alignment (left, right, center, none)
285     *          valign          Vertical alignment (baseline, sub, super, top, text-top, middle,
286     *                          bottom, text-bottom)
287     *          alt             Alternate text for image (i.e. alt attribute). Plain text.
288     *          title           Used for tooltips if caption isn't visible.
289     *          class           HTML for image classes. Plain text.
290     *          caption         HTML for image caption.
291     *          link-url        URL to link to
292     *          link-title      LinkTarget object to link to
293     *          link-target     Value for the target attribute, only with link-url
294     *          no-link         Boolean, suppress description link
295     *
296     * @param array $handlerParams Associative array of media handler parameters, to be passed
297     *       to transform(). Typical keys are "width" and "page".
298     *          targetlang      (optional) Target language code, see Parser::getTargetLanguage()
299     * @param string|false $time Timestamp of the file, set as false for current
300     * @param string $query Query params for desc url
301     * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
302     * @since 1.20
303     * @return string HTML for an image, with links, wrappers, etc.
304     */
305    public static function makeImageLink( Parser $parser, LinkTarget $title,
306        $file, $frameParams = [], $handlerParams = [], $time = false,
307        $query = '', $widthOption = null
308    ) {
309        $title = Title::newFromLinkTarget( $title );
310        $res = null;
311        $hookRunner = new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
312        if ( !$hookRunner->onImageBeforeProduceHTML( null, $title,
313            // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
314            $file, $frameParams, $handlerParams, $time, $res,
315            // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
316            $parser, $query, $widthOption )
317        ) {
318            return $res;
319        }
320
321        if ( $file && !$file->allowInlineDisplay() ) {
322            wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . ' does not allow inline display' );
323            return self::link( $title );
324        }
325
326        // Clean up parameters
327        $page = $handlerParams['page'] ?? false;
328        if ( !isset( $frameParams['align'] ) ) {
329            $frameParams['align'] = '';
330        }
331        if ( !isset( $frameParams['title'] ) ) {
332            $frameParams['title'] = '';
333        }
334        if ( !isset( $frameParams['class'] ) ) {
335            $frameParams['class'] = '';
336        }
337
338        $services = MediaWikiServices::getInstance();
339        $config = $services->getMainConfig();
340
341        $classes = [];
342        if (
343            !isset( $handlerParams['width'] ) &&
344            !isset( $handlerParams['height'] ) &&
345            !isset( $frameParams['manualthumb'] ) &&
346            !isset( $frameParams['framed'] )
347        ) {
348            $classes[] = 'mw-default-size';
349        }
350
351        $prefix = $postfix = '';
352
353        if ( $file && !isset( $handlerParams['width'] ) ) {
354            if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
355                // If its a vector image, and user only specifies height
356                // we don't want it to be limited by its "normal" width.
357                $svgMaxSize = $config->get( MainConfigNames::SVGMaxSize );
358                $handlerParams['width'] = $svgMaxSize;
359            } else {
360                $handlerParams['width'] = $file->getWidth( $page );
361            }
362
363            if ( isset( $frameParams['thumbnail'] )
364                || isset( $frameParams['manualthumb'] )
365                || isset( $frameParams['framed'] )
366                || isset( $frameParams['frameless'] )
367                || !$handlerParams['width']
368            ) {
369                $thumbLimits = $config->get( MainConfigNames::ThumbLimits );
370                $thumbUpright = $config->get( MainConfigNames::ThumbUpright );
371                if ( $widthOption === null || !isset( $thumbLimits[$widthOption] ) ) {
372                    $userOptionsLookup = $services->getUserOptionsLookup();
373                    $widthOption = $userOptionsLookup->getDefaultOption( 'thumbsize' );
374                }
375
376                // Reduce width for upright images when parameter 'upright' is used
377                if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
378                    $frameParams['upright'] = $thumbUpright;
379                }
380
381                // For caching health: If width scaled down due to upright
382                // parameter, round to full __0 pixel to avoid the creation of a
383                // lot of odd thumbs.
384                $prefWidth = isset( $frameParams['upright'] ) ?
385                    round( $thumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
386                    $thumbLimits[$widthOption];
387
388                // Use width which is smaller: real image width or user preference width
389                // Unless image is scalable vector.
390                if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
391                        $prefWidth < $handlerParams['width'] || $file->isVectorized() ) ) {
392                    $handlerParams['width'] = $prefWidth;
393                }
394            }
395        }
396
397        // Parser::makeImage has a similarly named variable
398        $hasVisibleCaption = isset( $frameParams['thumbnail'] ) ||
399            isset( $frameParams['manualthumb'] ) ||
400            isset( $frameParams['framed'] );
401
402        if ( $hasVisibleCaption ) {
403            return $prefix . self::makeThumbLink2(
404                $title, $file, $frameParams, $handlerParams, $time, $query,
405                $classes, $parser
406            ) . $postfix;
407        }
408
409        $rdfaType = 'mw:File';
410
411        if ( isset( $frameParams['frameless'] ) ) {
412            $rdfaType .= '/Frameless';
413            if ( $file ) {
414                $srcWidth = $file->getWidth( $page );
415                # For "frameless" option: do not present an image bigger than the
416                # source (for bitmap-style images). This is the same behavior as the
417                # "thumb" option does it already.
418                if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
419                    $handlerParams['width'] = $srcWidth;
420                }
421            }
422        }
423
424        if ( $file && isset( $handlerParams['width'] ) ) {
425            # Create a resized image, without the additional thumbnail features
426            $thumb = $file->transform( $handlerParams );
427        } else {
428            $thumb = false;
429        }
430
431        $isBadFile = $file && $thumb &&
432            $parser->getBadFileLookup()->isBadFile( $title->getDBkey(), $parser->getTitle() );
433
434        if ( !$thumb || $thumb->isError() || $isBadFile ) {
435            $rdfaType = 'mw:Error ' . $rdfaType;
436            $currentExists = $file && $file->exists();
437            if ( $currentExists && !$thumb ) {
438                $label = wfMessage( 'thumbnail_error', '' )->text();
439            } elseif ( $thumb && $thumb->isError() ) {
440                Assert::invariant(
441                    $thumb instanceof MediaTransformError,
442                    'Unknown MediaTransformOutput: ' . get_class( $thumb )
443                );
444                $label = $thumb->toText();
445            } else {
446                $label = $frameParams['alt'] ?? '';
447            }
448            $s = self::makeBrokenImageLinkObj(
449                $title, $label, '', '', '', (bool)$time, $handlerParams, $currentExists
450            );
451        } else {
452            self::processResponsiveImages( $file, $thumb, $handlerParams );
453            $params = [];
454            // An empty alt indicates an image is not a key part of the content
455            // and that non-visual browsers may omit it from rendering.  Only
456            // set the parameter if it's explicitly requested.
457            if ( isset( $frameParams['alt'] ) ) {
458                $params['alt'] = $frameParams['alt'];
459            }
460            $params['title'] = $frameParams['title'];
461            $params += [
462                'img-class' => 'mw-file-element',
463            ];
464            if (
465                isset( $frameParams['upright'] ) &&
466                in_array( 'mw-default-size', $classes, true ) &&
467                isset( $frameParams['frameless'] )
468            ) {
469                $params['img-class'] .= ' mw-file-upright';
470                $params['style'] = '--mw-file-upright: ' . $frameParams['upright'];
471            }
472            $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
473            $s = $thumb->toHtml( $params );
474        }
475
476        $wrapper = 'span';
477        $caption = '';
478
479        if ( $frameParams['align'] != '' ) {
480            $wrapper = 'figure';
481            // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
482            $classes[] = "mw-halign-{$frameParams['align']}";
483            $caption = Html::rawElement(
484                'figcaption', [], $frameParams['caption'] ?? ''
485            );
486        } elseif ( isset( $frameParams['valign'] ) ) {
487            // Possible values: mw-valign-middle mw-valign-baseline mw-valign-sub
488            // mw-valign-super mw-valign-top mw-valign-text-top mw-valign-bottom
489            // mw-valign-text-bottom
490            $classes[] = "mw-valign-{$frameParams['valign']}";
491        }
492
493        if ( isset( $frameParams['border'] ) ) {
494            $classes[] = 'mw-image-border';
495        }
496
497        if ( isset( $frameParams['class'] ) ) {
498            $classes[] = $frameParams['class'];
499        }
500
501        $attribs = [
502            'class' => $classes,
503            'typeof' => $rdfaType,
504        ];
505
506        $s = Html::rawElement( $wrapper, $attribs, $s . $caption );
507
508        return str_replace( "\n", ' ', $s );
509    }
510
511    /**
512     * Get the link parameters for MediaTransformOutput::toHtml() from given
513     * frame parameters supplied by the Parser.
514     * @param array $frameParams The frame parameters
515     * @param string $query An optional query string to add to description page links
516     * @param Parser|null $parser
517     * @return array
518     */
519    public static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
520        $mtoParams = [];
521        if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
522            $mtoParams['custom-url-link'] = $frameParams['link-url'];
523            if ( isset( $frameParams['link-target'] ) ) {
524                $mtoParams['custom-target-link'] = $frameParams['link-target'];
525            }
526            if ( $parser ) {
527                $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
528                foreach ( $extLinkAttrs as $name => $val ) {
529                    // Currently could include 'rel' and 'target'
530                    $mtoParams['parser-extlink-' . $name] = $val;
531                }
532            }
533        } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
534            $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
535                self::getLinkRenderer()->normalizeTarget( $frameParams['link-title'] )
536            );
537            if ( isset( $frameParams['link-title-query'] ) ) {
538                $mtoParams['custom-title-link-query'] = $frameParams['link-title-query'];
539            }
540        } elseif ( !empty( $frameParams['no-link'] ) ) {
541            // No link
542        } else {
543            $mtoParams['desc-link'] = true;
544            $mtoParams['desc-query'] = $query;
545        }
546        return $mtoParams;
547    }
548
549    /**
550     * Make HTML for a thumbnail including image, border and caption
551     * @param LinkTarget $title
552     * @param File|false $file File object or false if it doesn't exist
553     * @param string $label
554     * @param string $alt
555     * @param string|null $align
556     * @param array $params
557     * @param bool $framed
558     * @param string $manualthumb
559     * @return string
560     */
561    public static function makeThumbLinkObj(
562        LinkTarget $title, $file, $label = '', $alt = '', $align = null,
563        $params = [], $framed = false, $manualthumb = ''
564    ) {
565        $frameParams = [
566            'alt' => $alt,
567            'caption' => $label,
568            'align' => $align
569        ];
570        $classes = [];
571        if ( $manualthumb ) {
572            $frameParams['manualthumb'] = $manualthumb;
573        } elseif ( $framed ) {
574            $frameParams['framed'] = true;
575        } elseif ( !isset( $params['width'] ) && !isset( $params['height'] ) ) {
576            $classes[] = 'mw-default-size';
577        }
578        return self::makeThumbLink2(
579            $title, $file, $frameParams, $params, false, '', $classes
580        );
581    }
582
583    /**
584     * @param LinkTarget $title
585     * @param File|false $file
586     * @param array $frameParams
587     * @param array $handlerParams
588     * @param bool $time If a file of a certain timestamp was requested
589     * @param string $query
590     * @param string[] $classes @since 1.36
591     * @param Parser|null $parser @since 1.38
592     * @return string
593     */
594    public static function makeThumbLink2(
595        LinkTarget $title, $file, $frameParams = [], $handlerParams = [],
596        $time = false, $query = '', array $classes = [], ?Parser $parser = null
597    ) {
598        $exists = $file && $file->exists();
599        $services = MediaWikiServices::getInstance();
600
601        $page = $handlerParams['page'] ?? false;
602        $lang = $handlerParams['lang'] ?? false;
603
604        if ( !isset( $frameParams['align'] ) ) {
605            $frameParams['align'] = '';
606        }
607        if ( !isset( $frameParams['caption'] ) ) {
608            $frameParams['caption'] = '';
609        }
610
611        if ( empty( $handlerParams['width'] ) ) {
612            // Reduce width for upright images when parameter 'upright' is used
613            $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
614        }
615
616        $thumb = false;
617        $noscale = false;
618        $manualthumb = false;
619        $manual_title = '';
620        $rdfaType = 'mw:File/Thumb';
621
622        if ( !$exists ) {
623            // Same precedence as the $exists case
624            if ( !isset( $frameParams['manualthumb'] ) && isset( $frameParams['framed'] ) ) {
625                $rdfaType = 'mw:File/Frame';
626            }
627            $outerWidth = $handlerParams['width'] + 2;
628        } else {
629            if ( isset( $frameParams['manualthumb'] ) ) {
630                # Use manually specified thumbnail
631                $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
632                if ( $manual_title ) {
633                    $manual_img = $services->getRepoGroup()
634                        ->findFile( $manual_title );
635                    if ( $manual_img ) {
636                        $thumb = $manual_img->getUnscaledThumb( $handlerParams );
637                        $manualthumb = true;
638                    }
639                }
640            } else {
641                $srcWidth = $file->getWidth( $page );
642                if ( isset( $frameParams['framed'] ) ) {
643                    $rdfaType = 'mw:File/Frame';
644                    if ( !$file->isVectorized() ) {
645                        // Use image dimensions, don't scale
646                        $noscale = true;
647                    } else {
648                        // framed is unscaled, but for vectorized images
649                        // we need to a width for scaling up for the high density variants
650                        $handlerParams['width'] = $srcWidth;
651                    }
652                }
653
654                // Do not present an image bigger than the source, for bitmap-style images
655                // This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
656                if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
657                    $handlerParams['width'] = $srcWidth;
658                }
659
660                $thumb = $noscale
661                    ? $file->getUnscaledThumb( $handlerParams )
662                    : $file->transform( $handlerParams );
663            }
664
665            if ( $thumb ) {
666                $outerWidth = $thumb->getWidth() + 2;
667            } else {
668                $outerWidth = $handlerParams['width'] + 2;
669            }
670        }
671
672        if ( $parser && $rdfaType === 'mw:File/Thumb' ) {
673            $parser->getOutput()->addModules( [ 'mediawiki.page.media' ] );
674        }
675
676        $url = Title::newFromLinkTarget( $title )->getLocalURL( $query );
677        $linkTitleQuery = [];
678        if ( $page || $lang ) {
679            if ( $page ) {
680                $linkTitleQuery['page'] = $page;
681            }
682            if ( $lang ) {
683                $linkTitleQuery['lang'] = $lang;
684            }
685            # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
686            # So we don't need to pass it here in $query. However, the URL for the
687            # zoom icon still needs it, so we make a unique query for it. See T16771
688            $url = wfAppendQuery( $url, $linkTitleQuery );
689        }
690
691        if ( $manualthumb
692            && !isset( $frameParams['link-title'] )
693            && !isset( $frameParams['link-url'] )
694            && !isset( $frameParams['no-link'] ) ) {
695            $frameParams['link-title'] = $title;
696            $frameParams['link-title-query'] = $linkTitleQuery;
697        }
698
699        if ( $frameParams['align'] != '' ) {
700            // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
701            $classes[] = "mw-halign-{$frameParams['align']}";
702        }
703
704        if ( isset( $frameParams['class'] ) ) {
705            $classes[] = $frameParams['class'];
706        }
707
708        $s = '';
709
710        $isBadFile = $exists && $thumb && $parser &&
711            $parser->getBadFileLookup()->isBadFile(
712                $manualthumb ? $manual_title->getDBkey() : $title->getDBkey(),
713                $parser->getTitle()
714            );
715
716        if ( !$exists ) {
717            $rdfaType = 'mw:Error ' . $rdfaType;
718            $label = $frameParams['alt'] ?? '';
719            $s .= self::makeBrokenImageLinkObj(
720                $title, $label, '', '', '', (bool)$time, $handlerParams, false
721            );
722            $zoomIcon = '';
723        } elseif ( !$thumb || $thumb->isError() || $isBadFile ) {
724            $rdfaType = 'mw:Error ' . $rdfaType;
725            if ( $thumb && $thumb->isError() ) {
726                Assert::invariant(
727                    $thumb instanceof MediaTransformError,
728                    'Unknown MediaTransformOutput: ' . get_class( $thumb )
729                );
730                $label = $thumb->toText();
731            } elseif ( !$thumb ) {
732                $label = wfMessage( 'thumbnail_error', '' )->text();
733            } else {
734                $label = '';
735            }
736            $s .= self::makeBrokenImageLinkObj(
737                $title, $label, '', '', '', (bool)$time, $handlerParams, true
738            );
739            $zoomIcon = '';
740        } else {
741            if ( !$noscale && !$manualthumb ) {
742                self::processResponsiveImages( $file, $thumb, $handlerParams );
743            }
744            $params = [];
745            // An empty alt indicates an image is not a key part of the content
746            // and that non-visual browsers may omit it from rendering.  Only
747            // set the parameter if it's explicitly requested.
748            if ( isset( $frameParams['alt'] ) ) {
749                $params['alt'] = $frameParams['alt'];
750            }
751            $params += [
752                'img-class' => 'mw-file-element',
753            ];
754            if (
755                isset( $frameParams['upright'] ) &&
756                in_array( 'mw-default-size', $classes, true )
757            ) {
758                $params['img-class'] .= ' mw-file-upright';
759                $params['style'] = '--mw-file-upright: ' . $frameParams['upright'];
760            }
761            // Only thumbs gets the magnify link
762            if ( $rdfaType === 'mw:File/Thumb' ) {
763                $params['magnify-resource'] = $url;
764            }
765            $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
766            $s .= $thumb->toHtml( $params );
767            if ( isset( $frameParams['framed'] ) ) {
768                $zoomIcon = '';
769            } else {
770                $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
771                    Html::rawElement( 'a', [
772                        'href' => $url,
773                        'class' => 'internal',
774                        'title' => wfMessage( 'thumbnail-more' )->text(),
775                    ] )
776                );
777            }
778        }
779
780        $s .= Html::rawElement(
781            'figcaption', [], $frameParams['caption'] ?? ''
782        );
783
784        $attribs = [
785            'class' => $classes,
786            'typeof' => $rdfaType,
787        ];
788
789        $s = Html::rawElement( 'figure', $attribs, $s );
790
791        return str_replace( "\n", ' ', $s );
792    }
793
794    /**
795     * Add 2x variant for srcset, if $wgResponsiveImages is enabled.
796     *
797     * @see $wgResponsiveImages
798     * @param File $file
799     * @param MediaTransformOutput|null $thumb
800     * @param array $hp Image parameters
801     */
802    public static function processResponsiveImages( $file, $thumb, $hp ) {
803        $responsiveImages = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::ResponsiveImages );
804        if ( $responsiveImages && $thumb && !$thumb->isError() ) {
805            $hp20 = $hp;
806            $hp20['width'] = $hp['width'] * 2;
807            if ( isset( $hp['height'] ) ) {
808                $hp20['height'] = $hp['height'] * 2;
809            }
810            $thumb20 = $file->transform( $hp20 );
811            if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
812                $thumb->responsiveUrls['2'] = $thumb20->getUrl();
813            }
814        }
815    }
816
817    /**
818     * Make a "broken" link to an image
819     *
820     * @since 1.16.3
821     * @param ParsoidLinkTarget $title
822     * @param string $label Link label (plain text)
823     * @param string $query Query string
824     *   This parameter was deprecated in 1.47 and will be ignored in
825     *   a future release. For forward compatibility pass an empty string
826     *   if needed.
827     * @param string $unused1 Unused parameter kept for b/c
828     * @param string $unused2 Unused parameter kept for b/c
829     * @param bool $time A file of a certain timestamp was requested
830     * @param array $handlerParams @since 1.36
831     * @param bool $currentExists @since 1.41
832     * @return string
833     */
834    public static function makeBrokenImageLinkObj(
835        $title, $label = '', $query = '', $unused1 = '', $unused2 = '',
836        $time = false, array $handlerParams = [], bool $currentExists = false
837    ) {
838        if ( !$title instanceof ParsoidLinkTarget ) {
839            wfDeprecatedMsg( __METHOD__ . ': Requires $title to be a LinkTarget object', '1.47' );
840            return "<!-- ERROR -->" . htmlspecialchars( $label );
841        }
842        if ( $query !== '' ) {
843            wfDeprecated( __METHOD__ . ' with non-empty query parameter', '1.47' );
844        }
845
846        $title = Title::newFromLinkTarget( $title );
847        $services = MediaWikiServices::getInstance();
848        $mainConfig = $services->getMainConfig();
849        $enableUploads = $mainConfig->get( MainConfigNames::EnableUploads );
850        $uploadMissingFileUrl = $mainConfig->get( MainConfigNames::UploadMissingFileUrl );
851        $uploadNavigationUrl = $mainConfig->get( MainConfigNames::UploadNavigationUrl );
852        if ( $label == '' ) {
853            $label = $title->getPrefixedText();
854        }
855
856        $html = Html::element( 'span', [
857            'class' => 'mw-file-element mw-broken-media',
858            // These data attributes are used to dynamically size the span, see T273013
859            'data-width' => $handlerParams['width'] ?? null,
860            'data-height' => $handlerParams['height'] ?? null,
861        ], $label );
862
863        $repoGroup = $services->getRepoGroup();
864        $currentExists = $currentExists ||
865            ( $time && $repoGroup->findFile( $title ) !== false );
866
867        if ( ( $uploadMissingFileUrl || $uploadNavigationUrl || $enableUploads )
868            && !$currentExists
869        ) {
870            if (
871                $title->inNamespace( NS_FILE ) &&
872                $repoGroup->getLocalRepo()->checkRedirect( $title )
873            ) {
874                // We already know it's a redirect, so mark it accordingly
875                return self::link(
876                    $title,
877                    $html,
878                    [ 'class' => 'mw-redirect' ],
879                    wfCgiToArray( $query ),
880                    [ 'known', 'noclasses' ]
881                );
882            }
883            return Html::rawElement( 'a', [
884                    'href' => self::getUploadUrl( $title, $query ),
885                    'class' => 'new',
886                    'title' => $title->getPrefixedText()
887                ], $html );
888        }
889        return self::link(
890            $title,
891            $html,
892            [],
893            wfCgiToArray( $query ),
894            [ 'known', 'noclasses' ]
895        );
896    }
897
898    /**
899     * Get the URL to upload a certain file
900     *
901     * @since 1.16.3
902     * @param ParsoidLinkTarget $destFile LinkTarget object of the file to upload
903     * @param string $query Urlencoded query string to prepend
904     *   (deprecated since 1.47)
905     * @param bool $prefixedURL Return a prefixed URL instead of a local URL
906     *   (since 1.47)
907     * @return string Urlencoded URL
908     */
909    public static function getUploadUrl( ParsoidLinkTarget $destFile, string $query = '', bool $prefixedURL = false ) {
910        $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
911        $uploadMissingFileUrl = $mainConfig->get( MainConfigNames::UploadMissingFileUrl );
912        $uploadNavigationUrl = $mainConfig->get( MainConfigNames::UploadNavigationUrl );
913        $q = 'wpDestFile=' . Title::newFromLinkTarget( $destFile )->getPartialURL();
914        if ( $query != '' ) {
915            wfDeprecated( __METHOD__ . ' with $query parameter', '1.47' );
916            $q .= '&' . $query;
917        }
918
919        if ( $uploadMissingFileUrl ) {
920            return wfAppendQuery( $uploadMissingFileUrl, $q );
921        }
922
923        if ( $uploadNavigationUrl ) {
924            return wfAppendQuery( $uploadNavigationUrl, $q );
925        }
926
927        $upload = SpecialPage::getTitleFor( 'Upload' );
928
929        if ( $prefixedURL ) {
930            return './' . $upload->getPrefixedURL( $q );
931        }
932        return $upload->getLocalURL( $q );
933    }
934
935    /**
936     * Create a direct link to a given uploaded file.
937     *
938     * @since 1.16.3
939     * @param LinkTarget $title
940     * @param string $html Pre-sanitized HTML
941     * @param string|false $time MW timestamp of file creation time
942     * @return string HTML
943     */
944    public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
945        $img = MediaWikiServices::getInstance()->getRepoGroup()->findFile(
946            $title, [ 'time' => $time ]
947        );
948        return self::makeMediaLinkFile( $title, $img, $html );
949    }
950
951    /**
952     * Create a direct link to a given uploaded file.
953     * This will make a broken link if $file is false.
954     *
955     * @since 1.16.3
956     * @param LinkTarget $title
957     * @param File|false $file File object or false
958     * @param string $html Pre-sanitized HTML
959     * @return string HTML
960     *
961     * @todo Handle invalid or missing images better.
962     */
963    public static function makeMediaLinkFile( LinkTarget $title, $file, $html = '' ) {
964        if ( $file && $file->exists() ) {
965            $url = $file->getUrl();
966            $class = 'internal';
967        } else {
968            $url = self::getUploadUrl( $title );
969            $class = 'new';
970        }
971
972        $alt = $title->getText();
973        if ( $html == '' ) {
974            $html = $alt;
975        }
976
977        $ret = '';
978        $attribs = [
979            'href' => $url,
980            'class' => $class,
981            'title' => $alt
982        ];
983
984        if ( !( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onLinkerMakeMediaLinkFile(
985            Title::newFromLinkTarget( $title ), $file, $html, $attribs, $ret )
986        ) {
987            wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
988                . "with url {$url} and text {$html} to {$ret}" );
989            return $ret;
990        }
991
992        return Html::rawElement( 'a', $attribs, $html );
993    }
994
995    /**
996     * Make a link to a special page given its name and, optionally,
997     * a message key from the link text.
998     * Usage example: Linker::specialLink( 'Recentchanges' )
999     *
1000     * @since 1.16.3
1001     * @param string $name Special page name, can optionally include â€¦/subpages and â€¦?parameters
1002     * @param string $key Optional message key if different from $name
1003     * @return string
1004     */
1005    public static function specialLink( $name, $key = '' ) {
1006        $queryPos = strpos( $name, '?' );
1007        if ( $queryPos !== false ) {
1008            $getParams = wfCgiToArray( substr( $name, $queryPos + 1 ) );
1009            $name = substr( $name, 0, $queryPos );
1010        } else {
1011            $getParams = [];
1012        }
1013
1014        $slashPos = strpos( $name, '/' );
1015        if ( $slashPos !== false ) {
1016            $subpage = substr( $name, $slashPos + 1 );
1017            $name = substr( $name, 0, $slashPos );
1018        } else {
1019            $subpage = false;
1020        }
1021
1022        if ( $key == '' ) {
1023            $key = strtolower( $name );
1024        }
1025
1026        return self::getLinkRenderer()->makeKnownLink(
1027            SpecialPage::getTitleFor( $name, $subpage ),
1028            wfMessage( $key )->plain(),
1029            [],
1030            $getParams
1031        );
1032    }
1033
1034    /**
1035     * Make an external link
1036     *
1037     * @since 1.16.3. $title added in 1.21
1038     * @param string $url URL to link to
1039     * @param-taint $url escapes_html
1040     * @param string $text Text of link
1041     * @param-taint $text none
1042     * @param bool $escape Do we escape the link text?
1043     * @param-taint $escape none
1044     * @param string $linktype Type of external link. Gets added to the classes
1045     * @param-taint $linktype escapes_html
1046     * @param array $attribs Array of extra attributes to <a>
1047     * @param-taint $attribs escapes_html
1048     * @param LinkTarget|null $title LinkTarget object used for title specific link attributes
1049     * @param-taint $title none
1050     * @return string
1051     * @deprecated since 1.43; use LinkRenderer::makeExternalLink(), passing
1052     *   in an HtmlArmor instance if $escape was false.
1053     */
1054    public static function makeExternalLink( $url, $text, $escape = true,
1055        $linktype = '', $attribs = [], $title = null
1056    ) {
1057        // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
1058        global $wgTitle;
1059        return self::getLinkRenderer()->makeExternalLink(
1060            $url,
1061            $escape ? $text : new HtmlArmor( $text ),
1062            $title ?? $wgTitle ?? SpecialPage::getTitleFor( 'Badtitle' ),
1063            $linktype,
1064            $attribs
1065        );
1066    }
1067
1068    /**
1069     * Make user link (or user contributions for unregistered users)
1070     *
1071     * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
1072     *
1073     * @param int $userId User id in database.
1074     * @param string $userName User name in database.
1075     * @param string|false $altUserName Text to display instead of the user name (optional)
1076     * @param string[] $attributes Extra HTML attributes. See Linker::link.
1077     * @return string HTML fragment
1078     * @since 1.16.3. $altUserName was added in 1.19. $attributes was added in 1.40.
1079     *
1080     * @deprecated since 1.44, use {@link LinkRenderer::makeUserLink()} instead.
1081     */
1082    public static function userLink(
1083        $userId,
1084        $userName,
1085        $altUserName = false,
1086        $attributes = []
1087    ) {
1088        if ( $userName === '' || $userName === false || $userName === null ) {
1089            wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1090                'that need to be fixed?' );
1091            return wfMessage( 'empty-username' )->parse();
1092        }
1093
1094        return self::getLinkRenderer()->makeUserLink(
1095            new UserIdentityValue( $userId, (string)$userName ),
1096            RequestContext::getMain(),
1097            $altUserName === false ? null : (string)$altUserName,
1098            $attributes
1099        );
1100    }
1101
1102    /**
1103     * Generate standard user tool links (talk, contributions, block link, etc.)
1104     *
1105     * @since 1.42
1106     * @param int $userId User identifier
1107     * @param string $userText User name or IP address
1108     * @param bool $redContribsWhenNoEdits Should the contributions link be
1109     *   red if the user has no edits?
1110     * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1111     *   and Linker::TOOL_LINKS_EMAIL).
1112     * @param int|null $edits User edit count. If you enable $redContribsWhenNoEdits,
1113     *  you may pass a pre-computed edit count here, or 0 if the caller knows that
1114     *  the account has 0 edits. Otherwise, the value is unused and null may
1115     *  be passed. If $redContribsWhenNoEdits is enabled and null is passed, the
1116     *  edit count will be lazily fetched from UserEditTracker.
1117     * @return string[] Array of HTML fragments, each of them a link tag with a distinctive
1118     *   class; or a single string on error.
1119     */
1120    public static function userToolLinkArray(
1121        $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1122    ): array {
1123        $services = MediaWikiServices::getInstance();
1124        $disableAnonTalk = $services->getMainConfig()->get( MainConfigNames::DisableAnonTalk );
1125        $talkable = !( $disableAnonTalk && $userId == 0 );
1126        $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1127        $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1128
1129        if ( $userId == 0 && ExternalUserNames::isExternal( $userText ) ) {
1130            // No tools for an external user
1131            return [];
1132        }
1133
1134        $items = [];
1135        if ( $talkable ) {
1136            $items[] = self::userTalkLink( $userId, $userText );
1137        }
1138
1139        // (T412013) Do not link to Special:Contributions for temp accounts
1140        // since the target for the link in the username itself already links to
1141        // Special:Contributions.
1142        if ( $userId && !$services->getTempUserConfig()->isTempName( $userText ) ) {
1143            $attribs = [];
1144            $attribs['class'] = 'mw-usertoollinks-contribs';
1145
1146            // check if the user has edits
1147            if ( $redContribsWhenNoEdits ) {
1148                if ( $edits === null ) {
1149                    $user = UserIdentityValue::newRegistered( $userId, $userText );
1150                    $edits = $services->getUserEditTracker()->getUserEditCount( $user );
1151                }
1152                if ( $edits === 0 ) {
1153                    // Note: "new" class is inappropriate here, as "new" class
1154                    // should only be used for pages that do not exist.
1155                    $attribs['class'] .= ' mw-usertoollinks-contribs-no-edits';
1156                }
1157            }
1158            $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1159
1160            $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1161        }
1162        $userCanBlock = RequestContext::getMain()->getAuthority()->isAllowed( 'block' );
1163        if ( $blockable && $userCanBlock ) {
1164            $items[] = self::blockLink( $userId, $userText );
1165        }
1166
1167        if (
1168            $addEmailLink
1169            && MediaWikiServices::getInstance()->getEmailUserFactory()
1170                ->newEmailUser( RequestContext::getMain()->getAuthority() )
1171                ->canSend()
1172                ->isGood()
1173        ) {
1174            $items[] = self::emailLink( $userId, $userText );
1175        }
1176
1177        ( new HookRunner( $services->getHookContainer() ) )->onUserToolLinksEdit( $userId, $userText, $items );
1178
1179        return $items;
1180    }
1181
1182    /**
1183     * Generate standard tool links HTML from a link array returned by userToolLinkArray().
1184     * @since 1.42
1185     * @param array $items
1186     * @param bool $useParentheses (optional, default true) Wrap comments in parentheses where needed
1187     * @return string
1188     */
1189    public static function renderUserToolLinksArray( array $items, bool $useParentheses ): string {
1190        if ( !$items ) {
1191            return '';
1192        }
1193
1194        if ( $useParentheses ) {
1195            $lang = RequestContext::getMain()->getLanguage();
1196            return wfMessage( 'word-separator' )->escaped()
1197                . '<span class="mw-usertoollinks">'
1198                . wfMessage( 'parentheses' )->rawParams( $lang->pipeList( $items ) )->escaped()
1199                . '</span>';
1200        }
1201
1202        $tools = [];
1203        foreach ( $items as $tool ) {
1204            $tools[] = Html::rawElement( 'span', [], $tool );
1205        }
1206        return ' <span class="mw-usertoollinks mw-changeslist-links">' .
1207            implode( ' ', $tools ) . '</span>';
1208    }
1209
1210    /**
1211     * Generate standard user tool links (talk, contributions, block link, etc.)
1212     *
1213     * @since 1.16.3
1214     * @param int $userId User identifier
1215     * @param string $userText User name or IP address
1216     * @param bool $redContribsWhenNoEdits Should the contributions link be
1217     *   red if the user has no edits?
1218     * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1219     *   and Linker::TOOL_LINKS_EMAIL).
1220     * @param int|null $edits User edit count (optional, for performance)
1221     * @param bool $useParentheses (optional, default true) Wrap comments in parentheses where needed
1222     * @return string HTML fragment
1223     */
1224    public static function userToolLinks(
1225        $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
1226        $useParentheses = true
1227    ) {
1228        if ( $userText === '' ) {
1229            wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1230                'that need to be fixed?' );
1231            return ' ' . wfMessage( 'empty-username' )->parse();
1232        }
1233
1234        $items = self::userToolLinkArray( $userId, $userText, $redContribsWhenNoEdits, $flags, $edits );
1235        return self::renderUserToolLinksArray( $items, $useParentheses );
1236    }
1237
1238    /**
1239     * Alias for userToolLinks( $userId, $userText, true );
1240     * @since 1.16.3
1241     * @param int $userId User identifier
1242     * @param string $userText User name or IP address
1243     * @param int|null $edits User edit count (optional, for performance)
1244     * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1245     * @return string
1246     */
1247    public static function userToolLinksRedContribs(
1248        $userId, $userText, $edits = null, $useParentheses = true
1249    ) {
1250        return self::userToolLinks( $userId, $userText, true, 0, $edits, $useParentheses );
1251    }
1252
1253    /**
1254     * @since 1.16.3
1255     * @param int $userId User id in database.
1256     * @param string $userText User name in database.
1257     * @return string HTML fragment with user talk link
1258     */
1259    public static function userTalkLink( $userId, $userText ) {
1260        if ( $userText === '' ) {
1261            wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1262                'that need to be fixed?' );
1263            return wfMessage( 'empty-username' )->parse();
1264        }
1265
1266        $userTalkPage = TitleValue::tryNew( NS_USER_TALK, strtr( $userText, ' ', '_' ) );
1267        $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-talk' ];
1268        $linkText = wfMessage( 'talkpagelinktext' )->escaped();
1269
1270        return $userTalkPage
1271            ? self::link( $userTalkPage, $linkText, $moreLinkAttribs )
1272            : Html::rawElement( 'span', $moreLinkAttribs, $linkText );
1273    }
1274
1275    /**
1276     * @since 1.16.3
1277     * @param int $userId
1278     * @param string $userText User name in database.
1279     * @return string HTML fragment with block link
1280     */
1281    public static function blockLink( $userId, $userText ) {
1282        if ( $userText === '' ) {
1283            wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1284                'that need to be fixed?' );
1285            return wfMessage( 'empty-username' )->parse();
1286        }
1287
1288        $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1289        $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-block' ];
1290
1291        return self::link( $blockPage,
1292            wfMessage( 'blocklink' )->escaped(),
1293            $moreLinkAttribs
1294        );
1295    }
1296
1297    /**
1298     * @param int $userId
1299     * @param string $userText User name in database.
1300     * @return string HTML fragment with e-mail user link
1301     */
1302    public static function emailLink( $userId, $userText ) {
1303        if ( $userText === '' ) {
1304            wfLogWarning( __METHOD__ . ' received an empty username. Are there database errors ' .
1305                'that need to be fixed?' );
1306            return wfMessage( 'empty-username' )->parse();
1307        }
1308
1309        $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1310        $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-mail' ];
1311        return self::link( $emailPage,
1312            wfMessage( 'emaillink' )->escaped(),
1313            $moreLinkAttribs
1314        );
1315    }
1316
1317    /**
1318     * Generate a user link if the current user is allowed to view it
1319     *
1320     * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
1321     *
1322     * @since 1.16.3
1323     * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1324     *    since 1.35)
1325     * @param bool $isPublic Show only if all users can see it
1326     * @return string HTML fragment
1327     */
1328    public static function revUserLink( RevisionRecord $revRecord, $isPublic = false ) {
1329        // TODO inject authority
1330        $authority = RequestContext::getMain()->getAuthority();
1331
1332        $revUser = $revRecord->getUser(
1333            $isPublic ? RevisionRecord::FOR_PUBLIC : RevisionRecord::FOR_THIS_USER,
1334            $authority
1335        );
1336        if ( $revUser ) {
1337            $link = self::userLink( $revUser->getId(), $revUser->getName() );
1338        } else {
1339            // User is deleted and we can't (or don't want to) view it
1340            $link = wfMessage( 'rev-deleted-user' )->escaped();
1341        }
1342
1343        if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) ) {
1344            $class = self::getRevisionDeletedClass( $revRecord );
1345            return '<span class="' . $class . '">' . $link . '</span>';
1346        }
1347        return $link;
1348    }
1349
1350    /**
1351     * Returns css class of a deleted revision
1352     * @param RevisionRecord $revisionRecord
1353     * @return string 'history-deleted', 'mw-history-suppressed' added if suppressed too
1354     * @since 1.37
1355     */
1356    public static function getRevisionDeletedClass( RevisionRecord $revisionRecord ): string {
1357        $class = 'history-deleted';
1358        if ( $revisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ) {
1359            $class .= ' mw-history-suppressed';
1360        }
1361        return $class;
1362    }
1363
1364    /**
1365     * Generate a user tool link cluster if the current user is allowed to view it
1366     *
1367     * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
1368     *
1369     * @since 1.16.3
1370     * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1371     *    since 1.35)
1372     * @param bool $isPublic Show only if all users can see it
1373     * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1374     * @return string HTML
1375     */
1376    public static function revUserTools(
1377        RevisionRecord $revRecord,
1378        $isPublic = false,
1379        $useParentheses = true
1380    ) {
1381        // TODO inject authority
1382        $authority = RequestContext::getMain()->getAuthority();
1383
1384        $revUser = $revRecord->getUser(
1385            $isPublic ? RevisionRecord::FOR_PUBLIC : RevisionRecord::FOR_THIS_USER,
1386            $authority
1387        );
1388        if ( $revUser ) {
1389            $link = self::userLink(
1390                $revUser->getId(),
1391                $revUser->getName(),
1392                false,
1393                [ 'data-mw-revid' => $revRecord->getId() ]
1394            ) . self::userToolLinks(
1395                $revUser->getId(),
1396                $revUser->getName(),
1397                false,
1398                0,
1399                null,
1400                $useParentheses
1401            );
1402        } else {
1403            // User is deleted and we can't (or don't want to) view it
1404            $link = wfMessage( 'rev-deleted-user' )->escaped();
1405        }
1406
1407        if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) ) {
1408            $class = self::getRevisionDeletedClass( $revRecord );
1409            return ' <span class="' . $class . ' mw-userlink">' . $link . '</span>';
1410        }
1411        return $link;
1412    }
1413
1414    /**
1415     * Helper function to expand local links. Mostly used in action=render
1416     *
1417     * @since 1.38
1418     * @unstable
1419     *
1420     * @param string $html
1421     *
1422     * @return string HTML
1423     */
1424    public static function expandLocalLinks( string $html ) {
1425        return HtmlHelper::modifyElements(
1426            $html,
1427            static function ( SerializerNode $node ): bool {
1428                return $node->name === 'a' && isset( $node->attrs['href'] );
1429            },
1430            static function ( SerializerNode $node ): SerializerNode {
1431                $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
1432                $href = $urlUtils->expand( $node->attrs['href'], PROTO_RELATIVE );
1433                if ( $href !== null ) {
1434                    $node->attrs['href'] = $href;
1435                }
1436                return $node;
1437            }
1438        );
1439    }
1440
1441    /**
1442     * @param LinkTarget|null $contextTitle
1443     * @param string $target
1444     * @param string &$text
1445     * @return string
1446     */
1447    public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1448        # Valid link forms:
1449        # Foobar -- normal
1450        # :Foobar -- override special treatment of prefix (images, language links)
1451        # /Foobar -- convert to CurrentPage/Foobar
1452        # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1453        # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1454        # ../Foobar -- convert to CurrentPage/Foobar,
1455        #              (from CurrentPage/CurrentSubPage)
1456        # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1457        #              (from CurrentPage/CurrentSubPage)
1458
1459        $ret = $target; # default return value is no change
1460
1461        # Some namespaces don't allow subpages,
1462        # so only perform processing if subpages are allowed
1463        if (
1464            $contextTitle && MediaWikiServices::getInstance()->getNamespaceInfo()->
1465            hasSubpages( $contextTitle->getNamespace() )
1466        ) {
1467            $hash = strpos( $target, '#' );
1468            if ( $hash !== false ) {
1469                $suffix = substr( $target, $hash );
1470                $target = substr( $target, 0, $hash );
1471            } else {
1472                $suffix = '';
1473            }
1474            # T9425
1475            $target = trim( $target );
1476            $contextPrefixedText = MediaWikiServices::getInstance()->getTitleFormatter()->
1477                getPrefixedText( $contextTitle );
1478            # Look at the first character
1479            if ( $target != '' && $target[0] === '/' ) {
1480                # / at end means we don't want the slash to be shown
1481                $m = [];
1482                $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1483                if ( $trailingSlashes ) {
1484                    $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1485                } else {
1486                    $noslash = substr( $target, 1 );
1487                }
1488
1489                $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1490                if ( $text === '' ) {
1491                    $text = $target . $suffix;
1492                } # this might be changed for ugliness reasons
1493            } else {
1494                # check for .. subpage backlinks
1495                $dotdotcount = 0;
1496                $nodotdot = $target;
1497                while ( str_starts_with( $nodotdot, '../' ) ) {
1498                    ++$dotdotcount;
1499                    $nodotdot = substr( $nodotdot, 3 );
1500                }
1501                if ( $dotdotcount > 0 ) {
1502                    $exploded = explode( '/', $contextPrefixedText );
1503                    if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1504                        $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1505                        # / at the end means don't show full path
1506                        if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1507                            $nodotdot = rtrim( $nodotdot, '/' );
1508                            if ( $text === '' ) {
1509                                $text = $nodotdot . $suffix;
1510                            }
1511                        }
1512                        $nodotdot = trim( $nodotdot );
1513                        if ( $nodotdot != '' ) {
1514                            $ret .= '/' . $nodotdot;
1515                        }
1516                        $ret .= $suffix;
1517                    }
1518                }
1519            }
1520        }
1521
1522        return $ret;
1523    }
1524
1525    /**
1526     * @since 1.16.3
1527     * @param int $size
1528     * @return string
1529     */
1530    public static function formatRevisionSize( $size ) {
1531        if ( $size == 0 ) {
1532            $stxt = wfMessage( 'historyempty' )->escaped();
1533        } else {
1534            $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1535        }
1536        return "<span class=\"history-size mw-diff-bytes\" data-mw-bytes=\"$size\">$stxt</span>";
1537    }
1538
1539    /**
1540     * Split a link trail, return the "inside" portion and the remainder of the trail
1541     * as a two-element array
1542     * @param string $trail
1543     * @return string[]
1544     */
1545    public static function splitTrail( $trail ) {
1546        $regex = MediaWikiServices::getInstance()->getContentLanguage()->linkTrail();
1547        $inside = '';
1548        if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1549            [ , $inside, $trail ] = $m;
1550        }
1551        return [ $inside, $trail ];
1552    }
1553
1554    /**
1555     * Generate a rollback link for a given revision.  Currently it's the
1556     * caller's responsibility to ensure that the revision is the top one. If
1557     * it's not, of course, the user will get an error message.
1558     *
1559     * If the calling page is called with the parameter &bot=1, all rollback
1560     * links also get that parameter. It causes the edit itself and the rollback
1561     * to be marked as "bot" edits. Bot edits are hidden by default from recent
1562     * changes, so this allows sysops to combat a busy vandal without bothering
1563     * other users.
1564     *
1565     * This function will return the link only in case the revision can be reverted
1566     * (not all revisions are by the same user, and the last revision by a different
1567     * user is visible). Please note that due to performance limitations it might be
1568     * assumed that a user isn't the only contributor of a page while they are, which
1569     * will lead to useless rollback links. Furthermore this won't work if
1570     * $wgShowRollbackEditCount is disabled, so this can only function as an
1571     * additional check.
1572     *
1573     * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1574     *
1575     * @since 1.16.3. $context added in 1.20. $options added in 1.21
1576     *   $rev could be a RevisionRecord since 1.35
1577     *
1578     * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1579     *    since 1.35)
1580     * @param IContextSource|null $context Context to use or null for the main context.
1581     * @param array $options
1582     * @return string
1583     */
1584    public static function generateRollback(
1585        RevisionRecord $revRecord,
1586        ?IContextSource $context = null,
1587        $options = []
1588    ) {
1589        $context ??= RequestContext::getMain();
1590
1591        $editCount = self::getRollbackEditCount( $revRecord );
1592        if ( $editCount === false ) {
1593            return '';
1594        }
1595
1596        $inner = self::buildRollbackLink( $revRecord, $context, $editCount );
1597
1598        $services = MediaWikiServices::getInstance();
1599        // Allow extensions to modify the rollback link.
1600        // Abort further execution if the extension wants full control over the link.
1601        if ( !( new HookRunner( $services->getHookContainer() ) )->onLinkerGenerateRollbackLink(
1602            $revRecord, $context, $options, $inner ) ) {
1603            return $inner;
1604        }
1605
1606        if ( !in_array( 'noBrackets', $options, true ) ) {
1607            $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1608        }
1609
1610        if ( $services->getUserOptionsLookup()
1611            ->getBoolOption( $context->getUser(), 'showrollbackconfirmation' )
1612        ) {
1613            $context->getOutput()->addModules( 'mediawiki.misc-authed-curate' );
1614        }
1615
1616        return '<span class="mw-rollback-link">' . $inner . '</span>';
1617    }
1618
1619    /**
1620     * This function will return the number of revisions which a rollback
1621     * would revert and will verify that a revision can be reverted (that
1622     * the user isn't the only contributor and the revision we might
1623     * rollback to isn't deleted). These checks can only function as an
1624     * additional check as this function only checks against the last
1625     * $wgShowRollbackEditCount edits.
1626     *
1627     * Returns null if $wgShowRollbackEditCount is disabled or false if
1628     * the user is the only contributor of the page.
1629     *
1630     * @todo Unused outside of this file - should it be made private?
1631     *
1632     * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1633     *    since 1.35)
1634     * @param bool $verify Deprecated since 1.40, has no effect.
1635     * @return int|false|null
1636     */
1637    public static function getRollbackEditCount( RevisionRecord $revRecord, $verify = true ) {
1638        if ( func_num_args() > 1 ) {
1639            wfDeprecated( __METHOD__ . ' with $verify parameter', '1.40' );
1640        }
1641        $showRollbackEditCount = MediaWikiServices::getInstance()->getMainConfig()
1642            ->get( MainConfigNames::ShowRollbackEditCount );
1643
1644        if ( !is_int( $showRollbackEditCount ) || !$showRollbackEditCount > 0 ) {
1645            // Nothing has happened, indicate this by returning 'null'
1646            return null;
1647        }
1648
1649        $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1650
1651        // Up to the value of $wgShowRollbackEditCount revisions are counted
1652        $queryBuilder = MediaWikiServices::getInstance()->getRevisionStore()->newSelectQueryBuilder( $dbr );
1653        $res = $queryBuilder->where( [ 'rev_page' => $revRecord->getPageId() ] )
1654            ->useIndex( [ 'revision' => 'rev_page_timestamp' ] )
1655            ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder::SORT_DESC )
1656            ->limit( $showRollbackEditCount + 1 )
1657            ->caller( __METHOD__ )->fetchResultSet();
1658
1659        $revUser = $revRecord->getUser( RevisionRecord::RAW );
1660        $revUserText = $revUser ? $revUser->getName() : '';
1661
1662        $editCount = 0;
1663        $moreRevs = false;
1664        foreach ( $res as $row ) {
1665            if ( $row->rev_user_text != $revUserText ) {
1666                if ( $row->rev_deleted & RevisionRecord::DELETED_TEXT
1667                    || $row->rev_deleted & RevisionRecord::DELETED_USER
1668                ) {
1669                    // If the user or the text of the revision we might rollback
1670                    // to is deleted in some way we can't rollback. Similar to
1671                    // the checks in WikiPage::commitRollback.
1672                    return false;
1673                }
1674                $moreRevs = true;
1675                break;
1676            }
1677            $editCount++;
1678        }
1679
1680        if ( $editCount <= $showRollbackEditCount && !$moreRevs ) {
1681            // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1682            // and there weren't any other revisions. That means that the current user is the only
1683            // editor, so we can't rollback
1684            return false;
1685        }
1686        return $editCount;
1687    }
1688
1689    /**
1690     * Build a raw rollback link, useful for collections of "tool" links
1691     *
1692     * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1693     *   $rev could be a RevisionRecord since 1.35
1694     *
1695     * @todo Unused outside of this file - should it be made private?
1696     *
1697     * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1698     *    since 1.35)
1699     * @param IContextSource|null $context Context to use or null for the main context.
1700     * @param int|false|null $editCount Number of edits that would be reverted
1701     * @return string HTML fragment
1702     */
1703    public static function buildRollbackLink(
1704        RevisionRecord $revRecord,
1705        ?IContextSource $context = null,
1706        $editCount = false
1707    ) {
1708        $config = MediaWikiServices::getInstance()->getMainConfig();
1709        $showRollbackEditCount = $config->get( MainConfigNames::ShowRollbackEditCount );
1710        $miserMode = $config->get( MainConfigNames::MiserMode );
1711        // To config which pages are affected by miser mode
1712        $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1713
1714        $context ??= RequestContext::getMain();
1715
1716        $title = $revRecord->getPageAsLinkTarget();
1717        $revUser = $revRecord->getUser();
1718        $revUserText = $revUser ? $revUser->getName() : '';
1719
1720        $query = [
1721            'action' => 'rollback',
1722            'from' => $revUserText,
1723            'token' => $context->getUser()->getEditToken( 'rollback' ),
1724        ];
1725
1726        $attrs = [
1727            'data-mw-interface' => '',
1728            'title' => $context->msg( 'tooltip-rollback' )->text()
1729        ];
1730
1731        $options = [ 'known', 'noclasses' ];
1732
1733        if ( $context->getRequest()->getBool( 'bot' ) ) {
1734            // T17999
1735            $query['hidediff'] = '1';
1736            $query['bot'] = '1';
1737        }
1738
1739        if ( $miserMode ) {
1740            foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1741                if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1742                    $showRollbackEditCount = false;
1743                    break;
1744                }
1745            }
1746        }
1747
1748        // The edit count can be 0 on replica lag, fall back to the generic rollbacklink message
1749        $msg = [ 'rollbacklink' ];
1750        if ( is_int( $showRollbackEditCount ) && $showRollbackEditCount > 0 ) {
1751            if ( !is_numeric( $editCount ) ) {
1752                $editCount = self::getRollbackEditCount( $revRecord );
1753            }
1754
1755            if ( $editCount > $showRollbackEditCount ) {
1756                $msg = [ 'rollbacklinkcount-morethan', Message::numParam( $showRollbackEditCount ) ];
1757            } elseif ( $editCount ) {
1758                $msg = [ 'rollbacklinkcount', Message::numParam( $editCount ) ];
1759            }
1760        }
1761
1762        $html = $context->msg( ...$msg )->parse();
1763        return self::link( $title, $html, $attrs, $query, $options );
1764    }
1765
1766    /**
1767     * Returns HTML for the "hidden categories on this page" list.
1768     *
1769     * @since 1.16.3
1770     * @param array $hiddencats Array of hidden categories
1771     *    from {@link WikiPage::getHiddenCategories} or similar
1772     * @return string HTML output
1773     */
1774    public static function formatHiddenCategories( $hiddencats ) {
1775        $outText = '';
1776        if ( count( $hiddencats ) > 0 ) {
1777            # Construct the HTML
1778            $outText = '<div class="mw-hiddenCategoriesExplanation">';
1779            $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1780            $outText .= "</div><ul>\n";
1781
1782            foreach ( $hiddencats as $titleObj ) {
1783                # If it's hidden, it must exist - no need to check with a LinkBatch
1784                $outText .= '<li>'
1785                    . self::link( $titleObj, null, [], [], 'known' )
1786                    . "</li>\n";
1787            }
1788            $outText .= '</ul>';
1789        }
1790        return $outText;
1791    }
1792
1793    /**
1794     * @return ContextSource
1795     */
1796    private static function getContextFromMain() {
1797        $context = RequestContext::getMain();
1798        // TODO: Why is this here?
1799        $context = new DerivativeContext( $context );
1800        return $context;
1801    }
1802
1803    /**
1804     * Given the id of an interface element, constructs the appropriate title
1805     * attribute from the system messages.  (Note, this is usually the id but
1806     * isn't always, because sometimes the accesskey needs to go on a different
1807     * element than the id, for reverse-compatibility, etc.)
1808     *
1809     * @since 1.16.3 $msgParams added in 1.27
1810     * @param string $name Id of the element, minus prefixes.
1811     * @param string|array|null $options Null, string or array with some of the following options:
1812     *   - 'withaccess' to add an access-key hint
1813     *   - 'nonexisting' to add an accessibility hint that page does not exist
1814     * @param array $msgParams Parameters to pass to the message
1815     * @param MessageLocalizer|null $localizer
1816     *
1817     * @return string|false Contents of the title attribute (which you must HTML-
1818     *   escape), or false for no title attribute
1819     */
1820    public static function titleAttrib( $name, $options = null, array $msgParams = [], $localizer = null ) {
1821        if ( !$localizer ) {
1822            $localizer = self::getContextFromMain();
1823        }
1824        $message = $localizer->msg( "tooltip-$name", $msgParams );
1825        // Set a default tooltip for subject namespace tabs if that hasn't
1826        // been defined. See T22126
1827        if ( !$message->exists() && str_starts_with( $name, 'ca-nstab-' ) ) {
1828            $message = $localizer->msg( 'tooltip-ca-nstab' );
1829        }
1830
1831        if ( $message->isDisabled() ) {
1832            $tooltip = false;
1833        } else {
1834            $tooltip = $message->text();
1835            # Compatibility: formerly some tooltips had [alt-.] hardcoded
1836            $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1837        }
1838
1839        $options = (array)$options;
1840
1841        if ( in_array( 'nonexisting', $options ) ) {
1842            $tooltip = $localizer->msg( 'red-link-title', $tooltip ?: '' )->text();
1843        }
1844        if ( in_array( 'withaccess', $options ) ) {
1845            $accesskey = self::accesskey( $name, $localizer );
1846            if ( $accesskey !== false ) {
1847                // Should be build the same as in jquery.accessKeyLabel.js
1848                if ( $tooltip === false || $tooltip === '' ) {
1849                    $tooltip = $localizer->msg( 'brackets', $accesskey )->text();
1850                } else {
1851                    $tooltip .= $localizer->msg( 'word-separator' )->text();
1852                    $tooltip .= $localizer->msg( 'brackets', $accesskey )->text();
1853                }
1854            }
1855        }
1856
1857        return $tooltip;
1858    }
1859
1860    /**
1861     * @internal For Linker::accesskey, exposed for MediaWikiIntegrationTestCase
1862     * @var (string|false)[]
1863     */
1864    public static $accesskeycache;
1865
1866    /**
1867     * Given the id of an interface element, constructs the appropriate
1868     * accesskey attribute from the system messages.  (Note, this is usually
1869     * the id but isn't always, because sometimes the accesskey needs to go on
1870     * a different element than the id, for reverse-compatibility, etc.)
1871     *
1872     * @since 1.16.3
1873     * @param string $name Id of the element, minus prefixes.
1874     * @param MessageLocalizer|null $localizer
1875     * @return string|false Contents of the accesskey attribute (which you must HTML-
1876     *   escape), or false for no accesskey attribute
1877     */
1878    public static function accesskey( $name, $localizer = null ) {
1879        // Optimization: Reduce from 79 to 35 fetches
1880        // Vector fetches most accesskeys 2x and "search" 6x (April 2026).
1881        // This cache was added in 2010 (r78995), and worthwhile even with message preload (r52503).
1882        //
1883        // NOTE: This assumes calls won't differ by context (i.e. wiki database, and user language).
1884        if ( !isset( self::$accesskeycache[$name] ) ) {
1885            $localizer ??= RequestContext::getMain();
1886            $msg = $localizer->msg( "accesskey-$name" );
1887            // T22126: For custom namespaces, ensure a default
1888            // Talk pages have their default in SkinTemplate::buildContentNavigationUrlsInternal.
1889            if ( !$msg->exists() && str_starts_with( $name, 'ca-nstab-' ) ) {
1890                $msg = $localizer->msg( 'accesskey-ca-nstab' );
1891            }
1892            self::$accesskeycache[$name] = $msg->isDisabled() ? false : $msg->plain();
1893        }
1894        return self::$accesskeycache[$name];
1895    }
1896
1897    /**
1898     * Get a revision-deletion link, or disabled link, or nothing, depending
1899     * on user permissions & the settings on the revision.
1900     *
1901     * Will use forward-compatible revision ID in the Special:RevDelete link
1902     * if possible, otherwise the timestamp-based ID which may break after
1903     * undeletion.
1904     *
1905     * @param Authority $performer
1906     * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1907     *    since 1.35)
1908     * @param LinkTarget $title
1909     * @return string HTML fragment
1910     */
1911    public static function getRevDeleteLink(
1912        Authority $performer,
1913        RevisionRecord $revRecord,
1914        LinkTarget $title
1915    ) {
1916        $canHide = $performer->isAllowed( 'deleterevision' );
1917        $canHideHistory = $performer->isAllowed( 'deletedhistory' );
1918        if ( !$canHide && !( $revRecord->getVisibility() && $canHideHistory ) ) {
1919            return '';
1920        }
1921
1922        if ( !$revRecord->userCan( RevisionRecord::DELETED_RESTRICTED, $performer ) ) {
1923            return self::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1924        }
1925        $prefixedDbKey = MediaWikiServices::getInstance()->getTitleFormatter()->
1926            getPrefixedDBkey( $title );
1927        if ( $revRecord->getId() ) {
1928            // RevDelete links using revision ID are stable across
1929            // page deletion and undeletion; use when possible.
1930            $query = [
1931                'type' => 'revision',
1932                'target' => $prefixedDbKey,
1933                'ids' => $revRecord->getId()
1934            ];
1935        } else {
1936            // Older deleted entries didn't save a revision ID.
1937            // We have to refer to these by timestamp, ick!
1938            $query = [
1939                'type' => 'archive',
1940                'target' => $prefixedDbKey,
1941                'ids' => $revRecord->getTimestamp()
1942            ];
1943        }
1944        return self::revDeleteLink(
1945            $query,
1946            $revRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ),
1947            $canHide
1948        );
1949    }
1950
1951    /**
1952     * Creates a (show/hide) link for deleting revisions/log entries
1953     *
1954     * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
1955     *
1956     * @param array $query Query parameters to be passed to link()
1957     * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
1958     * @param bool $delete Set to true to use (show/hide) rather than (show)
1959     *
1960     * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
1961     * span to allow for customization of appearance with CSS
1962     */
1963    public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
1964        $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
1965        $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
1966        $html = wfMessage( $msgKey )->escaped();
1967        $tag = $restricted ? 'strong' : 'span';
1968        $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
1969        return Html::rawElement(
1970            $tag,
1971            [ 'class' => 'mw-revdelundel-link' ],
1972            wfMessage( 'parentheses' )->rawParams( $link )->escaped()
1973        );
1974    }
1975
1976    /**
1977     * Creates a dead (show/hide) link for deleting revisions/log entries
1978     *
1979     * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
1980     *
1981     * @since 1.16.3
1982     * @param bool $delete Set to true to use (show/hide) rather than (show)
1983     *
1984     * @return string HTML text wrapped in a span to allow for customization
1985     * of appearance with CSS
1986     */
1987    public static function revDeleteLinkDisabled( $delete = true ) {
1988        $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
1989        $html = wfMessage( $msgKey )->escaped();
1990        $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
1991        return Html::rawElement( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
1992    }
1993
1994    /**
1995     * Returns the attributes for the tooltip and access key.
1996     *
1997     * @since 1.16.3. $msgParams introduced in 1.27
1998     * @param string $name
1999     * @param array $msgParams Params for constructing the message
2000     * @param string|array|null $options Options to be passed to titleAttrib.
2001     * @param MessageLocalizer|null $localizer
2002     *
2003     * @see Linker::titleAttrib for what options could be passed to $options.
2004     *
2005     * @return array
2006     */
2007    public static function tooltipAndAccesskeyAttribs(
2008        $name,
2009        array $msgParams = [],
2010        $options = null,
2011        $localizer = null
2012    ) {
2013        $options = (array)$options;
2014        $options[] = 'withaccess';
2015
2016        // Get optional parameters from global context if any missing.
2017        if ( !$localizer ) {
2018            $localizer = self::getContextFromMain();
2019        }
2020
2021        $attribs = [
2022            'title' => self::titleAttrib( $name, $options, $msgParams, $localizer ),
2023            'accesskey' => self::accesskey( $name, $localizer )
2024        ];
2025        if ( $attribs['title'] === false ) {
2026            unset( $attribs['title'] );
2027        }
2028        if ( $attribs['accesskey'] === false ) {
2029            unset( $attribs['accesskey'] );
2030        }
2031        return $attribs;
2032    }
2033
2034    /**
2035     * Returns raw bits of HTML, use titleAttrib()
2036     * @since 1.16.3
2037     * @param string $name
2038     * @param array|null $options
2039     * @return null|string
2040     */
2041    public static function tooltip( $name, $options = null ) {
2042        $tooltip = self::titleAttrib( $name, $options );
2043        if ( $tooltip === false ) {
2044            return '';
2045        }
2046        return Html::expandAttributes( [
2047            'title' => $tooltip
2048        ] );
2049    }
2050
2051    /**
2052     * @param array $legacyOptions
2053     * @return LinkRenderer
2054     */
2055    private static function getLinkRenderer(
2056        array $legacyOptions = []
2057    ): LinkRenderer {
2058        $services = MediaWikiServices::getInstance();
2059
2060        if ( count( $legacyOptions ) > 0 ) {
2061            return $services->getLinkRendererFactory()->createFromLegacyOptions(
2062                $legacyOptions
2063            );
2064        }
2065
2066        return $services->getLinkRenderer();
2067    }
2068
2069}