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