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