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