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