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