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