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