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