Merge "Add DROP INDEX support to DatabaseSqlite::replaceVars method"
[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 // TODO: BUG? Both values are identical
685 $params['img-class'] .= ( $params['img-class'] !== '' ) ? ' thumbborder' : 'thumbborder';
686 }
687 $params = self::getImageLinkMTOParams( $fp, $query, $parser ) + $params;
688
689 $s = $thumb->toHtml( $params );
690 }
691 if ( $fp['align'] != '' ) {
692 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
693 }
694 return str_replace( "\n", ' ', $prefix . $s . $postfix );
695 }
696
697 /**
698 * See makeImageLink()
699 * When this function is removed, remove if( $parser instanceof Parser ) check there too
700 * @deprecated since 1.20
701 */
702 public static function makeImageLink2( Title $title, $file, $frameParams = array(),
703 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
704 return self::makeImageLink( null, $title, $file, $frameParams,
705 $handlerParams, $time, $query, $widthOption );
706 }
707
708 /**
709 * Get the link parameters for MediaTransformOutput::toHtml() from given
710 * frame parameters supplied by the Parser.
711 * @param array $frameParams The frame parameters
712 * @param string $query An optional query string to add to description page links
713 * @return array
714 */
715 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
716 $mtoParams = array();
717 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
718 $mtoParams['custom-url-link'] = $frameParams['link-url'];
719 if ( isset( $frameParams['link-target'] ) ) {
720 $mtoParams['custom-target-link'] = $frameParams['link-target'];
721 }
722 if ( $parser ) {
723 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
724 foreach ( $extLinkAttrs as $name => $val ) {
725 // Currently could include 'rel' and 'target'
726 $mtoParams['parser-extlink-' . $name] = $val;
727 }
728 }
729 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
730 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
731 } elseif ( !empty( $frameParams['no-link'] ) ) {
732 // No link
733 } else {
734 $mtoParams['desc-link'] = true;
735 $mtoParams['desc-query'] = $query;
736 }
737 return $mtoParams;
738 }
739
740 /**
741 * Make HTML for a thumbnail including image, border and caption
742 * @param $title Title object
743 * @param $file File object or false if it doesn't exist
744 * @param $label String
745 * @param $alt String
746 * @param $align String
747 * @param $params Array
748 * @param $framed Boolean
749 * @param $manualthumb String
750 * @return mixed
751 */
752 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
753 $align = 'right', $params = array(), $framed = false, $manualthumb = "" )
754 {
755 $frameParams = array(
756 'alt' => $alt,
757 'caption' => $label,
758 'align' => $align
759 );
760 if ( $framed ) {
761 $frameParams['framed'] = true;
762 }
763 if ( $manualthumb ) {
764 $frameParams['manualthumb'] = $manualthumb;
765 }
766 return self::makeThumbLink2( $title, $file, $frameParams, $params );
767 }
768
769 /**
770 * @param $title Title
771 * @param $file File
772 * @param array $frameParams
773 * @param array $handlerParams
774 * @param bool $time
775 * @param string $query
776 * @return mixed
777 */
778 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
779 $handlerParams = array(), $time = false, $query = "" )
780 {
781 global $wgStylePath, $wgContLang;
782 $exists = $file && $file->exists();
783
784 # Shortcuts
785 $fp =& $frameParams;
786 $hp =& $handlerParams;
787
788 $page = isset( $hp['page'] ) ? $hp['page'] : false;
789 if ( !isset( $fp['align'] ) ) {
790 $fp['align'] = 'right';
791 }
792 if ( !isset( $fp['alt'] ) ) {
793 $fp['alt'] = '';
794 }
795 if ( !isset( $fp['title'] ) ) {
796 $fp['title'] = '';
797 }
798 if ( !isset( $fp['caption'] ) ) {
799 $fp['caption'] = '';
800 }
801
802 if ( empty( $hp['width'] ) ) {
803 // Reduce width for upright images when parameter 'upright' is used
804 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
805 }
806 $thumb = false;
807 $noscale = false;
808 $manualthumb = false;
809
810 if ( !$exists ) {
811 $outerWidth = $hp['width'] + 2;
812 } else {
813 if ( isset( $fp['manualthumb'] ) ) {
814 # Use manually specified thumbnail
815 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
816 if ( $manual_title ) {
817 $manual_img = wfFindFile( $manual_title );
818 if ( $manual_img ) {
819 $thumb = $manual_img->getUnscaledThumb( $hp );
820 $manualthumb = true;
821 } else {
822 $exists = false;
823 }
824 }
825 } elseif ( isset( $fp['framed'] ) ) {
826 // Use image dimensions, don't scale
827 $thumb = $file->getUnscaledThumb( $hp );
828 $noscale = true;
829 } else {
830 # Do not present an image bigger than the source, for bitmap-style images
831 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
832 $srcWidth = $file->getWidth( $page );
833 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
834 $hp['width'] = $srcWidth;
835 }
836 $thumb = $file->transform( $hp );
837 }
838
839 if ( $thumb ) {
840 $outerWidth = $thumb->getWidth() + 2;
841 } else {
842 $outerWidth = $hp['width'] + 2;
843 }
844 }
845
846 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
847 # So we don't need to pass it here in $query. However, the URL for the
848 # zoom icon still needs it, so we make a unique query for it. See bug 14771
849 $url = $title->getLocalURL( $query );
850 if ( $page ) {
851 $url = wfAppendQuery( $url, array( 'page' => $page ) );
852 }
853 if ( $manualthumb &&
854 !isset( $fp['link-title'] ) &&
855 !isset( $fp['link-url'] ) &&
856 !isset( $fp['no-link'] ) ) {
857 $fp['link-url'] = $url;
858 }
859
860 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
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'] !== '' ) ? $fp['class'] . ' thumbimage' : 'thumbimage'
875 );
876 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
877 $s .= $thumb->toHtml( $params );
878 if ( isset( $fp['framed'] ) ) {
879 $zoomIcon = "";
880 } else {
881 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
882 Html::rawElement( 'a', array(
883 'href' => $url,
884 'class' => 'internal',
885 'title' => wfMessage( 'thumbnail-more' )->text() ),
886 Html::element( 'img', array(
887 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ? '-rtl' : '' ) . '.png',
888 'width' => 15,
889 'height' => 11,
890 'alt' => "" ) ) ) );
891 }
892 }
893 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
894 return str_replace( "\n", ' ', $s );
895 }
896
897 /**
898 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
899 * applicable.
900 *
901 * @param File $file
902 * @param MediaOutput $thumb
903 * @param array $hp image parameters
904 */
905 protected static function processResponsiveImages( $file, $thumb, $hp ) {
906 global $wgResponsiveImages;
907 if ( $wgResponsiveImages ) {
908 $hp15 = $hp;
909 $hp15['width'] = round( $hp['width'] * 1.5 );
910 $hp20 = $hp;
911 $hp20['width'] = $hp['width'] * 2;
912 if ( isset( $hp['height'] ) ) {
913 $hp15['height'] = round( $hp['height'] * 1.5 );
914 $hp20['height'] = $hp['height'] * 2;
915 }
916
917 $thumb15 = $file->transform( $hp15 );
918 $thumb20 = $file->transform( $hp20 );
919 if ( $thumb15->url !== $thumb->url ) {
920 $thumb->responsiveUrls['1.5'] = $thumb15->url;
921 }
922 if ( $thumb20->url !== $thumb->url ) {
923 $thumb->responsiveUrls['2'] = $thumb20->url;
924 }
925 }
926 }
927
928 /**
929 * Make a "broken" link to an image
930 *
931 * @param $title Title object
932 * @param string $label link label (plain text)
933 * @param string $query query string
934 * @param $unused1 Unused parameter kept for b/c
935 * @param $unused2 Unused parameter kept for b/c
936 * @param $time Boolean: a file of a certain timestamp was requested
937 * @return String
938 */
939 public static function makeBrokenImageLinkObj( $title, $label = '', $query = '', $unused1 = '', $unused2 = '', $time = false ) {
940 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
941 if ( ! $title instanceof Title ) {
942 return "<!-- ERROR -->" . htmlspecialchars( $label );
943 }
944 wfProfileIn( __METHOD__ );
945 if ( $label == '' ) {
946 $label = $title->getPrefixedText();
947 }
948 $encLabel = htmlspecialchars( $label );
949 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
950
951 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
952 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
953
954 if ( $redir ) {
955 wfProfileOut( __METHOD__ );
956 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
957 }
958
959 $href = self::getUploadUrl( $title, $query );
960
961 wfProfileOut( __METHOD__ );
962 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
963 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
964 $encLabel . '</a>';
965 }
966
967 wfProfileOut( __METHOD__ );
968 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
969 }
970
971 /**
972 * Get the URL to upload a certain file
973 *
974 * @param $destFile Title object of the file to upload
975 * @param string $query urlencoded query string to prepend
976 * @return String: urlencoded URL
977 */
978 protected static function getUploadUrl( $destFile, $query = '' ) {
979 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
980 $q = 'wpDestFile=' . $destFile->getPartialURL();
981 if ( $query != '' ) {
982 $q .= '&' . $query;
983 }
984
985 if ( $wgUploadMissingFileUrl ) {
986 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
987 } elseif ( $wgUploadNavigationUrl ) {
988 return wfAppendQuery( $wgUploadNavigationUrl, $q );
989 } else {
990 $upload = SpecialPage::getTitleFor( 'Upload' );
991 return $upload->getLocalURL( $q );
992 }
993 }
994
995 /**
996 * Create a direct link to a given uploaded file.
997 *
998 * @param $title Title object.
999 * @param string $html pre-sanitized HTML
1000 * @param string $time MW timestamp of file creation time
1001 * @return String: HTML
1002 */
1003 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
1004 $img = wfFindFile( $title, array( 'time' => $time ) );
1005 return self::makeMediaLinkFile( $title, $img, $html );
1006 }
1007
1008 /**
1009 * Create a direct link to a given uploaded file.
1010 * This will make a broken link if $file is false.
1011 *
1012 * @param $title Title object.
1013 * @param $file File|bool mixed File object or false
1014 * @param string $html pre-sanitized HTML
1015 * @return String: HTML
1016 *
1017 * @todo Handle invalid or missing images better.
1018 */
1019 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
1020 if ( $file && $file->exists() ) {
1021 $url = $file->getURL();
1022 $class = 'internal';
1023 } else {
1024 $url = self::getUploadUrl( $title );
1025 $class = 'new';
1026 }
1027 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES );
1028 if ( $html == '' ) {
1029 $html = $alt;
1030 }
1031 $u = htmlspecialchars( $url );
1032 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
1033 }
1034
1035 /**
1036 * Make a link to a special page given its name and, optionally,
1037 * a message key from the link text.
1038 * Usage example: Linker::specialLink( 'Recentchanges' )
1039 *
1040 * @return string
1041 */
1042 public static function specialLink( $name, $key = '' ) {
1043 if ( $key == '' ) {
1044 $key = strtolower( $name );
1045 }
1046
1047 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1048 }
1049
1050 /**
1051 * Make an external link
1052 * @param string $url URL to link to
1053 * @param string $text text of link
1054 * @param $escape Boolean: do we escape the link text?
1055 * @param string $linktype type of external link. Gets added to the classes
1056 * @param array $attribs of extra attributes to <a>
1057 * @param $title Title|null Title object used for title specific link attributes
1058 * @return string
1059 */
1060 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array(), $title = null ) {
1061 global $wgTitle;
1062 $class = "external";
1063 if ( $linktype ) {
1064 $class .= " $linktype";
1065 }
1066 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1067 $class .= " {$attribs['class']}";
1068 }
1069 $attribs['class'] = $class;
1070
1071 if ( $escape ) {
1072 $text = htmlspecialchars( $text );
1073 }
1074
1075 if ( !$title ) {
1076 $title = $wgTitle;
1077 }
1078 $attribs['rel'] = Parser::getExternalLinkRel( $url, $title );
1079 $link = '';
1080 $success = wfRunHooks( 'LinkerMakeExternalLink',
1081 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1082 if ( !$success ) {
1083 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
1084 return $link;
1085 }
1086 $attribs['href'] = $url;
1087 return Html::rawElement( 'a', $attribs, $text );
1088 }
1089
1090 /**
1091 * Make user link (or user contributions for unregistered users)
1092 * @param $userId Integer: user id in database.
1093 * @param string $userName user name in database.
1094 * @param string $altUserName text to display instead of the user name (optional)
1095 * @return String: HTML fragment
1096 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1097 */
1098 public static function userLink( $userId, $userName, $altUserName = false ) {
1099 if ( $userId == 0 ) {
1100 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1101 if ( $altUserName === false ) {
1102 $altUserName = IP::prettifyIP( $userName );
1103 }
1104 } else {
1105 $page = Title::makeTitle( NS_USER, $userName );
1106 }
1107
1108 return self::link(
1109 $page,
1110 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1111 array( 'class' => 'mw-userlink' )
1112 );
1113 }
1114
1115 /**
1116 * Generate standard user tool links (talk, contributions, block link, etc.)
1117 *
1118 * @param $userId Integer: user identifier
1119 * @param string $userText user name or IP address
1120 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1121 * red if the user has no edits?
1122 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1123 * @param $edits Integer: user edit count (optional, for performance)
1124 * @return String: HTML fragment
1125 */
1126 public static function userToolLinks(
1127 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1128 ) {
1129 global $wgUser, $wgDisableAnonTalk, $wgLang;
1130 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1131 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1132 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1133
1134 $items = array();
1135 if ( $talkable ) {
1136 $items[] = self::userTalkLink( $userId, $userText );
1137 }
1138 if ( $userId ) {
1139 // check if the user has an edit
1140 $attribs = array();
1141 if ( $redContribsWhenNoEdits ) {
1142 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1143 $user = User::newFromId( $userId );
1144 $edits = $user->getEditCount();
1145 }
1146 if ( $edits === 0 ) {
1147 $attribs['class'] = 'new';
1148 }
1149 }
1150 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1151
1152 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1153 }
1154 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1155 $items[] = self::blockLink( $userId, $userText );
1156 }
1157
1158 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1159 $items[] = self::emailLink( $userId, $userText );
1160 }
1161
1162 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1163
1164 if ( $items ) {
1165 return wfMessage( 'word-separator' )->plain()
1166 . '<span class="mw-usertoollinks">'
1167 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1168 . '</span>';
1169 } else {
1170 return '';
1171 }
1172 }
1173
1174 /**
1175 * Alias for userToolLinks( $userId, $userText, true );
1176 * @param $userId Integer: user identifier
1177 * @param string $userText user name or IP address
1178 * @param $edits Integer: user edit count (optional, for performance)
1179 * @return String
1180 */
1181 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1182 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1183 }
1184
1185 /**
1186 * @param $userId Integer: user id in database.
1187 * @param string $userText user name in database.
1188 * @return String: HTML fragment with user talk link
1189 */
1190 public static function userTalkLink( $userId, $userText ) {
1191 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1192 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1193 return $userTalkLink;
1194 }
1195
1196 /**
1197 * @param $userId Integer: userid
1198 * @param string $userText user name in database.
1199 * @return String: HTML fragment with block link
1200 */
1201 public static function blockLink( $userId, $userText ) {
1202 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1203 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1204 return $blockLink;
1205 }
1206
1207 /**
1208 * @param $userId Integer: userid
1209 * @param string $userText user name in database.
1210 * @return String: HTML fragment with e-mail user link
1211 */
1212 public static function emailLink( $userId, $userText ) {
1213 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1214 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1215 return $emailLink;
1216 }
1217
1218 /**
1219 * Generate a user link if the current user is allowed to view it
1220 * @param $rev Revision object.
1221 * @param $isPublic Boolean: show only if all users can see it
1222 * @return String: HTML fragment
1223 */
1224 public static function revUserLink( $rev, $isPublic = false ) {
1225 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1226 $link = wfMessage( 'rev-deleted-user' )->escaped();
1227 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1228 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1229 $rev->getUserText( Revision::FOR_THIS_USER ) );
1230 } else {
1231 $link = wfMessage( 'rev-deleted-user' )->escaped();
1232 }
1233 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1234 return '<span class="history-deleted">' . $link . '</span>';
1235 }
1236 return $link;
1237 }
1238
1239 /**
1240 * Generate a user tool link cluster if the current user is allowed to view it
1241 * @param $rev Revision object.
1242 * @param $isPublic Boolean: show only if all users can see it
1243 * @return string HTML
1244 */
1245 public static function revUserTools( $rev, $isPublic = false ) {
1246 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1247 $link = wfMessage( 'rev-deleted-user' )->escaped();
1248 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1249 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1250 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1251 $link = self::userLink( $userId, $userText )
1252 . wfMessage( 'word-separator' )->plain()
1253 . self::userToolLinks( $userId, $userText );
1254 } else {
1255 $link = wfMessage( 'rev-deleted-user' )->escaped();
1256 }
1257 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1258 return ' <span class="history-deleted">' . $link . '</span>';
1259 }
1260 return $link;
1261 }
1262
1263 /**
1264 * This function is called by all recent changes variants, by the page history,
1265 * and by the user contributions list. It is responsible for formatting edit
1266 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1267 * auto-generated comments (from section editing) and formats [[wikilinks]].
1268 *
1269 * @author Erik Moeller <moeller@scireview.de>
1270 *
1271 * Note: there's not always a title to pass to this function.
1272 * Since you can't set a default parameter for a reference, I've turned it
1273 * temporarily to a value pass. Should be adjusted further. --brion
1274 *
1275 * @param $comment String
1276 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1277 * @param $local Boolean: whether section links should refer to local page
1278 * @return mixed|String
1279 */
1280 public static function formatComment( $comment, $title = null, $local = false ) {
1281 wfProfileIn( __METHOD__ );
1282
1283 # Sanitize text a bit:
1284 $comment = str_replace( "\n", " ", $comment );
1285 # Allow HTML entities (for bug 13815)
1286 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1287
1288 # Render autocomments and make links:
1289 $comment = self::formatAutocomments( $comment, $title, $local );
1290 $comment = self::formatLinksInComment( $comment, $title, $local );
1291
1292 wfProfileOut( __METHOD__ );
1293 return $comment;
1294 }
1295
1296 /**
1297 * @var Title
1298 */
1299 static $autocommentTitle;
1300 static $autocommentLocal;
1301
1302 /**
1303 * Converts autogenerated comments in edit summaries into section links.
1304 * The pattern for autogen comments is / * foo * /, which makes for
1305 * some nasty regex.
1306 * We look for all comments, match any text before and after the comment,
1307 * add a separator where needed and format the comment itself with CSS
1308 * Called by Linker::formatComment.
1309 *
1310 * @param string $comment comment text
1311 * @param $title Title|null An optional title object used to links to sections
1312 * @param $local Boolean: whether section links should refer to local page
1313 * @return String: formatted comment
1314 */
1315 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1316 // Bah!
1317 self::$autocommentTitle = $title;
1318 self::$autocommentLocal = $local;
1319 $comment = preg_replace_callback(
1320 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1321 array( 'Linker', 'formatAutocommentsCallback' ),
1322 $comment );
1323 self::$autocommentTitle = null;
1324 self::$autocommentLocal = null;
1325 return $comment;
1326 }
1327
1328 /**
1329 * Helper function for Linker::formatAutocomments
1330 * @param $match
1331 * @return string
1332 */
1333 private static function formatAutocommentsCallback( $match ) {
1334 global $wgLang;
1335 $title = self::$autocommentTitle;
1336 $local = self::$autocommentLocal;
1337
1338 $pre = $match[1];
1339 $auto = $match[2];
1340 $post = $match[3];
1341 $comment = null;
1342 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1343 if ( $comment === null ) {
1344 $link = '';
1345 if ( $title ) {
1346 $section = $auto;
1347
1348 # Remove links that a user may have manually put in the autosummary
1349 # This could be improved by copying as much of Parser::stripSectionName as desired.
1350 $section = str_replace( '[[:', '', $section );
1351 $section = str_replace( '[[', '', $section );
1352 $section = str_replace( ']]', '', $section );
1353
1354 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1355 if ( $local ) {
1356 $sectionTitle = Title::newFromText( '#' . $section );
1357 } else {
1358 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1359 $title->getDBkey(), $section );
1360 }
1361 if ( $sectionTitle ) {
1362 $link = self::link( $sectionTitle,
1363 $wgLang->getArrow(), array(), array(),
1364 'noclasses' );
1365 } else {
1366 $link = '';
1367 }
1368 }
1369 if ( $pre ) {
1370 # written summary $presep autocomment (summary /* section */)
1371 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1372 }
1373 if ( $post ) {
1374 # autocomment $postsep written summary (/* section */ summary)
1375 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1376 }
1377 $auto = '<span class="autocomment">' . $auto . '</span>';
1378 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1379 }
1380 return $comment;
1381 }
1382
1383 /**
1384 * @var Title
1385 */
1386 static $commentContextTitle;
1387 static $commentLocal;
1388
1389 /**
1390 * Formats wiki links and media links in text; all other wiki formatting
1391 * is ignored
1392 *
1393 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1394 * @param string $comment text to format links in
1395 * @param $title Title|null An optional title object used to links to sections
1396 * @param $local Boolean: whether section links should refer to local page
1397 * @return String
1398 */
1399 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1400 self::$commentContextTitle = $title;
1401 self::$commentLocal = $local;
1402 $html = preg_replace_callback(
1403 '/
1404 \[\[
1405 :? # ignore optional leading colon
1406 ([^\]|]+) # 1. link target; page names cannot include ] or |
1407 (?:\|
1408 # 2. a pipe-separated substring; only the last is captured
1409 # Stop matching at | and ]] without relying on backtracking.
1410 ((?:]?[^\]|])*+)
1411 )*
1412 \]\]
1413 ([^[]*) # 3. link trail (the text up until the next link)
1414 /x',
1415 array( 'Linker', 'formatLinksInCommentCallback' ),
1416 $comment );
1417 self::$commentContextTitle = null;
1418 self::$commentLocal = null;
1419 return $html;
1420 }
1421
1422 /**
1423 * @param $match
1424 * @return mixed
1425 */
1426 protected static function formatLinksInCommentCallback( $match ) {
1427 global $wgContLang;
1428
1429 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1430 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1431
1432 $comment = $match[0];
1433
1434 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1435 if ( strpos( $match[1], '%' ) !== false ) {
1436 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1437 }
1438
1439 # Handle link renaming [[foo|text]] will show link as "text"
1440 if ( $match[2] != "" ) {
1441 $text = $match[2];
1442 } else {
1443 $text = $match[1];
1444 }
1445 $submatch = array();
1446 $thelink = null;
1447 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1448 # Media link; trail not supported.
1449 $linkRegexp = '/\[\[(.*?)\]\]/';
1450 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1451 if ( $title ) {
1452 $thelink = self::makeMediaLinkObj( $title, $text );
1453 }
1454 } else {
1455 # Other kind of link
1456 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1457 $trail = $submatch[1];
1458 } else {
1459 $trail = "";
1460 }
1461 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1462 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1463 $match[1] = substr( $match[1], 1 );
1464 }
1465 list( $inside, $trail ) = self::splitTrail( $trail );
1466
1467 $linkText = $text;
1468 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1469 $match[1], $linkText );
1470
1471 $target = Title::newFromText( $linkTarget );
1472 if ( $target ) {
1473 if ( $target->getText() == '' && $target->getInterwiki() === ''
1474 && !self::$commentLocal && self::$commentContextTitle )
1475 {
1476 $newTarget = clone ( self::$commentContextTitle );
1477 $newTarget->setFragment( '#' . $target->getFragment() );
1478 $target = $newTarget;
1479 }
1480 $thelink = self::link(
1481 $target,
1482 $linkText . $inside
1483 ) . $trail;
1484 }
1485 }
1486 if ( $thelink ) {
1487 // If the link is still valid, go ahead and replace it in!
1488 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1489 }
1490
1491 return $comment;
1492 }
1493
1494 /**
1495 * @param $contextTitle Title
1496 * @param $target
1497 * @param $text
1498 * @return string
1499 */
1500 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1501 # Valid link forms:
1502 # Foobar -- normal
1503 # :Foobar -- override special treatment of prefix (images, language links)
1504 # /Foobar -- convert to CurrentPage/Foobar
1505 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1506 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1507 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1508
1509 wfProfileIn( __METHOD__ );
1510 $ret = $target; # default return value is no change
1511
1512 # Some namespaces don't allow subpages,
1513 # so only perform processing if subpages are allowed
1514 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1515 $hash = strpos( $target, '#' );
1516 if ( $hash !== false ) {
1517 $suffix = substr( $target, $hash );
1518 $target = substr( $target, 0, $hash );
1519 } else {
1520 $suffix = '';
1521 }
1522 # bug 7425
1523 $target = trim( $target );
1524 # Look at the first character
1525 if ( $target != '' && $target[0] === '/' ) {
1526 # / at end means we don't want the slash to be shown
1527 $m = array();
1528 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1529 if ( $trailingSlashes ) {
1530 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1531 } else {
1532 $noslash = substr( $target, 1 );
1533 }
1534
1535 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1536 if ( $text === '' ) {
1537 $text = $target . $suffix;
1538 } # this might be changed for ugliness reasons
1539 } else {
1540 # check for .. subpage backlinks
1541 $dotdotcount = 0;
1542 $nodotdot = $target;
1543 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1544 ++$dotdotcount;
1545 $nodotdot = substr( $nodotdot, 3 );
1546 }
1547 if ( $dotdotcount > 0 ) {
1548 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1549 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1550 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1551 # / at the end means don't show full path
1552 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1553 $nodotdot = substr( $nodotdot, 0, -1 );
1554 if ( $text === '' ) {
1555 $text = $nodotdot . $suffix;
1556 }
1557 }
1558 $nodotdot = trim( $nodotdot );
1559 if ( $nodotdot != '' ) {
1560 $ret .= '/' . $nodotdot;
1561 }
1562 $ret .= $suffix;
1563 }
1564 }
1565 }
1566 }
1567
1568 wfProfileOut( __METHOD__ );
1569 return $ret;
1570 }
1571
1572 /**
1573 * Wrap a comment in standard punctuation and formatting if
1574 * it's non-empty, otherwise return empty string.
1575 *
1576 * @param $comment String
1577 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1578 * @param $local Boolean: whether section links should refer to local page
1579 *
1580 * @return string
1581 */
1582 public static function commentBlock( $comment, $title = null, $local = false ) {
1583 // '*' used to be the comment inserted by the software way back
1584 // in antiquity in case none was provided, here for backwards
1585 // compatibility, acc. to brion -ævar
1586 if ( $comment == '' || $comment == '*' ) {
1587 return '';
1588 } else {
1589 $formatted = self::formatComment( $comment, $title, $local );
1590 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1591 return " <span class=\"comment\">$formatted</span>";
1592 }
1593 }
1594
1595 /**
1596 * Wrap and format the given revision's comment block, if the current
1597 * user is allowed to view it.
1598 *
1599 * @param $rev Revision object
1600 * @param $local Boolean: whether section links should refer to local page
1601 * @param $isPublic Boolean: show only if all users can see it
1602 * @return String: HTML fragment
1603 */
1604 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1605 if ( $rev->getRawComment() == "" ) {
1606 return "";
1607 }
1608 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1609 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1610 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1611 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1612 $rev->getTitle(), $local );
1613 } else {
1614 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1615 }
1616 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1617 return " <span class=\"history-deleted\">$block</span>";
1618 }
1619 return $block;
1620 }
1621
1622 /**
1623 * @param $size
1624 * @return string
1625 */
1626 public static function formatRevisionSize( $size ) {
1627 if ( $size == 0 ) {
1628 $stxt = wfMessage( 'historyempty' )->escaped();
1629 } else {
1630 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1631 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1632 }
1633 return "<span class=\"history-size\">$stxt</span>";
1634 }
1635
1636 /**
1637 * Add another level to the Table of Contents
1638 *
1639 * @return string
1640 */
1641 public static function tocIndent() {
1642 return "\n<ul>";
1643 }
1644
1645 /**
1646 * Finish one or more sublevels on the Table of Contents
1647 *
1648 * @return string
1649 */
1650 public static function tocUnindent( $level ) {
1651 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1652 }
1653
1654 /**
1655 * parameter level defines if we are on an indentation level
1656 *
1657 * @return string
1658 */
1659 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1660 $classes = "toclevel-$level";
1661 if ( $sectionIndex !== false ) {
1662 $classes .= " tocsection-$sectionIndex";
1663 }
1664 return "\n<li class=\"$classes\"><a href=\"#" .
1665 $anchor . '"><span class="tocnumber">' .
1666 $tocnumber . '</span> <span class="toctext">' .
1667 $tocline . '</span></a>';
1668 }
1669
1670 /**
1671 * End a Table Of Contents line.
1672 * tocUnindent() will be used instead if we're ending a line below
1673 * the new level.
1674 * @return string
1675 */
1676 public static function tocLineEnd() {
1677 return "</li>\n";
1678 }
1679
1680 /**
1681 * Wraps the TOC in a table and provides the hide/collapse javascript.
1682 *
1683 * @param string $toc html of the Table Of Contents
1684 * @param $lang String|Language|false: Language for the toc title, defaults to user language
1685 * @return String: full html of the TOC
1686 */
1687 public static function tocList( $toc, $lang = false ) {
1688 $lang = wfGetLangObj( $lang );
1689 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1690
1691 return '<div id="toc" class="toc">'
1692 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1693 . $toc
1694 . "</ul>\n</div>\n";
1695 }
1696
1697 /**
1698 * Generate a table of contents from a section tree
1699 * Currently unused.
1700 *
1701 * @param array $tree Return value of ParserOutput::getSections()
1702 * @return String: HTML fragment
1703 */
1704 public static function generateTOC( $tree ) {
1705 $toc = '';
1706 $lastLevel = 0;
1707 foreach ( $tree as $section ) {
1708 if ( $section['toclevel'] > $lastLevel ) {
1709 $toc .= self::tocIndent();
1710 } elseif ( $section['toclevel'] < $lastLevel ) {
1711 $toc .= self::tocUnindent(
1712 $lastLevel - $section['toclevel'] );
1713 } else {
1714 $toc .= self::tocLineEnd();
1715 }
1716
1717 $toc .= self::tocLine( $section['anchor'],
1718 $section['line'], $section['number'],
1719 $section['toclevel'], $section['index'] );
1720 $lastLevel = $section['toclevel'];
1721 }
1722 $toc .= self::tocLineEnd();
1723 return self::tocList( $toc );
1724 }
1725
1726 /**
1727 * Create a headline for content
1728 *
1729 * @param $level Integer: the level of the headline (1-6)
1730 * @param string $attribs any attributes for the headline, starting with
1731 * a space and ending with '>'
1732 * This *must* be at least '>' for no attribs
1733 * @param string $anchor the anchor to give the headline (the bit after the #)
1734 * @param string $html html for the text of the header
1735 * @param string $link HTML to add for the section edit link
1736 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1737 * backward compatibility (false to omit)
1738 *
1739 * @return String: HTML headline
1740 */
1741 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1742 $ret = "<h$level$attribs"
1743 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1744 . $link
1745 . "</h$level>";
1746 if ( $legacyAnchor !== false ) {
1747 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1748 }
1749 return $ret;
1750 }
1751
1752 /**
1753 * Split a link trail, return the "inside" portion and the remainder of the trail
1754 * as a two-element array
1755 * @return array
1756 */
1757 static function splitTrail( $trail ) {
1758 global $wgContLang;
1759 $regex = $wgContLang->linkTrail();
1760 $inside = '';
1761 if ( $trail !== '' ) {
1762 $m = array();
1763 if ( preg_match( $regex, $trail, $m ) ) {
1764 $inside = $m[1];
1765 $trail = $m[2];
1766 }
1767 }
1768 return array( $inside, $trail );
1769 }
1770
1771 /**
1772 * Generate a rollback link for a given revision. Currently it's the
1773 * caller's responsibility to ensure that the revision is the top one. If
1774 * it's not, of course, the user will get an error message.
1775 *
1776 * If the calling page is called with the parameter &bot=1, all rollback
1777 * links also get that parameter. It causes the edit itself and the rollback
1778 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1779 * changes, so this allows sysops to combat a busy vandal without bothering
1780 * other users.
1781 *
1782 * If the option verify is set this function will return the link only in case the
1783 * revision can be reverted. Please note that due to performance limitations
1784 * it might be assumed that a user isn't the only contributor of a page while
1785 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1786 * work if $wgShowRollbackEditCount is disabled, so this can only function
1787 * as an additional check.
1788 *
1789 * If the option noBrackets is set the rollback link wont be enclosed in []
1790 *
1791 * @param $rev Revision object
1792 * @param $context IContextSource context to use or null for the main context.
1793 * @param $options array
1794 * @return string
1795 */
1796 public static function generateRollback( $rev, IContextSource $context = null, $options = array( 'verify' ) ) {
1797 if ( $context === null ) {
1798 $context = RequestContext::getMain();
1799 }
1800 $editCount = false;
1801 if ( in_array( 'verify', $options ) ) {
1802 $editCount = self::getRollbackEditCount( $rev, true );
1803 if ( $editCount === false ) {
1804 return '';
1805 }
1806 }
1807
1808 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1809
1810 if ( !in_array( 'noBrackets', $options ) ) {
1811 $inner = $context->msg( 'brackets' )->rawParams( $inner )->plain();
1812 }
1813
1814 return '<span class="mw-rollback-link">' . $inner . '</span>';
1815 }
1816
1817 /**
1818 * This function will return the number of revisions which a rollback
1819 * would revert and, if $verify is set it will verify that a revision
1820 * can be reverted (that the user isn't the only contributor and the
1821 * revision we might rollback to isn't deleted). These checks can only
1822 * function as an additional check as this function only checks against
1823 * the last $wgShowRollbackEditCount edits.
1824 *
1825 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1826 * is set and the user is the only contributor of the page.
1827 *
1828 * @param $rev Revision object
1829 * @param bool $verify Try to verify that this revision can really be rolled back
1830 * @return integer|bool|null
1831 */
1832 public static function getRollbackEditCount( $rev, $verify ) {
1833 global $wgShowRollbackEditCount;
1834 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1835 // Nothing has happened, indicate this by returning 'null'
1836 return null;
1837 }
1838
1839 $dbr = wfGetDB( DB_SLAVE );
1840
1841 // Up to the value of $wgShowRollbackEditCount revisions are counted
1842 $res = $dbr->select(
1843 'revision',
1844 array( 'rev_user_text', 'rev_deleted' ),
1845 // $rev->getPage() returns null sometimes
1846 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1847 __METHOD__,
1848 array(
1849 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1850 'ORDER BY' => 'rev_timestamp DESC',
1851 'LIMIT' => $wgShowRollbackEditCount + 1
1852 )
1853 );
1854
1855 $editCount = 0;
1856 $moreRevs = false;
1857 foreach ( $res as $row ) {
1858 if ( $rev->getRawUserText() != $row->rev_user_text ) {
1859 if ( $verify && ( $row->rev_deleted & Revision::DELETED_TEXT || $row->rev_deleted & Revision::DELETED_USER ) ) {
1860 // If the user or the text of the revision we might rollback to is deleted in some way we can't rollback
1861 // Similar to the sanity checks in WikiPage::commitRollback
1862 return false;
1863 }
1864 $moreRevs = true;
1865 break;
1866 }
1867 $editCount++;
1868 }
1869
1870 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1871 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1872 // and there weren't any other revisions. That means that the current user is the only
1873 // editor, so we can't rollback
1874 return false;
1875 }
1876 return $editCount;
1877 }
1878
1879 /**
1880 * Build a raw rollback link, useful for collections of "tool" links
1881 *
1882 * @param $rev Revision object
1883 * @param $context IContextSource context to use or null for the main context.
1884 * @param $editCount integer Number of edits that would be reverted
1885 * @return String: HTML fragment
1886 */
1887 public static function buildRollbackLink( $rev, IContextSource $context = null, $editCount = false ) {
1888 global $wgShowRollbackEditCount, $wgMiserMode;
1889
1890 // To config which pages are effected by miser mode
1891 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1892
1893 if ( $context === null ) {
1894 $context = RequestContext::getMain();
1895 }
1896
1897 $title = $rev->getTitle();
1898 $query = array(
1899 'action' => 'rollback',
1900 'from' => $rev->getUserText(),
1901 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1902 );
1903 if ( $context->getRequest()->getBool( 'bot' ) ) {
1904 $query['bot'] = '1';
1905 $query['hidediff'] = '1'; // bug 15999
1906 }
1907
1908 $disableRollbackEditCount = false;
1909 if ( $wgMiserMode ) {
1910 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1911 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1912 $disableRollbackEditCount = true;
1913 break;
1914 }
1915 }
1916 }
1917
1918 if ( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1919 if ( !is_numeric( $editCount ) ) {
1920 $editCount = self::getRollbackEditCount( $rev, false );
1921 }
1922
1923 if ( $editCount > $wgShowRollbackEditCount ) {
1924 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1925 } else {
1926 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1927 }
1928
1929 return self::link(
1930 $title,
1931 $editCount_output,
1932 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1933 $query,
1934 array( 'known', 'noclasses' )
1935 );
1936 } else {
1937 return self::link(
1938 $title,
1939 $context->msg( 'rollbacklink' )->escaped(),
1940 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1941 $query,
1942 array( 'known', 'noclasses' )
1943 );
1944 }
1945 }
1946
1947 /**
1948 * Returns HTML for the "templates used on this page" list.
1949 *
1950 * Make an HTML list of templates, and then add a "More..." link at
1951 * the bottom. If $more is null, do not add a "More..." link. If $more
1952 * is a Title, make a link to that title and use it. If $more is a string,
1953 * directly paste it in as the link (escaping needs to be done manually).
1954 * Finally, if $more is a Message, call toString().
1955 *
1956 * @param array $templates Array of templates from Article::getUsedTemplate or similar
1957 * @param bool $preview Whether this is for a preview
1958 * @param bool $section Whether this is for a section edit
1959 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1960 * @return String: HTML output
1961 */
1962 public static function formatTemplates( $templates, $preview = false, $section = false, $more = null ) {
1963 global $wgLang;
1964 wfProfileIn( __METHOD__ );
1965
1966 $outText = '';
1967 if ( count( $templates ) > 0 ) {
1968 # Do a batch existence check
1969 $batch = new LinkBatch;
1970 foreach ( $templates as $title ) {
1971 $batch->addObj( $title );
1972 }
1973 $batch->execute();
1974
1975 # Construct the HTML
1976 $outText = '<div class="mw-templatesUsedExplanation">';
1977 if ( $preview ) {
1978 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1979 ->parseAsBlock();
1980 } elseif ( $section ) {
1981 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
1982 ->parseAsBlock();
1983 } else {
1984 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
1985 ->parseAsBlock();
1986 }
1987 $outText .= "</div><ul>\n";
1988
1989 usort( $templates, 'Title::compare' );
1990 foreach ( $templates as $titleObj ) {
1991 $protected = '';
1992 $restrictions = $titleObj->getRestrictions( 'edit' );
1993 if ( $restrictions ) {
1994 // Check backwards-compatible messages
1995 $msg = null;
1996 if ( $restrictions === array( 'sysop' ) ) {
1997 $msg = wfMessage( 'template-protected' );
1998 } elseif ( $restrictions === array( 'autoconfirmed' ) ) {
1999 $msg = wfMessage( 'template-semiprotected' );
2000 }
2001 if ( $msg && !$msg->isDisabled() ) {
2002 $protected = $msg->parse();
2003 } else {
2004 // Construct the message from restriction-level-*
2005 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2006 $msgs = array();
2007 foreach ( $restrictions as $r ) {
2008 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2009 }
2010 $protected = wfMessage( 'parentheses' )
2011 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2012 }
2013 }
2014 if ( $titleObj->quickUserCan( 'edit' ) ) {
2015 $editLink = self::link(
2016 $titleObj,
2017 wfMessage( 'editlink' )->text(),
2018 array(),
2019 array( 'action' => 'edit' )
2020 );
2021 } else {
2022 $editLink = self::link(
2023 $titleObj,
2024 wfMessage( 'viewsourcelink' )->text(),
2025 array(),
2026 array( 'action' => 'edit' )
2027 );
2028 }
2029 $outText .= '<li>' . self::link( $titleObj )
2030 . wfMessage( 'word-separator' )->escaped()
2031 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2032 . wfMessage( 'word-separator' )->escaped()
2033 . $protected . '</li>';
2034 }
2035
2036 if ( $more instanceof Title ) {
2037 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2038 } elseif ( $more ) {
2039 $outText .= "<li>$more</li>";
2040 }
2041
2042 $outText .= '</ul>';
2043 }
2044 wfProfileOut( __METHOD__ );
2045 return $outText;
2046 }
2047
2048 /**
2049 * Returns HTML for the "hidden categories on this page" list.
2050 *
2051 * @param array $hiddencats of hidden categories from Article::getHiddenCategories
2052 * or similar
2053 * @return String: HTML output
2054 */
2055 public static function formatHiddenCategories( $hiddencats ) {
2056 wfProfileIn( __METHOD__ );
2057
2058 $outText = '';
2059 if ( count( $hiddencats ) > 0 ) {
2060 # Construct the HTML
2061 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2062 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2063 $outText .= "</div><ul>\n";
2064
2065 foreach ( $hiddencats as $titleObj ) {
2066 $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
2067 }
2068 $outText .= '</ul>';
2069 }
2070 wfProfileOut( __METHOD__ );
2071 return $outText;
2072 }
2073
2074 /**
2075 * Format a size in bytes for output, using an appropriate
2076 * unit (B, KB, MB or GB) according to the magnitude in question
2077 *
2078 * @param int $size Size to format
2079 * @return String
2080 */
2081 public static function formatSize( $size ) {
2082 global $wgLang;
2083 return htmlspecialchars( $wgLang->formatSize( $size ) );
2084 }
2085
2086 /**
2087 * Given the id of an interface element, constructs the appropriate title
2088 * attribute from the system messages. (Note, this is usually the id but
2089 * isn't always, because sometimes the accesskey needs to go on a different
2090 * element than the id, for reverse-compatibility, etc.)
2091 *
2092 * @param string $name id of the element, minus prefixes.
2093 * @param $options Mixed: null or the string 'withaccess' to add an access-
2094 * key hint
2095 * @return String: contents of the title attribute (which you must HTML-
2096 * escape), or false for no title attribute
2097 */
2098 public static function titleAttrib( $name, $options = null ) {
2099 wfProfileIn( __METHOD__ );
2100
2101 $message = wfMessage( "tooltip-$name" );
2102
2103 if ( !$message->exists() ) {
2104 $tooltip = false;
2105 } else {
2106 $tooltip = $message->text();
2107 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2108 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2109 # Message equal to '-' means suppress it.
2110 if ( $tooltip == '-' ) {
2111 $tooltip = false;
2112 }
2113 }
2114
2115 if ( $options == 'withaccess' ) {
2116 $accesskey = self::accesskey( $name );
2117 if ( $accesskey !== false ) {
2118 if ( $tooltip === false || $tooltip === '' ) {
2119 $tooltip = wfMessage( 'brackets', $accesskey )->escaped();
2120 } else {
2121 $tooltip .= wfMessage( 'word-separator' )->escaped();
2122 $tooltip .= wfMessage( 'brackets', $accesskey )->escaped();
2123 }
2124 }
2125 }
2126
2127 wfProfileOut( __METHOD__ );
2128 return $tooltip;
2129 }
2130
2131 static $accesskeycache;
2132
2133 /**
2134 * Given the id of an interface element, constructs the appropriate
2135 * accesskey attribute from the system messages. (Note, this is usually
2136 * the id but isn't always, because sometimes the accesskey needs to go on
2137 * a different element than the id, for reverse-compatibility, etc.)
2138 *
2139 * @param string $name id of the element, minus prefixes.
2140 * @return String: contents of the accesskey attribute (which you must HTML-
2141 * escape), or false for no accesskey attribute
2142 */
2143 public static function accesskey( $name ) {
2144 if ( isset( self::$accesskeycache[$name] ) ) {
2145 return self::$accesskeycache[$name];
2146 }
2147 wfProfileIn( __METHOD__ );
2148
2149 $message = wfMessage( "accesskey-$name" );
2150
2151 if ( !$message->exists() ) {
2152 $accesskey = false;
2153 } else {
2154 $accesskey = $message->plain();
2155 if ( $accesskey === '' || $accesskey === '-' ) {
2156 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2157 # attribute, but this is broken for accesskey: that might be a useful
2158 # value.
2159 $accesskey = false;
2160 }
2161 }
2162
2163 wfProfileOut( __METHOD__ );
2164 return self::$accesskeycache[$name] = $accesskey;
2165 }
2166
2167 /**
2168 * Get a revision-deletion link, or disabled link, or nothing, depending
2169 * on user permissions & the settings on the revision.
2170 *
2171 * Will use forward-compatible revision ID in the Special:RevDelete link
2172 * if possible, otherwise the timestamp-based ID which may break after
2173 * undeletion.
2174 *
2175 * @param User $user
2176 * @param Revision $rev
2177 * @param Revision $title
2178 * @return string HTML fragment
2179 */
2180 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2181 $canHide = $user->isAllowed( 'deleterevision' );
2182 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2183 return '';
2184 }
2185
2186 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2187 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2188 } else {
2189 if ( $rev->getId() ) {
2190 // RevDelete links using revision ID are stable across
2191 // page deletion and undeletion; use when possible.
2192 $query = array(
2193 'type' => 'revision',
2194 'target' => $title->getPrefixedDBkey(),
2195 'ids' => $rev->getId()
2196 );
2197 } else {
2198 // Older deleted entries didn't save a revision ID.
2199 // We have to refer to these by timestamp, ick!
2200 $query = array(
2201 'type' => 'archive',
2202 'target' => $title->getPrefixedDBkey(),
2203 'ids' => $rev->getTimestamp()
2204 );
2205 }
2206 return Linker::revDeleteLink( $query,
2207 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2208 }
2209 }
2210
2211 /**
2212 * Creates a (show/hide) link for deleting revisions/log entries
2213 *
2214 * @param array $query query parameters to be passed to link()
2215 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2216 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2217 *
2218 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2219 * span to allow for customization of appearance with CSS
2220 */
2221 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2222 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2223 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2224 $html = wfMessage( $msgKey )->escaped();
2225 $tag = $restricted ? 'strong' : 'span';
2226 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2227 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2228 }
2229
2230 /**
2231 * Creates a dead (show/hide) link for deleting revisions/log entries
2232 *
2233 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2234 *
2235 * @return string HTML text wrapped in a span to allow for customization
2236 * of appearance with CSS
2237 */
2238 public static function revDeleteLinkDisabled( $delete = true ) {
2239 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2240 $html = wfMessage( $msgKey )->escaped();
2241 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2242 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2243 }
2244
2245 /* Deprecated methods */
2246
2247 /**
2248 * @deprecated since 1.16 Use link()
2249 *
2250 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2251 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2252 *
2253 * @param string $title The text of the title
2254 * @param string $text Link text
2255 * @param string $query Optional query part
2256 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2257 * be included in the link text. Other characters will be appended after
2258 * the end of the link.
2259 * @return string
2260 */
2261 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2262 wfDeprecated( __METHOD__, '1.16' );
2263
2264 $nt = Title::newFromText( $title );
2265 if ( $nt instanceof Title ) {
2266 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
2267 } else {
2268 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2269 return $text == '' ? $title : $text;
2270 }
2271 }
2272
2273 /**
2274 * @deprecated since 1.16 Use link(); warnings since 1.21
2275 *
2276 * Make a link for a title which may or may not be in the database. If you need to
2277 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2278 * call to this will result in a DB query.
2279 *
2280 * @param $nt Title: the title object to make the link from, e.g. from
2281 * Title::newFromText.
2282 * @param $text String: link text
2283 * @param string $query optional query part
2284 * @param string $trail optional trail. Alphabetic characters at the start of this string will
2285 * be included in the link text. Other characters will be appended after
2286 * the end of the link.
2287 * @param string $prefix optional prefix. As trail, only before instead of after.
2288 * @return string
2289 */
2290 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2291 wfDeprecated( __METHOD__, '1.21' );
2292
2293 wfProfileIn( __METHOD__ );
2294 $query = wfCgiToArray( $query );
2295 list( $inside, $trail ) = self::splitTrail( $trail );
2296 if ( $text === '' ) {
2297 $text = self::linkText( $nt );
2298 }
2299
2300 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2301
2302 wfProfileOut( __METHOD__ );
2303 return $ret;
2304 }
2305
2306 /**
2307 * @deprecated since 1.16 Use link(); warnings since 1.21
2308 *
2309 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2310 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2311 * pages.
2312 *
2313 * @param $title Title object of target page
2314 * @param $text String: text to replace the title
2315 * @param $query String: link target
2316 * @param $trail String: text after link
2317 * @param string $prefix text before link text
2318 * @param string $aprops extra attributes to the a-element
2319 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2320 * @return string the a-element
2321 */
2322 static function makeKnownLinkObj(
2323 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2324 ) {
2325 wfDeprecated( __METHOD__, '1.21' );
2326
2327 wfProfileIn( __METHOD__ );
2328
2329 if ( $text == '' ) {
2330 $text = self::linkText( $title );
2331 }
2332 $attribs = Sanitizer::mergeAttributes(
2333 Sanitizer::decodeTagAttributes( $aprops ),
2334 Sanitizer::decodeTagAttributes( $style )
2335 );
2336 $query = wfCgiToArray( $query );
2337 list( $inside, $trail ) = self::splitTrail( $trail );
2338
2339 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2340 array( 'known', 'noclasses' ) ) . $trail;
2341
2342 wfProfileOut( __METHOD__ );
2343 return $ret;
2344 }
2345
2346 /**
2347 * @deprecated since 1.16 Use link()
2348 *
2349 * Make a red link to the edit page of a given title.
2350 *
2351 * @param $title Title object of the target page
2352 * @param $text String: Link text
2353 * @param string $query Optional query part
2354 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2355 * be included in the link text. Other characters will be appended after
2356 * the end of the link.
2357 * @param string $prefix Optional prefix
2358 * @return string
2359 */
2360 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2361 wfDeprecated( __METHOD__, '1.16' );
2362
2363 wfProfileIn( __METHOD__ );
2364
2365 list( $inside, $trail ) = self::splitTrail( $trail );
2366 if ( $text === '' ) {
2367 $text = self::linkText( $title );
2368 }
2369
2370 $ret = self::link( $title, "$prefix$text$inside", array(),
2371 wfCgiToArray( $query ), 'broken' ) . $trail;
2372
2373 wfProfileOut( __METHOD__ );
2374 return $ret;
2375 }
2376
2377 /**
2378 * @deprecated since 1.16 Use link()
2379 *
2380 * Make a coloured link.
2381 *
2382 * @param $nt Title object of the target page
2383 * @param $colour Integer: colour of the link
2384 * @param $text String: link text
2385 * @param $query String: optional query part
2386 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2387 * be included in the link text. Other characters will be appended after
2388 * the end of the link.
2389 * @param string $prefix Optional prefix
2390 * @return string
2391 */
2392 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2393 wfDeprecated( __METHOD__, '1.16' );
2394
2395 if ( $colour != '' ) {
2396 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
2397 } else {
2398 $style = '';
2399 }
2400 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2401 }
2402
2403 /**
2404 * Returns the attributes for the tooltip and access key.
2405 * @return array
2406 */
2407 public static function tooltipAndAccesskeyAttribs( $name ) {
2408 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2409 # no attribute" instead of "output '' as value for attribute", this
2410 # would be three lines.
2411 $attribs = array(
2412 'title' => self::titleAttrib( $name, 'withaccess' ),
2413 'accesskey' => self::accesskey( $name )
2414 );
2415 if ( $attribs['title'] === false ) {
2416 unset( $attribs['title'] );
2417 }
2418 if ( $attribs['accesskey'] === false ) {
2419 unset( $attribs['accesskey'] );
2420 }
2421 return $attribs;
2422 }
2423
2424 /**
2425 * Returns raw bits of HTML, use titleAttrib()
2426 * @return null|string
2427 */
2428 public static function tooltip( $name, $options = null ) {
2429 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2430 # no attribute" instead of "output '' as value for attribute", this
2431 # would be two lines.
2432 $tooltip = self::titleAttrib( $name, $options );
2433 if ( $tooltip === false ) {
2434 return '';
2435 }
2436 return Xml::expandAttributes( array(
2437 'title' => $tooltip
2438 ) );
2439 }
2440 }
2441
2442 /**
2443 * @since 1.18
2444 */
2445 class DummyLinker {
2446
2447 /**
2448 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2449 * into static calls to the new Linker for backwards compatibility.
2450 *
2451 * @param string $fname Name of called method
2452 * @param array $args Arguments to the method
2453 * @return mixed
2454 */
2455 public function __call( $fname, $args ) {
2456 return call_user_func_array( array( 'Linker', $fname ), $args );
2457 }
2458 }