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