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