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