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