3 * Split off some of the internal bits from Skin.php. These functions are used
4 * for primarily page content: links, embedded images, table of contents. Links
5 * are also used in the skin. For the moment, Skin is a descendent class of
6 * Linker. In the future, it should probably be further split so that every
7 * other bit of the wiki doesn't have to go loading up Skin to get at it.
14 * Flags for userToolLinks()
16 const TOOL_LINKS_NOBLOCK
= 1;
18 function __construct() {}
21 * Get the appropriate HTML attributes to add to the "a" element of an ex-
22 * ternal link, as created by [wikisyntax].
24 * @param $class String: the contents of the class attribute; if an empty
25 * string is passed, which is the default value, defaults to 'external'.
27 function getExternalLinkAttributes( $class = 'external' ) {
28 return $this->getLinkAttributesInternal( '', $class );
32 * Get the appropriate HTML attributes to add to the "a" element of an in-
35 * @param $title String: the title text for the link, URL-encoded (???) but
37 * @param $unused String: unused
38 * @param $class String: the contents of the class attribute; if an empty
39 * string is passed, which is the default value, defaults to 'external'.
41 function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
44 # FIXME: We have a whole bunch of handling here that doesn't happen in
45 # getExternalLinkAttributes, why?
46 $title = urldecode( $title );
47 $title = $wgContLang->checkTitleEncoding( $title );
48 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
50 return $this->getLinkAttributesInternal( $title, $class );
54 * Get the appropriate HTML attributes to add to the "a" element of an in-
57 * @param $title String: the title text for the link, URL-encoded (???) but
59 * @param $unused String: unused
60 * @param $class String: the contents of the class attribute, default none
62 function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
63 $title = urldecode( $title );
64 $title = str_replace( '_', ' ', $title );
65 return $this->getLinkAttributesInternal( $title, $class );
69 * Get the appropriate HTML attributes to add to the "a" element of an in-
70 * ternal link, given the Title object for the page we want to link to.
72 * @param $nt The Title object
73 * @param $unused String: unused
74 * @param $class String: the contents of the class attribute, default none
75 * @param $title Mixed: optional (unescaped) string to use in the title
76 * attribute; if false, default to the name of the page we're linking to
78 function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
79 if ( $title === false ) {
80 $title = $nt->getPrefixedText();
82 return $this->getLinkAttributesInternal( $title, $class );
86 * Common code for getLinkAttributesX functions
88 private function getLinkAttributesInternal( $title, $class ) {
89 $title = htmlspecialchars( $title );
90 $class = htmlspecialchars( $class );
93 $r .= " class=\"$class\"";
96 $r .= " title=\"$title\"";
102 * Return the CSS colour of a known link
104 * @param $t Title object
105 * @param $threshold Integer: user defined threshold
106 * @return String: CSS class
108 function getLinkColour( $t, $threshold ) {
110 if ( $t->isRedirect() ) {
112 $colour = 'mw-redirect';
113 } elseif ( $threshold > 0 &&
114 $t->exists() && $t->getLength() < $threshold &&
115 $t->isContentPage() ) {
123 * This function returns an HTML link to the given target. It serves a few
125 * 1) If $target is a Title, the correct URL to link to will be figured
127 * 2) It automatically adds the usual classes for various types of link
128 * targets: "new" for red links, "stub" for short articles, etc.
129 * 3) It escapes all attribute values safely so there's no risk of XSS.
130 * 4) It provides a default tooltip if the target is a Title (the page
131 * name of the target).
132 * link() replaces the old functions in the makeLink() family.
134 * @param $target Title Can currently only be a Title, but this may
135 * change to support Images, literal URLs, etc.
136 * @param $text string The HTML contents of the <a> element, i.e.,
137 * the link text. This is raw HTML and will not be escaped. If null,
138 * defaults to the prefixed text of the Title; or if the Title is just a
139 * fragment, the contents of the fragment.
140 * @param $customAttribs array A key => value array of extra HTML attri-
141 * butes, such as title and class. (href is ignored.) Classes will be
142 * merged with the default classes, while other attributes will replace
143 * default attributes. All passed attribute values will be HTML-escaped.
144 * A false attribute value means to suppress that attribute.
145 * @param $query array The query string to append to the URL
146 * you're linking to, in key => value array form. Query keys and values
147 * will be URL-encoded.
148 * @param $options mixed String or array of strings:
149 * 'known': Page is known to exist, so don't check if it does.
150 * 'broken': Page is known not to exist, so don't check if it does.
151 * 'noclasses': Don't add any classes automatically (includes "new",
152 * "stub", "mw-redirect", "extiw"). Only use the class attribute
153 * provided, if any, so you get a simple blue link with no funny i-
155 * 'forcearticlepath': Use the article path always, even with a querystring.
156 * Has compatibility issues on some setups, so avoid wherever possible.
157 * @return string HTML <a> attribute
159 public function link( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
160 wfProfileIn( __METHOD__
);
161 if ( !$target instanceof Title
) {
162 return "<!-- ERROR -->$text";
164 $options = (array)$options;
167 if ( !wfRunHooks( 'LinkBegin', array( $this, $target, &$text,
168 &$customAttribs, &$query, &$options, &$ret ) ) ) {
169 wfProfileOut( __METHOD__
);
173 # Normalize the Title if it's a special page
174 $target = $this->normaliseSpecialPage( $target );
176 # If we don't know whether the page exists, let's find out.
177 wfProfileIn( __METHOD__
. '-checkPageExistence' );
178 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
179 if ( $target->isKnown() ) {
180 $options[] = 'known';
182 $options[] = 'broken';
185 wfProfileOut( __METHOD__
. '-checkPageExistence' );
188 if ( in_array( "forcearticlepath", $options ) && $query ) {
193 # Note: we want the href attribute first, for prettiness.
194 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
195 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
196 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
199 $attribs = array_merge(
201 $this->linkAttribs( $target, $customAttribs, $options, $text )
203 if ( is_null( $text ) ) {
204 $text = $this->linkText( $target );
208 if ( wfRunHooks( 'LinkEnd', array( $this, $target, $options, &$text, &$attribs, &$ret ) ) ) {
209 $ret = Html
::rawElement( 'a', $attribs, $text );
212 wfProfileOut( __METHOD__
);
217 * Identical to link(), except $options defaults to 'known'.
219 public function linkKnown( $target, $text = null, $customAttribs = array(), $query = array(), $options = array( 'known', 'noclasses' ) ) {
220 return $this->link( $target, $text, $customAttribs, $query, $options );
224 * Returns the Url used to link to a Title
226 private function linkUrl( $target, $query, $options ) {
227 wfProfileIn( __METHOD__
);
228 # We don't want to include fragments for broken links, because they
229 # generally make no sense.
230 if ( in_array( 'broken', $options ) and $target->mFragment
!== '' ) {
231 $target = clone $target;
232 $target->mFragment
= '';
235 # If it's a broken link, add the appropriate query pieces, unless
236 # there's already an action specified, or unless 'edit' makes no sense
237 # (i.e., for a nonexistent special page).
238 if ( in_array( 'broken', $options ) and empty( $query['action'] )
239 and $target->getNamespace() != NS_SPECIAL
) {
240 $query['action'] = 'edit';
241 $query['redlink'] = '1';
243 $ret = $target->getLinkUrl( $query );
244 wfProfileOut( __METHOD__
);
249 * Returns the array of attributes used when linking to the Title $target
251 private function linkAttribs( $target, $attribs, $options, $linkText ) {
252 wfProfileIn( __METHOD__
);
256 if ( !in_array( 'noclasses', $options ) ) {
257 wfProfileIn( __METHOD__
. '-getClasses' );
258 # Now build the classes.
261 if ( in_array( 'broken', $options ) ) {
265 if ( $target->isExternal() ) {
266 $classes[] = 'extiw';
269 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
270 $colour = $this->getLinkColour( $target, $wgUser->getStubThreshold() );
271 if ( $colour !== '' ) {
272 $classes[] = $colour; # mw-redirect or stub
275 if ( $classes != array() ) {
276 $defaults['class'] = implode( ' ', $classes );
278 wfProfileOut( __METHOD__
. '-getClasses' );
281 # Get a default title attribute.
282 $known = in_array( 'known', $options );
283 if ( $target->getPrefixedText() == '' ) {
284 # A link like [[#Foo]]. This used to mean an empty title
285 # attribute, but that's silly. Just don't output a title.
286 } elseif ( $known && strtolower($linkText) !== strtolower($target->getPrefixedText() ) ) {
287 $defaults['title'] = $target->getPrefixedText();
288 } elseif ( !$known ) {
289 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
292 # Finally, merge the custom attribs with the default ones, and iterate
293 # over that, deleting all "false" attributes.
295 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
296 foreach ( $merged as $key => $val ) {
297 # A false value suppresses the attribute, and we don't want the
298 # href attribute to be overridden.
299 if ( $key != 'href' and $val !== false ) {
303 wfProfileOut( __METHOD__
);
308 * Default text of the links to the Title $target
310 private function linkText( $target ) {
311 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
312 if ( !$target instanceof Title
) {
316 # If the target is just a fragment, with no title, we return the frag-
317 # ment text. Otherwise, we return the title text itself.
318 if ( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
319 return htmlspecialchars( $target->getFragment() );
321 return htmlspecialchars( $target->getPrefixedText() );
325 * Generate either a normal exists-style link or a stub link, depending
326 * on the given page size.
328 * @param $size Integer
329 * @param $nt Title object.
330 * @param $text String
331 * @param $query String
332 * @param $trail String
333 * @param $prefix String
334 * @return string HTML of link
337 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
339 wfDeprecated( __METHOD__
);
341 $threshold = $wgUser->getStubThreshold();
342 $colour = ( $size < $threshold ) ?
'stub' : '';
343 // FIXME: replace deprecated makeColouredLinkObj by link()
344 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
348 * Make appropriate markup for a link to the current article. This is currently rendered
349 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
350 * despite $query not being used.
352 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
354 $text = htmlspecialchars( $nt->getPrefixedText() );
356 list( $inside, $trail ) = Linker
::splitTrail( $trail );
357 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
360 function normaliseSpecialPage( Title
$title ) {
361 if ( $title->getNamespace() == NS_SPECIAL
) {
362 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
366 $ret = SpecialPage
::getTitleFor( $name, $subpage );
367 $ret->mFragment
= $title->getFragment();
375 * Returns the filename part of an url.
376 * Used as alternative text for external images.
378 function fnamePart( $url ) {
379 $basename = strrchr( $url, '/' );
380 if ( false === $basename ) {
383 $basename = substr( $basename, 1 );
389 * Return the code for images which were added via external links,
390 * via Parser::maybeMakeExternalImage().
392 function makeExternalImage( $url, $alt = '' ) {
394 $alt = $this->fnamePart( $url );
397 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
399 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
402 return Html
::element( 'img',
409 * Given parameters derived from [[Image:Foo|options...]], generate the
410 * HTML that that syntax inserts in the page.
412 * @param $title Title object
413 * @param $file File object, or false if it doesn't exist
414 * @param $frameParams Array: associative array of parameters external to the media handler.
415 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
416 * will often be false.
417 * thumbnail If present, downscale and frame
418 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
419 * framed Shows image in original size in a frame
420 * frameless Downscale but don't frame
421 * upright If present, tweak default sizes for portrait orientation
422 * upright_factor Fudge factor for "upright" tweak (default 0.75)
423 * border If present, show a border around the image
424 * align Horizontal alignment (left, right, center, none)
425 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
426 * bottom, text-bottom)
427 * alt Alternate text for image (i.e. alt attribute). Plain text.
428 * caption HTML for image caption.
429 * link-url URL to link to
430 * link-title Title object to link to
431 * no-link Boolean, suppress description link
433 * @param $handlerParams Array: associative array of media handler parameters, to be passed
434 * to transform(). Typical keys are "width" and "page".
435 * @param $time String: timestamp of the file, set as false for current
436 * @param $query String: query params for desc url
437 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
438 * @return String: HTML for an image, with links, wrappers, etc.
440 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
442 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
443 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
447 if ( $file && !$file->allowInlineDisplay() ) {
448 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
449 return $this->link( $title );
454 $hp =& $handlerParams;
456 // Clean up parameters
457 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
458 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
459 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
460 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
462 $prefix = $postfix = '';
464 if ( 'center' == $fp['align'] ) {
465 $prefix = '<div class="center">';
467 $fp['align'] = 'none';
469 if ( $file && !isset( $hp['width'] ) ) {
470 $hp['width'] = $file->getWidth( $page );
472 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
473 global $wgThumbLimits, $wgThumbUpright;
474 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
475 $widthOption = User
::getDefaultOption( 'thumbsize' );
478 // Reduce width for upright images when parameter 'upright' is used
479 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
480 $fp['upright'] = $wgThumbUpright;
482 // 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
483 $prefWidth = isset( $fp['upright'] ) ?
484 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
485 $wgThumbLimits[$widthOption];
487 // Use width which is smaller: real image width or user preference width
488 // Unless image is scalable vector.
489 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
490 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
491 $hp['width'] = $prefWidth;
496 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
498 # Create a thumbnail. Alignment depends on language
499 # writing direction, # right aligned for left-to-right-
500 # languages ("Western languages"), left-aligned
501 # for right-to-left-languages ("Semitic languages")
503 # If thumbnail width has not been provided, it is set
504 # to the default user option as specified in Language*.php
505 if ( $fp['align'] == '' ) {
506 $fp['align'] = $wgContLang->alignEnd();
508 return $prefix . $this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
511 if ( $file && isset( $fp['frameless'] ) ) {
512 $srcWidth = $file->getWidth( $page );
513 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
514 # This is the same behaviour as the "thumb" option does it already.
515 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
516 $hp['width'] = $srcWidth;
520 if ( $file && isset( $hp['width'] ) ) {
521 # Create a resized image, without the additional thumbnail features
522 $thumb = $file->transform( $hp );
528 $s = $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
532 'title' => $fp['title'],
533 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
534 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
535 $params = $this->getImageLinkMTOParams( $fp, $query ) +
$params;
537 $s = $thumb->toHtml( $params );
539 if ( $fp['align'] != '' ) {
540 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
542 return str_replace( "\n", ' ', $prefix . $s . $postfix );
546 * Get the link parameters for MediaTransformOutput::toHtml() from given
547 * frame parameters supplied by the Parser.
548 * @param $frameParams The frame parameters
549 * @param $query An optional query string to add to description page links
551 function getImageLinkMTOParams( $frameParams, $query = '' ) {
552 $mtoParams = array();
553 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
554 $mtoParams['custom-url-link'] = $frameParams['link-url'];
555 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
556 $mtoParams['custom-title-link'] = $frameParams['link-title'];
557 } elseif ( !empty( $frameParams['no-link'] ) ) {
560 $mtoParams['desc-link'] = true;
561 $mtoParams['desc-query'] = $query;
567 * Make HTML for a thumbnail including image, border and caption
568 * @param $title Title object
569 * @param $file File object or false if it doesn't exist
570 * @param $label String
572 * @param $align String
573 * @param $params Array
574 * @param $framed Boolean
575 * @param $manualthumb String
577 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed = false , $manualthumb = "" ) {
578 $frameParams = array(
583 if ( $framed ) $frameParams['framed'] = true;
584 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
585 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
588 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
590 $exists = $file && $file->exists();
594 $hp =& $handlerParams;
596 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
597 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
598 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
599 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
600 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
602 if ( empty( $hp['width'] ) ) {
603 // Reduce width for upright images when parameter 'upright' is used
604 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
609 $outerWidth = $hp['width'] +
2;
611 if ( isset( $fp['manualthumb'] ) ) {
612 # Use manually specified thumbnail
613 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
614 if ( $manual_title ) {
615 $manual_img = wfFindFile( $manual_title );
617 $thumb = $manual_img->getUnscaledThumb( $hp );
622 } elseif ( isset( $fp['framed'] ) ) {
623 // Use image dimensions, don't scale
624 $thumb = $file->getUnscaledThumb( $hp );
626 # Do not present an image bigger than the source, for bitmap-style images
627 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
628 $srcWidth = $file->getWidth( $page );
629 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
630 $hp['width'] = $srcWidth;
632 $thumb = $file->transform( $hp );
636 $outerWidth = $thumb->getWidth() +
2;
638 $outerWidth = $hp['width'] +
2;
642 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
643 # So we don't need to pass it here in $query. However, the URL for the
644 # zoom icon still needs it, so we make a unique query for it. See bug 14771
645 $url = $title->getLocalURL( $query );
647 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
650 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
652 $s .= $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
654 } elseif ( !$thumb ) {
655 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
660 'title' => $fp['title'],
661 'img-class' => 'thumbimage' );
662 $params = $this->getImageLinkMTOParams( $fp, $query ) +
$params;
663 $s .= $thumb->toHtml( $params );
664 if ( isset( $fp['framed'] ) ) {
667 $zoomIcon = '<div class="magnify">' .
668 '<a href="' . htmlspecialchars( $url ) . '" class="internal" ' .
669 'title="' . htmlspecialchars( wfMsg( 'thumbnail-more' ) ) . '">' .
670 '<img src="' . htmlspecialchars( $wgStylePath ) . '/common/images/magnify-clip.png" ' .
671 'width="15" height="11" alt="" /></a></div>';
674 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
675 return str_replace( "\n", ' ', $s );
679 * Make a "broken" link to an image
681 * @param $title Title object
682 * @param $text String: link label
683 * @param $query String: query string
684 * @param $trail String: link trail
685 * @param $prefix String: link prefix
686 * @param $time Boolean: a file of a certain timestamp was requested
689 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
690 global $wgEnableUploads, $wgUploadMissingFileUrl;
691 if ( $title instanceof Title
) {
692 wfProfileIn( __METHOD__
);
693 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
695 list( $inside, $trail ) = self
::splitTrail( $trail );
697 $text = htmlspecialchars( $title->getPrefixedText() );
699 if ( ( $wgUploadMissingFileUrl ||
$wgEnableUploads ) && !$currentExists ) {
700 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
703 wfProfileOut( __METHOD__
);
704 return $this->linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
707 $href = $this->getUploadUrl( $title, $query );
709 wfProfileOut( __METHOD__
);
710 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
711 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
712 htmlspecialchars( $prefix . $text . $inside, ENT_NOQUOTES
) . '</a>' . $trail;
714 wfProfileOut( __METHOD__
);
715 return $this->linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
718 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
723 * Get the URL to upload a certain file
725 * @param $destFile Title object of the file to upload
726 * @param $query String: urlencoded query string to prepend
727 * @return String: urlencoded URL
729 protected function getUploadUrl( $destFile, $query = '' ) {
730 global $wgUploadMissingFileUrl;
731 $q = 'wpDestFile=' . $destFile->getPartialUrl();
735 if ( $wgUploadMissingFileUrl ) {
736 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
738 $upload = SpecialPage
::getTitleFor( 'Upload' );
739 return $upload->getLocalUrl( $q );
744 * Create a direct link to a given uploaded file.
746 * @param $title Title object.
747 * @param $text String: pre-sanitized HTML
748 * @param $time string: time image was created
749 * @return String: HTML
751 * @todo Handle invalid or missing images better.
753 public function makeMediaLinkObj( $title, $text = '', $time = false ) {
754 if ( is_null( $title ) ) {
755 # # # HOTFIX. Instead of breaking, return empty string.
758 $img = wfFindFile( $title, array( 'time' => $time ) );
760 $url = $img->getURL();
763 $url = $this->getUploadUrl( $title );
766 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
770 $u = htmlspecialchars( $url );
771 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
776 * Make a link to a special page given its name and, optionally,
777 * a message key from the link text.
778 * Usage example: $skin->specialLink( 'recentchanges' )
780 function specialLink( $name, $key = '' ) {
781 if ( $key == '' ) { $key = strtolower( $name ); }
783 return $this->linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
787 * Make an external link
788 * @param $url String: URL to link to
789 * @param $text String: text of link
790 * @param $escape Boolean: do we escape the link text?
791 * @param $linktype String: type of external link. Gets added to the classes
792 * @param $attribs Array of extra attributes to <a>
794 * @todo FIXME: This is a really crappy implementation. $linktype and
795 * 'external' are mashed into the class attrib for the link (which is made
796 * into a string). Then, if we've got additional params in $attribs, we
797 * add to it. People using this might want to change the classes (or other
798 * default link attributes), but passing $attribsText is just messy. Would
799 * make a lot more sense to make put the classes into $attribs, let the
800 * hook play with them, *then* expand it all at once.
802 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
803 if ( isset( $attribs['class'] ) ) {
804 # yet another hack :(
805 $class = $attribs['class'];
807 $class = "external $linktype";
810 $attribsText = $this->getExternalLinkAttributes( $class );
811 $url = htmlspecialchars( $url );
813 $text = htmlspecialchars( $text );
816 $success = wfRunHooks( 'LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
818 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
822 $attribsText .= Html
::expandAttributes( $attribs );
824 return '<a href="' . $url . '"' . $attribsText . '>' . $text . '</a>';
828 * Make user link (or user contributions for unregistered users)
829 * @param $userId Integer: user id in database.
830 * @param $userText String: user name in database
831 * @return String: HTML fragment
834 function userLink( $userId, $userText ) {
835 if ( $userId == 0 ) {
836 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
838 $page = Title
::makeTitle( NS_USER
, $userText );
840 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
844 * Generate standard user tool links (talk, contributions, block link, etc.)
846 * @param $userId Integer: user identifier
847 * @param $userText String: user name or IP address
848 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
849 * red if the user has no edits?
850 * @param $flags Integer: customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
851 * @param $edits Integer: user edit count (optional, for performance)
852 * @return String: HTML fragment
854 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null ) {
855 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans, $wgLang;
856 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
857 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
861 $items[] = $this->userTalkLink( $userId, $userText );
864 // check if the user has an edit
866 if ( $redContribsWhenNoEdits ) {
867 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
869 $attribs['class'] = 'new';
872 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
874 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
876 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
877 $items[] = $this->blockLink( $userId, $userText );
881 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
888 * Alias for userToolLinks( $userId, $userText, true );
889 * @param $userId Integer: user identifier
890 * @param $userText String: user name or IP address
891 * @param $edits Integer: user edit count (optional, for performance)
893 public function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
894 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
899 * @param $userId Integer: user id in database.
900 * @param $userText String: user name in database.
901 * @return String: HTML fragment with user talk link
904 function userTalkLink( $userId, $userText ) {
905 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
906 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
907 return $userTalkLink;
911 * @param $userId Integer: userid
912 * @param $userText String: user name in database.
913 * @return String: HTML fragment with block link
916 function blockLink( $userId, $userText ) {
917 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
918 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
923 * Generate a user link if the current user is allowed to view it
924 * @param $rev Revision object.
925 * @param $isPublic Boolean: show only if all users can see it
926 * @return String: HTML fragment
928 function revUserLink( $rev, $isPublic = false ) {
929 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
930 $link = wfMsgHtml( 'rev-deleted-user' );
931 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
932 $link = $this->userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
933 $rev->getUserText( Revision
::FOR_THIS_USER
) );
935 $link = wfMsgHtml( 'rev-deleted-user' );
937 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
938 return '<span class="history-deleted">' . $link . '</span>';
944 * Generate a user tool link cluster if the current user is allowed to view it
945 * @param $rev Revision object.
946 * @param $isPublic Boolean: show only if all users can see it
947 * @return string HTML
949 function revUserTools( $rev, $isPublic = false ) {
950 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
951 $link = wfMsgHtml( 'rev-deleted-user' );
952 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
953 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
954 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
955 $link = $this->userLink( $userId, $userText ) .
956 ' ' . $this->userToolLinks( $userId, $userText );
958 $link = wfMsgHtml( 'rev-deleted-user' );
960 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
961 return ' <span class="history-deleted">' . $link . '</span>';
967 * This function is called by all recent changes variants, by the page history,
968 * and by the user contributions list. It is responsible for formatting edit
969 * comments. It escapes any HTML in the comment, but adds some CSS to format
970 * auto-generated comments (from section editing) and formats [[wikilinks]].
972 * @author Erik Moeller <moeller@scireview.de>
974 * Note: there's not always a title to pass to this function.
975 * Since you can't set a default parameter for a reference, I've turned it
976 * temporarily to a value pass. Should be adjusted further. --brion
978 * @param $comment String
979 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
980 * @param $local Boolean: whether section links should refer to local page
982 function formatComment( $comment, $title = null, $local = false ) {
983 wfProfileIn( __METHOD__
);
985 # Sanitize text a bit:
986 $comment = str_replace( "\n", " ", $comment );
987 # Allow HTML entities (for bug 13815)
988 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
990 # Render autocomments and make links:
991 $comment = $this->formatAutocomments( $comment, $title, $local );
992 $comment = $this->formatLinksInComment( $comment, $title, $local );
994 wfProfileOut( __METHOD__
);
999 * The pattern for autogen comments is / * foo * /, which makes for
1001 * We look for all comments, match any text before and after the comment,
1002 * add a separator where needed and format the comment itself with CSS
1003 * Called by Linker::formatComment.
1005 * @param $comment String: comment text
1006 * @param $title An optional title object used to links to sections
1007 * @param $local Boolean: whether section links should refer to local page
1008 * @return String: formatted comment
1010 private function formatAutocomments( $comment, $title = null, $local = false ) {
1012 $this->autocommentTitle
= $title;
1013 $this->autocommentLocal
= $local;
1014 $comment = preg_replace_callback(
1015 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1016 array( $this, 'formatAutocommentsCallback' ),
1018 unset( $this->autocommentTitle
);
1019 unset( $this->autocommentLocal
);
1023 private function formatAutocommentsCallback( $match ) {
1024 $title = $this->autocommentTitle
;
1025 $local = $this->autocommentLocal
;
1034 # Remove links that a user may have manually put in the autosummary
1035 # This could be improved by copying as much of Parser::stripSectionName as desired.
1036 $section = str_replace( '[[:', '', $section );
1037 $section = str_replace( '[[', '', $section );
1038 $section = str_replace( ']]', '', $section );
1040 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1042 $sectionTitle = Title
::newFromText( '#' . $section );
1044 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1045 $title->getDBkey(), $section );
1047 if ( $sectionTitle ) {
1048 $link = $this->link( $sectionTitle,
1049 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1055 $auto = "$link$auto";
1057 # written summary $presep autocomment (summary /* section */)
1058 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1061 # autocomment $postsep written summary (/* section */ summary)
1062 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1064 $auto = '<span class="autocomment">' . $auto . '</span>';
1065 $comment = $pre . $auto . $post;
1070 * Formats wiki links and media links in text; all other wiki formatting
1073 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1074 * @param $comment String: text to format links in
1075 * @param $title An optional title object used to links to sections
1076 * @param $local Boolean: whether section links should refer to local page
1079 public function formatLinksInComment( $comment, $title = null, $local = false ) {
1080 $this->commentContextTitle
= $title;
1081 $this->commentLocal
= $local;
1082 $html = preg_replace_callback(
1083 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1084 array( $this, 'formatLinksInCommentCallback' ),
1086 unset( $this->commentContextTitle
);
1087 unset( $this->commentLocal
);
1091 protected function formatLinksInCommentCallback( $match ) {
1094 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1095 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1097 $comment = $match[0];
1099 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1100 if ( strpos( $match[1], '%' ) !== false ) {
1101 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), urldecode( $match[1] ) );
1104 # Handle link renaming [[foo|text]] will show link as "text"
1105 if ( $match[3] != "" ) {
1110 $submatch = array();
1112 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1113 # Media link; trail not supported.
1114 $linkRegexp = '/\[\[(.*?)\]\]/';
1115 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1116 $thelink = $this->makeMediaLinkObj( $title, $text );
1118 # Other kind of link
1119 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1120 $trail = $submatch[1];
1124 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1125 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1126 $match[1] = substr( $match[1], 1 );
1127 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1130 $linkTarget = Linker
::normalizeSubpageLink( $this->commentContextTitle
,
1131 $match[1], $linkText );
1133 $target = Title
::newFromText( $linkTarget );
1135 if ( $target->getText() == '' && $target->getInterwiki() === ''
1136 && !$this->commentLocal
&& $this->commentContextTitle
)
1138 $newTarget = clone ( $this->commentContextTitle
);
1139 $newTarget->setFragment( '#' . $target->getFragment() );
1140 $target = $newTarget;
1142 $thelink = $this->link(
1149 // If the link is still valid, go ahead and replace it in!
1150 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1156 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1159 # :Foobar -- override special treatment of prefix (images, language links)
1160 # /Foobar -- convert to CurrentPage/Foobar
1161 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1162 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1163 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1165 wfProfileIn( __METHOD__
);
1166 $ret = $target; # default return value is no change
1168 # Some namespaces don't allow subpages,
1169 # so only perform processing if subpages are allowed
1170 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1171 $hash = strpos( $target, '#' );
1172 if ( $hash !== false ) {
1173 $suffix = substr( $target, $hash );
1174 $target = substr( $target, 0, $hash );
1179 $target = trim( $target );
1180 # Look at the first character
1181 if ( $target != '' && $target { 0 } === '/' ) {
1182 # / at end means we don't want the slash to be shown
1184 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1185 if ( $trailingSlashes ) {
1186 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1188 $noslash = substr( $target, 1 );
1191 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1192 if ( $text === '' ) {
1193 $text = $target . $suffix;
1194 } # this might be changed for ugliness reasons
1196 # check for .. subpage backlinks
1198 $nodotdot = $target;
1199 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1201 $nodotdot = substr( $nodotdot, 3 );
1203 if ( $dotdotcount > 0 ) {
1204 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1205 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1206 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1207 # / at the end means don't show full path
1208 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1209 $nodotdot = substr( $nodotdot, 0, -1 );
1210 if ( $text === '' ) {
1211 $text = $nodotdot . $suffix;
1214 $nodotdot = trim( $nodotdot );
1215 if ( $nodotdot != '' ) {
1216 $ret .= '/' . $nodotdot;
1224 wfProfileOut( __METHOD__
);
1229 * Wrap a comment in standard punctuation and formatting if
1230 * it's non-empty, otherwise return empty string.
1232 * @param $comment String
1233 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1234 * @param $local Boolean: whether section links should refer to local page
1238 function commentBlock( $comment, $title = null, $local = false ) {
1239 // '*' used to be the comment inserted by the software way back
1240 // in antiquity in case none was provided, here for backwards
1241 // compatability, acc. to brion -ævar
1242 if ( $comment == '' ||
$comment == '*' ) {
1245 $formatted = $this->formatComment( $comment, $title, $local );
1246 return " <span class=\"comment\">($formatted)</span>";
1251 * Wrap and format the given revision's comment block, if the current
1252 * user is allowed to view it.
1254 * @param $rev Revision object
1255 * @param $local Boolean: whether section links should refer to local page
1256 * @param $isPublic Boolean: show only if all users can see it
1257 * @return String: HTML fragment
1259 function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1260 if ( $rev->getRawComment() == "" ) return "";
1261 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1262 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1263 } else if ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1264 $block = $this->commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1265 $rev->getTitle(), $local );
1267 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1269 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1270 return " <span class=\"history-deleted\">$block</span>";
1275 public function formatRevisionSize( $size ) {
1277 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1280 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1283 $stxt = htmlspecialchars( $stxt );
1284 return "<span class=\"history-size\">$stxt</span>";
1288 * Add another level to the Table of Contents
1290 function tocIndent() {
1295 * Finish one or more sublevels on the Table of Contents
1297 function tocUnindent( $level ) {
1298 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1302 * parameter level defines if we are on an indentation level
1304 function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1305 $classes = "toclevel-$level";
1306 if ( $sectionIndex !== false )
1307 $classes .= " tocsection-$sectionIndex";
1308 return "\n<li class=\"$classes\"><a href=\"#" .
1309 $anchor . '"><span class="tocnumber">' .
1310 $tocnumber . '</span> <span class="toctext">' .
1311 $tocline . '</span></a>';
1315 * End a Table Of Contents line.
1316 * tocUnindent() will be used instead if we're ending a line below
1319 function tocLineEnd() {
1324 * Wraps the TOC in a table and provides the hide/collapse javascript.
1326 * @param $toc String: html of the Table Of Contents
1327 * @return String: full html of the TOC
1329 function tocList( $toc ) {
1330 $title = wfMsgHtml( 'toc' ) ;
1332 '<table id="toc" class="toc"><tr><td>'
1333 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1335 . "</ul>\n</td></tr></table>\n";
1339 * Generate a table of contents from a section tree
1342 * @param $tree Return value of ParserOutput::getSections()
1343 * @return String: HTML fragment
1345 public function generateTOC( $tree ) {
1348 foreach ( $tree as $section ) {
1349 if ( $section['toclevel'] > $lastLevel )
1350 $toc .= $this->tocIndent();
1351 else if ( $section['toclevel'] < $lastLevel )
1352 $toc .= $this->tocUnindent(
1353 $lastLevel - $section['toclevel'] );
1355 $toc .= $this->tocLineEnd();
1357 $toc .= $this->tocLine( $section['anchor'],
1358 $section['line'], $section['number'],
1359 $section['toclevel'], $section['index'] );
1360 $lastLevel = $section['toclevel'];
1362 $toc .= $this->tocLineEnd();
1363 return $this->tocList( $toc );
1367 * Create a section edit link. This supersedes editSectionLink() and
1368 * editSectionLinkForOther().
1370 * @param $nt Title The title being linked to (may not be the same as
1371 * $wgTitle, if the section is included from a template)
1372 * @param $section string The designation of the section being pointed to,
1373 * to be included in the link, like "§ion=$section"
1374 * @param $tooltip string The tooltip to use for the link: will be escaped
1375 * and wrapped in the 'editsectionhint' message
1376 * @param $lang string Language code
1377 * @return string HTML to use for edit link
1379 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1380 // HTML generated here should probably have userlangattributes
1381 // added to it for LTR text on RTL pages
1383 if ( !is_null( $tooltip ) ) {
1384 # Bug 25462: undo double-escaping.
1385 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1386 $attribs['title'] = wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang );
1388 $link = $this->link( $nt, wfMsgExt( 'editsection', array( 'language' => $lang ) ),
1390 array( 'action' => 'edit', 'section' => $section ),
1391 array( 'noclasses', 'known' )
1394 # Run the old hook. This takes up half of the function . . . hopefully
1395 # we can rid of it someday.
1398 $attribs = htmlspecialchars( wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang ) );
1399 $attribs = " title=\"$attribs\"";
1402 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1403 if ( !is_null( $result ) ) {
1404 # For reverse compatibility, add the brackets *after* the hook is
1405 # run, and even add them to hook-provided text. (This is the main
1406 # reason that the EditSectionLink hook is deprecated in favor of
1407 # DoEditSectionLink: it can't change the brackets or the span.)
1408 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $result );
1409 return "<span class=\"editsection\">$result</span>";
1412 # Add the brackets and the span, and *then* run the nice new hook, with
1413 # clean and non-redundant arguments.
1414 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $link );
1415 $result = "<span class=\"editsection\">$result</span>";
1417 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1422 * Create a headline for content
1424 * @param $level Integer: the level of the headline (1-6)
1425 * @param $attribs String: any attributes for the headline, starting with
1426 * a space and ending with '>'
1427 * This *must* be at least '>' for no attribs
1428 * @param $anchor String: the anchor to give the headline (the bit after the #)
1429 * @param $text String: the text of the header
1430 * @param $link String: HTML to add for the section edit link
1431 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1432 * backward compatibility (false to omit)
1434 * @return String: HTML headline
1436 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1437 $ret = "<h$level$attribs"
1439 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1441 if ( $legacyAnchor !== false ) {
1442 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1448 * Split a link trail, return the "inside" portion and the remainder of the trail
1449 * as a two-element array
1451 static function splitTrail( $trail ) {
1452 static $regex = false;
1453 if ( $regex === false ) {
1455 $regex = $wgContLang->linkTrail();
1458 if ( $trail !== '' ) {
1460 if ( preg_match( $regex, $trail, $m ) ) {
1465 return array( $inside, $trail );
1469 * Generate a rollback link for a given revision. Currently it's the
1470 * caller's responsibility to ensure that the revision is the top one. If
1471 * it's not, of course, the user will get an error message.
1473 * If the calling page is called with the parameter &bot=1, all rollback
1474 * links also get that parameter. It causes the edit itself and the rollback
1475 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1476 * changes, so this allows sysops to combat a busy vandal without bothering
1479 * @param $rev Revision object
1481 function generateRollback( $rev ) {
1482 return '<span class="mw-rollback-link">['
1483 . $this->buildRollbackLink( $rev )
1488 * Build a raw rollback link, useful for collections of "tool" links
1490 * @param $rev Revision object
1491 * @return String: HTML fragment
1493 public function buildRollbackLink( $rev ) {
1494 global $wgRequest, $wgUser;
1495 $title = $rev->getTitle();
1497 'action' => 'rollback',
1498 'from' => $rev->getUserText()
1500 if ( $wgRequest->getBool( 'bot' ) ) {
1501 $query['bot'] = '1';
1502 $query['hidediff'] = '1'; // bug 15999
1504 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1505 $rev->getUserText() ) );
1506 return $this->link( $title, wfMsgHtml( 'rollbacklink' ),
1507 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1508 $query, array( 'known', 'noclasses' ) );
1512 * Returns HTML for the "templates used on this page" list.
1514 * @param $templates Array of templates from Article::getUsedTemplate
1516 * @param $preview Boolean: whether this is for a preview
1517 * @param $section Boolean: whether this is for a section edit
1518 * @return String: HTML output
1520 public function formatTemplates( $templates, $preview = false, $section = false ) {
1521 wfProfileIn( __METHOD__
);
1524 if ( count( $templates ) > 0 ) {
1525 # Do a batch existence check
1526 $batch = new LinkBatch
;
1527 foreach ( $templates as $title ) {
1528 $batch->addObj( $title );
1532 # Construct the HTML
1533 $outText = '<div class="mw-templatesUsedExplanation">';
1535 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1536 } elseif ( $section ) {
1537 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1539 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1541 $outText .= "</div><ul>\n";
1543 usort( $templates, array( 'Title', 'compare' ) );
1544 foreach ( $templates as $titleObj ) {
1545 $r = $titleObj->getRestrictions( 'edit' );
1546 if ( in_array( 'sysop', $r ) ) {
1547 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1548 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1549 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1553 if ( $titleObj->quickUserCan( 'edit' ) ) {
1554 $editLink = $this->link(
1556 wfMsg( 'editlink' ),
1558 array( 'action' => 'edit' )
1561 $editLink = $this->link(
1563 wfMsg( 'viewsourcelink' ),
1565 array( 'action' => 'edit' )
1568 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1570 $outText .= '</ul>';
1572 wfProfileOut( __METHOD__
);
1577 * Returns HTML for the "hidden categories on this page" list.
1579 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1581 * @return String: HTML output
1583 public function formatHiddenCategories( $hiddencats ) {
1585 wfProfileIn( __METHOD__
);
1588 if ( count( $hiddencats ) > 0 ) {
1589 # Construct the HTML
1590 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1591 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1592 $outText .= "</div><ul>\n";
1594 foreach ( $hiddencats as $titleObj ) {
1595 $outText .= '<li>' . $this->link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1597 $outText .= '</ul>';
1599 wfProfileOut( __METHOD__
);
1604 * Format a size in bytes for output, using an appropriate
1605 * unit (B, KB, MB or GB) according to the magnitude in question
1607 * @param $size Size to format
1610 public function formatSize( $size ) {
1612 return htmlspecialchars( $wgLang->formatSize( $size ) );
1616 * Given the id of an interface element, constructs the appropriate title
1617 * attribute from the system messages. (Note, this is usually the id but
1618 * isn't always, because sometimes the accesskey needs to go on a different
1619 * element than the id, for reverse-compatibility, etc.)
1621 * @param $name String: id of the element, minus prefixes.
1622 * @param $options Mixed: null or the string 'withaccess' to add an access-
1624 * @return String: contents of the title attribute (which you must HTML-
1625 * escape), or false for no title attribute
1627 public function titleAttrib( $name, $options = null ) {
1628 wfProfileIn( __METHOD__
);
1630 if ( wfEmptyMsg( "tooltip-$name" ) ) {
1633 $tooltip = wfMsg( "tooltip-$name" );
1634 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1635 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1636 # Message equal to '-' means suppress it.
1637 if ( $tooltip == '-' ) {
1642 if ( $options == 'withaccess' ) {
1643 $accesskey = $this->accesskey( $name );
1644 if ( $accesskey !== false ) {
1645 if ( $tooltip === false ||
$tooltip === '' ) {
1646 $tooltip = "[$accesskey]";
1648 $tooltip .= " [$accesskey]";
1653 wfProfileOut( __METHOD__
);
1658 * Given the id of an interface element, constructs the appropriate
1659 * accesskey attribute from the system messages. (Note, this is usually
1660 * the id but isn't always, because sometimes the accesskey needs to go on
1661 * a different element than the id, for reverse-compatibility, etc.)
1663 * @param $name String: id of the element, minus prefixes.
1664 * @return String: contents of the accesskey attribute (which you must HTML-
1665 * escape), or false for no accesskey attribute
1667 public function accesskey( $name ) {
1668 wfProfileIn( __METHOD__
);
1670 if ( wfEmptyMsg( "accesskey-$name" ) ) {
1673 $accesskey = wfMsg( "accesskey-$name" );
1674 if ( $accesskey === '' ||
$accesskey === '-' ) {
1675 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1676 # attribute, but this is broken for accesskey: that might be a useful
1682 wfProfileOut( __METHOD__
);
1687 * Creates a (show/hide) link for deleting revisions/log entries
1689 * @param $query Array: query parameters to be passed to link()
1690 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1691 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1693 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1694 * span to allow for customization of appearance with CSS
1696 public function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1697 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1698 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1699 $tag = $restricted ?
'strong' : 'span';
1700 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1701 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1705 * Creates a dead (show/hide) link for deleting revisions/log entries
1707 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1709 * @return string HTML text wrapped in a span to allow for customization
1710 * of appearance with CSS
1712 public function revDeleteLinkDisabled( $delete = true ) {
1713 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1714 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1717 /* Deprecated methods */
1722 function postParseLinkColour( $s = null ) {
1723 wfDeprecated( __METHOD__
);
1729 * @deprecated Use link()
1731 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1732 * it if you already have a title object handy. See makeLinkObj for further documentation.
1734 * @param $title String: the text of the title
1735 * @param $text String: link text
1736 * @param $query String: optional query part
1737 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1738 * be included in the link text. Other characters will be appended after
1739 * the end of the link.
1741 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1742 wfProfileIn( __METHOD__
);
1743 $nt = Title
::newFromText( $title );
1744 if ( $nt instanceof Title
) {
1745 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1747 wfDebug( 'Invalid title passed to Linker::makeLink(): "' . $title . "\"\n" );
1748 $result = $text == "" ?
$title : $text;
1751 wfProfileOut( __METHOD__
);
1756 * @deprecated Use link()
1758 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1759 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1761 * @param $title String: the text of the title
1762 * @param $text String: link text
1763 * @param $query String: optional query part
1764 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1765 * be included in the link text. Other characters will be appended after
1766 * the end of the link.
1767 * @param $prefix String: Optional prefix
1768 * @param $aprops String: extra attributes to the a-element
1770 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '' ) {
1771 $nt = Title
::newFromText( $title );
1772 if ( $nt instanceof Title
) {
1773 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1775 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "' . $title . "\"\n" );
1776 return $text == '' ?
$title : $text;
1781 * @deprecated Use link()
1783 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1784 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1786 * @param $title String: The text of the title
1787 * @param $text String: Link text
1788 * @param $query String: Optional query part
1789 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1790 * be included in the link text. Other characters will be appended after
1791 * the end of the link.
1793 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1794 $nt = Title
::newFromText( $title );
1795 if ( $nt instanceof Title
) {
1796 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1798 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "' . $title . "\"\n" );
1799 return $text == '' ?
$title : $text;
1804 * @deprecated Use link()
1806 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1807 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1809 * @param $title String: the text of the title
1810 * @param $text String: link text
1811 * @param $query String: optional query part
1812 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1813 * be included in the link text. Other characters will be appended after
1814 * the end of the link.
1816 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1817 wfDeprecated( __METHOD__
);
1818 $nt = Title
::newFromText( $title );
1819 if ( $nt instanceof Title
) {
1820 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1822 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "' . $title . "\"\n" );
1823 return $text == '' ?
$title : $text;
1828 * @deprecated Use link()
1830 * Make a link for a title which may or may not be in the database. If you need to
1831 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1832 * call to this will result in a DB query.
1834 * @param $nt Title: the title object to make the link from, e.g. from
1835 * Title::newFromText.
1836 * @param $text String: link text
1837 * @param $query String: optional query part
1838 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1839 * be included in the link text. Other characters will be appended after
1840 * the end of the link.
1841 * @param $prefix String: optional prefix. As trail, only before instead of after.
1843 function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1844 wfProfileIn( __METHOD__
);
1846 $query = wfCgiToArray( $query );
1847 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1848 if ( $text === '' ) {
1849 $text = $this->linkText( $nt );
1852 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1854 wfProfileOut( __METHOD__
);
1859 * @deprecated Use link()
1861 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1862 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1865 * @param $title Title object of target page
1866 * @param $text String: text to replace the title
1867 * @param $query String: link target
1868 * @param $trail String: text after link
1869 * @param $prefix String: text before link text
1870 * @param $aprops String: extra attributes to the a-element
1871 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1872 * @return the a-element
1874 function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
1875 wfProfileIn( __METHOD__
);
1877 if ( $text == '' ) {
1878 $text = $this->linkText( $title );
1880 $attribs = Sanitizer
::mergeAttributes(
1881 Sanitizer
::decodeTagAttributes( $aprops ),
1882 Sanitizer
::decodeTagAttributes( $style )
1884 $query = wfCgiToArray( $query );
1885 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1887 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1888 array( 'known', 'noclasses' ) ) . $trail;
1890 wfProfileOut( __METHOD__
);
1895 * @deprecated Use link()
1897 * Make a red link to the edit page of a given title.
1899 * @param $title Title object of the target page
1900 * @param $text String: Link text
1901 * @param $query String: Optional query part
1902 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1903 * be included in the link text. Other characters will be appended after
1904 * the end of the link.
1905 * @param $prefix String: Optional prefix
1907 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1908 wfProfileIn( __METHOD__
);
1910 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1911 if ( $text === '' ) {
1912 $text = $this->linkText( $title );
1915 $ret = $this->link( $title, "$prefix$text$inside", array(),
1916 wfCgiToArray( $query ), 'broken' ) . $trail;
1918 wfProfileOut( __METHOD__
);
1923 * @deprecated Use link()
1925 * Make a brown link to a short article.
1927 * @param $nt Title object of the target page
1928 * @param $text String: link text
1929 * @param $query String: optional query part
1930 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1931 * be included in the link text. Other characters will be appended after
1932 * the end of the link.
1933 * @param $prefix String: Optional prefix
1935 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1936 // wfDeprecated( __METHOD__ );
1937 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1941 * @deprecated Use link()
1943 * Make a coloured link.
1945 * @param $nt Title object of the target page
1946 * @param $colour Integer: colour of the link
1947 * @param $text String: link text
1948 * @param $query String: optional query part
1949 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1950 * be included in the link text. Other characters will be appended after
1951 * the end of the link.
1952 * @param $prefix String: Optional prefix
1954 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1955 // wfDeprecated( __METHOD__ );
1956 if ( $colour != '' ) {
1957 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
1959 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1962 /** Obsolete alias */
1963 function makeImage( $url, $alt = '' ) {
1964 wfDeprecated( __METHOD__
);
1965 return $this->makeExternalImage( $url, $alt );
1969 * Creates the HTML source for images
1970 * @deprecated use makeImageLink2
1972 * @param $title Title object
1973 * @param $label String: label text
1974 * @param $alt String: alt text
1975 * @param $align String: horizontal alignment: none, left, center, right)
1976 * @param $handlerParams Array: parameters to be passed to the media handler
1977 * @param $framed Boolean: shows image in original size in a frame
1978 * @param $thumb Boolean: shows image as thumbnail in a frame
1979 * @param $manualthumb String: image name for the manual thumbnail
1980 * @param $valign String: vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
1981 * @param $time String: timestamp of the file, set as false for current
1984 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
1985 $thumb = false, $manualthumb = '', $valign = '', $time = false )
1987 $frameParams = array( 'alt' => $alt, 'caption' => $label );
1989 $frameParams['align'] = $align;
1992 $frameParams['framed'] = true;
1995 $frameParams['thumbnail'] = true;
1997 if ( $manualthumb ) {
1998 $frameParams['manualthumb'] = $manualthumb;
2001 $frameParams['valign'] = $valign;
2003 $file = wfFindFile( $title, array( 'time' => $time ) );
2004 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2007 /** @deprecated use Linker::makeMediaLinkObj() */
2008 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2009 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
2010 return $this->makeMediaLinkObj( $nt, $text, $time );
2014 * Used to generate section edit links that point to "other" pages
2015 * (sections that are really part of included pages).
2017 * @deprecated use Linker::doEditSectionLink()
2018 * @param $title Title string.
2019 * @param $section Integer: section number.
2021 public function editSectionLinkForOther( $title, $section ) {
2022 wfDeprecated( __METHOD__
);
2023 $title = Title
::newFromText( $title );
2024 return $this->doEditSectionLink( $title, $section );
2028 * @deprecated use Linker::doEditSectionLink()
2029 * @param $nt Title object.
2030 * @param $section Integer: section number.
2031 * @param $hint Link String: title, or default if omitted or empty
2033 public function editSectionLink( Title
$nt, $section, $hint = '' ) {
2034 wfDeprecated( __METHOD__
);
2035 if ( $hint === '' ) {
2036 # No way to pass an actual empty $hint here! The new interface al-
2037 # lows this, so we have to do this for compatibility.
2040 return $this->doEditSectionLink( $nt, $section, $hint );
2044 * Returns the attributes for the tooltip and access key.
2046 public function tooltipAndAccesskeyAttribs( $name ) {
2047 global $wgEnableTooltipsAndAccesskeys;
2048 if ( !$wgEnableTooltipsAndAccesskeys )
2050 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2051 # no attribute" instead of "output '' as value for attribute", this
2052 # would be three lines.
2054 'title' => $this->titleAttrib( $name, 'withaccess' ),
2055 'accesskey' => $this->accesskey( $name )
2057 if ( $attribs['title'] === false ) {
2058 unset( $attribs['title'] );
2060 if ( $attribs['accesskey'] === false ) {
2061 unset( $attribs['accesskey'] );
2066 * @deprecated Returns raw bits of HTML, use titleAttrib() and accesskey()
2068 public function tooltipAndAccesskey( $name ) {
2069 return Xml
::expandAttributes( $this->tooltipAndAccesskeyAttribs( $name ) );
2072 /** @deprecated Returns raw bits of HTML, use titleAttrib() */
2073 public function tooltip( $name, $options = null ) {
2074 global $wgEnableTooltipsAndAccesskeys;
2075 if ( !$wgEnableTooltipsAndAccesskeys )
2077 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2078 # no attribute" instead of "output '' as value for attribute", this
2079 # would be two lines.
2080 $tooltip = $this->titleAttrib( $name, $options );
2081 if ( $tooltip === false ) {
2084 return Xml
::expandAttributes( array(
2085 'title' => $this->titleAttrib( $name, $options )