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