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 string $class 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 string $title The title text for the link, URL-encoded (???) but
37 * @param string $unused Unused
38 * @param string $class 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 string $title The title text for the link, URL-encoded (???) but
59 * @param string $unused Unused
60 * @param string $class 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 Title $nt The Title object
73 * @param string $unused Unused
74 * @param string $class The contents of the class attribute, default none
75 * @param mixed $title 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
105 * @param integer $threshold 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 MWNamespace
::isContent( $t->getNamespace() ) ) {
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 )
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 );
223 private function linkUrl( $target, $query, $options ) {
224 wfProfileIn( __METHOD__
);
225 # We don't want to include fragments for broken links, because they
226 # generally make no sense.
227 if( in_array( 'broken', $options ) and $target->mFragment
!== '' ) {
228 $target = clone $target;
229 $target->mFragment
= '';
232 # If it's a broken link, add the appropriate query pieces, unless
233 # there's already an action specified, or unless 'edit' makes no sense
234 # (i.e., for a nonexistent special page).
235 if( in_array( 'broken', $options ) and empty( $query['action'] )
236 and $target->getNamespace() != NS_SPECIAL
) {
237 $query['action'] = 'edit';
238 $query['redlink'] = '1';
240 $ret = $target->getLinkUrl( $query );
241 wfProfileOut( __METHOD__
);
245 private function linkAttribs( $target, $attribs, $options ) {
246 wfProfileIn( __METHOD__
);
250 if( !in_array( 'noclasses', $options ) ) {
251 wfProfileIn( __METHOD__
. '-getClasses' );
252 # Now build the classes.
255 if( in_array( 'broken', $options ) ) {
259 if( $target->isExternal() ) {
260 $classes[] = 'extiw';
263 # Note that redirects never count as stubs here.
264 if ( !in_array( 'broken', $options ) && $target->isRedirect() ) {
265 $classes[] = 'mw-redirect';
266 } elseif( $target->isContentPage() ) {
268 $threshold = $wgUser->getOption( 'stubthreshold' );
269 if( $threshold > 0 and $target->exists() and $target->getLength() < $threshold ) {
273 if( $classes != array() ) {
274 $defaults['class'] = implode( ' ', $classes );
276 wfProfileOut( __METHOD__
. '-getClasses' );
279 # Get a default title attribute.
280 if( $target->getPrefixedText() == '' ) {
281 # A link like [[#Foo]]. This used to mean an empty title
282 # attribute, but that's silly. Just don't output a title.
283 } elseif( in_array( 'known', $options ) ) {
284 $defaults['title'] = $target->getPrefixedText();
286 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
289 # Finally, merge the custom attribs with the default ones, and iterate
290 # over that, deleting all "false" attributes.
292 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
293 foreach( $merged as $key => $val ) {
294 # A false value suppresses the attribute, and we don't want the
295 # href attribute to be overridden.
296 if( $key != 'href' and $val !== false ) {
300 wfProfileOut( __METHOD__
);
304 private function linkText( $target ) {
305 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
306 if( !$target instanceof Title
) {
310 # If the target is just a fragment, with no title, we return the frag-
311 # ment text. Otherwise, we return the title text itself.
312 if( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
313 return htmlspecialchars( $target->getFragment() );
315 return htmlspecialchars( $target->getPrefixedText() );
319 * Generate either a normal exists-style link or a stub link, depending
320 * on the given page size.
322 * @param $size Integer
323 * @param $nt Title object.
324 * @param $text String
325 * @param $query String
326 * @param $trail String
327 * @param $prefix String
328 * @return string HTML of link
330 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
332 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
333 $colour = ( $size < $threshold ) ?
'stub' : '';
334 // FIXME: replace deprecated makeColouredLinkObj by link()
335 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
339 * Make appropriate markup for a link to the current article. This is currently rendered
340 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
341 * despite $query not being used.
343 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
345 $text = htmlspecialchars( $nt->getPrefixedText() );
347 list( $inside, $trail ) = Linker
::splitTrail( $trail );
348 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
351 function normaliseSpecialPage( Title
$title ) {
352 if ( $title->getNamespace() == NS_SPECIAL
) {
353 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
354 if ( !$name ) return $title;
355 $ret = SpecialPage
::getTitleFor( $name, $subpage );
356 $ret->mFragment
= $title->getFragment();
363 /** @todo document */
364 function fnamePart( $url ) {
365 $basename = strrchr( $url, '/' );
366 if ( false === $basename ) {
369 $basename = substr( $basename, 1 );
374 /** @todo document */
375 function makeExternalImage( $url, $alt = '' ) {
377 $alt = $this->fnamePart( $url );
380 $success = wfRunHooks('LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
382 wfDebug("Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true);
385 return Html
::element( 'img',
392 * Given parameters derived from [[Image:Foo|options...]], generate the
393 * HTML that that syntax inserts in the page.
395 * @param Title $title Title object
396 * @param File $file File object, or false if it doesn't exist
398 * @param array $frameParams Associative array of parameters external to the media handler.
399 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
400 * will often be false.
401 * thumbnail If present, downscale and frame
402 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
403 * framed Shows image in original size in a frame
404 * frameless Downscale but don't frame
405 * upright If present, tweak default sizes for portrait orientation
406 * upright_factor Fudge factor for "upright" tweak (default 0.75)
407 * border If present, show a border around the image
408 * align Horizontal alignment (left, right, center, none)
409 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
410 * bottom, text-bottom)
411 * alt Alternate text for image (i.e. alt attribute). Plain text.
412 * caption HTML for image caption.
413 * link-url URL to link to
414 * link-title Title object to link to
415 * no-link Boolean, suppress description link
417 * @param array $handlerParams Associative array of media handler parameters, to be passed
418 * to transform(). Typical keys are "width" and "page".
419 * @param string $time, timestamp of the file, set as false for current
420 * @param string $query, query params for desc url
421 * @return string HTML for an image, with links, wrappers, etc.
423 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
425 if( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
426 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
430 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
431 if ( $file && !$file->allowInlineDisplay() ) {
432 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
433 return $this->link( $title );
438 $hp =& $handlerParams;
440 // Clean up parameters
441 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
442 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
443 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
444 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
446 $prefix = $postfix = '';
448 if ( 'center' == $fp['align'] ) {
449 $prefix = '<div class="center">';
451 $fp['align'] = 'none';
453 if ( $file && !isset( $hp['width'] ) ) {
454 $hp['width'] = $file->getWidth( $page );
456 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
457 $wopt = $wgUser->getOption( 'thumbsize' );
459 if( !isset( $wgThumbLimits[$wopt] ) ) {
460 $wopt = User
::getDefaultOption( 'thumbsize' );
463 // Reduce width for upright images when parameter 'upright' is used
464 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
465 $fp['upright'] = $wgThumbUpright;
467 // Use width which is smaller: real image width or user preference width
468 // 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
469 $prefWidth = isset( $fp['upright'] ) ?
470 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
471 $wgThumbLimits[$wopt];
472 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
473 $hp['width'] = $prefWidth;
478 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
479 # Create a thumbnail. Alignment depends on language
480 # writing direction, # right aligned for left-to-right-
481 # languages ("Western languages"), left-aligned
482 # for right-to-left-languages ("Semitic languages")
484 # If thumbnail width has not been provided, it is set
485 # to the default user option as specified in Language*.php
486 if ( $fp['align'] == '' ) {
487 $fp['align'] = $wgContLang->alignEnd();
489 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ).$postfix;
492 if ( $file && isset( $fp['frameless'] ) ) {
493 $srcWidth = $file->getWidth( $page );
494 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
495 # This is the same behaviour as the "thumb" option does it already.
496 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
497 $hp['width'] = $srcWidth;
501 if ( $file && $hp['width'] ) {
502 # Create a resized image, without the additional thumbnail features
503 $thumb = $file->transform( $hp );
509 $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
513 'title' => $fp['title'],
514 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
515 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
516 if ( !empty( $fp['link-url'] ) ) {
517 $params['custom-url-link'] = $fp['link-url'];
518 } elseif ( !empty( $fp['link-title'] ) ) {
519 $params['custom-title-link'] = $fp['link-title'];
520 } elseif ( !empty( $fp['no-link'] ) ) {
523 $params['desc-link'] = true;
524 $params['desc-query'] = $query;
527 $s = $thumb->toHtml( $params );
529 if ( '' != $fp['align'] ) {
530 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
532 return str_replace("\n", ' ',$prefix.$s.$postfix);
536 * Make HTML for a thumbnail including image, border and caption
537 * @param Title $title
538 * @param File $file File object or false if it doesn't exist
540 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
541 $frameParams = array(
546 if ( $framed ) $frameParams['framed'] = true;
547 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
548 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
551 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
552 global $wgStylePath, $wgContLang;
553 $exists = $file && $file->exists();
557 $hp =& $handlerParams;
559 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
560 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
561 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
562 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
563 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
565 if ( empty( $hp['width'] ) ) {
566 // Reduce width for upright images when parameter 'upright' is used
567 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
572 $outerWidth = $hp['width'] +
2;
574 if ( isset( $fp['manualthumb'] ) ) {
575 # Use manually specified thumbnail
576 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
577 if( $manual_title ) {
578 $manual_img = wfFindFile( $manual_title );
580 $thumb = $manual_img->getUnscaledThumb();
585 } elseif ( isset( $fp['framed'] ) ) {
586 // Use image dimensions, don't scale
587 $thumb = $file->getUnscaledThumb( $page );
589 # Do not present an image bigger than the source, for bitmap-style images
590 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
591 $srcWidth = $file->getWidth( $page );
592 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
593 $hp['width'] = $srcWidth;
595 $thumb = $file->transform( $hp );
599 $outerWidth = $thumb->getWidth() +
2;
601 $outerWidth = $hp['width'] +
2;
605 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
606 # So we don't need to pass it here in $query. However, the URL for the
607 # zoom icon still needs it, so we make a unique query for it. See bug 14771
608 $url = $title->getLocalURL( $query );
610 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
613 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
615 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
617 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
619 } elseif ( !$thumb ) {
620 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
623 $s .= $thumb->toHtml( array(
625 'title' => $fp['title'],
626 'img-class' => 'thumbimage',
628 'desc-query' => $query ) );
629 if ( isset( $fp['framed'] ) ) {
632 $zoomicon = '<div class="magnify">'.
633 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
634 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
635 'width="15" height="11" alt="" /></a></div>';
638 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
639 return str_replace("\n", ' ', $s);
643 * Make a "broken" link to an image
645 * @param Title $title Image title
646 * @param string $text Link label
647 * @param string $query Query string
648 * @param string $trail Link trail
649 * @param string $prefix Link prefix
650 * @param bool $time, a file of a certain timestamp was requested
653 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
654 global $wgEnableUploads;
655 if( $title instanceof Title
) {
656 wfProfileIn( __METHOD__
);
657 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
658 if( $wgEnableUploads && !$currentExists ) {
659 $upload = SpecialPage
::getTitleFor( 'Upload' );
661 $text = htmlspecialchars( $title->getPrefixedText() );
662 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
664 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
666 $q = 'wpDestFile=' . $title->getPartialUrl();
669 list( $inside, $trail ) = self
::splitTrail( $trail );
670 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
671 wfProfileOut( __METHOD__
);
672 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
673 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
675 wfProfileOut( __METHOD__
);
676 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
679 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
684 * Create a direct link to a given uploaded file.
686 * @param $title Title object.
687 * @param $text String: pre-sanitized HTML
688 * @param $time string: time image was created
689 * @return string HTML
692 * @todo Handle invalid or missing images better.
694 function makeMediaLinkObj( $title, $text = '', $time = false ) {
695 if( is_null( $title ) ) {
696 ### HOTFIX. Instead of breaking, return empty string.
699 $img = wfFindFile( $title, array( 'time' => $time ) );
701 $url = $img->getURL();
704 $upload = SpecialPage
::getTitleFor( 'Upload' );
705 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
708 $alt = htmlspecialchars( $title->getText() );
712 $u = htmlspecialchars( $url );
713 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
717 /** @todo document */
718 function specialLink( $name, $key = '' ) {
721 if ( '' == $key ) { $key = strtolower( $name ); }
722 $pn = $wgContLang->ucfirst( $name );
723 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
728 * Make an external link
729 * @param String $url URL to link to
730 * @param String $text text of link
731 * @param boolean $escape Do we escape the link text?
732 * @param String $linktype Type of external link. Gets added to the classes
733 * @param array $attribs Array of extra attributes to <a>
735 * @TODO! @FIXME! This is a really crappy implementation. $linktype and
736 * 'external' are mashed into the class attrib for the link (which is made
737 * into a string). Then, if we've got additional params in $attribs, we
738 * add to it. People using this might want to change the classes (or other
739 * default link attributes), but passing $attribsText is just messy. Would
740 * make a lot more sense to make put the classes into $attribs, let the
741 * hook play with them, *then* expand it all at once.
743 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
744 $attribsText = $this->getExternalLinkAttributes( 'external ' . $linktype );
745 $url = htmlspecialchars( $url );
747 $text = htmlspecialchars( $text );
750 $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
752 wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true);
756 $attribsText .= Html
::expandAttributes( $attribs );
758 return '<a href="'.$url.'"'.$attribsText.'>'.$text.'</a>';
762 * Make user link (or user contributions for unregistered users)
763 * @param $userId Integer: user id in database.
764 * @param $userText String: user name in database
765 * @return string HTML fragment
768 function userLink( $userId, $userText ) {
770 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
772 $page = Title
::makeTitle( NS_USER
, $userText );
774 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
778 * Generate standard user tool links (talk, contributions, block link, etc.)
780 * @param int $userId User identifier
781 * @param string $userText User name or IP address
782 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
783 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
784 * @param int $edits, user edit count (optional, for performance)
787 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
788 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans, $wgLang;
789 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
790 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
794 $items[] = $this->userTalkLink( $userId, $userText );
797 // check if the user has an edit
799 if( $redContribsWhenNoEdits ) {
800 $count = !is_null($edits) ?
$edits : User
::edits( $userId );
802 $attribs['class'] = 'new';
805 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
807 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
809 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
810 $items[] = $this->blockLink( $userId, $userText );
814 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
821 * Alias for userToolLinks( $userId, $userText, true );
822 * @param int $userId User identifier
823 * @param string $userText User name or IP address
824 * @param int $edits, user edit count (optional, for performance)
826 public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
827 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
832 * @param $userId Integer: user id in database.
833 * @param $userText String: user name in database.
834 * @return string HTML fragment with user talk link
837 function userTalkLink( $userId, $userText ) {
838 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
839 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
840 return $userTalkLink;
844 * @param $userId Integer: userid
845 * @param $userText String: user name in database.
846 * @return string HTML fragment with block link
849 function blockLink( $userId, $userText ) {
850 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
851 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
856 * Generate a user link if the current user is allowed to view it
857 * @param $rev Revision object.
858 * @param $isPublic, bool, show only if all users can see it
859 * @return string HTML
861 function revUserLink( $rev, $isPublic = false ) {
862 if( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
863 $link = wfMsgHtml( 'rev-deleted-user' );
864 } else if( $rev->userCan( Revision
::DELETED_USER
) ) {
865 $link = $this->userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
866 $rev->getUserText( Revision
::FOR_THIS_USER
) );
868 $link = wfMsgHtml( 'rev-deleted-user' );
870 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
871 return '<span class="history-deleted">' . $link . '</span>';
877 * Generate a user tool link cluster if the current user is allowed to view it
878 * @param $rev Revision object.
879 * @param $isPublic, bool, show only if all users can see it
880 * @return string HTML
882 function revUserTools( $rev, $isPublic = false ) {
883 if( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
884 $link = wfMsgHtml( 'rev-deleted-user' );
885 } else if( $rev->userCan( Revision
::DELETED_USER
) ) {
886 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
887 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
888 $link = $this->userLink( $userId, $userText ) .
889 ' ' . $this->userToolLinks( $userId, $userText );
891 $link = wfMsgHtml( 'rev-deleted-user' );
893 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
894 return ' <span class="history-deleted">' . $link . '</span>';
900 * This function is called by all recent changes variants, by the page history,
901 * and by the user contributions list. It is responsible for formatting edit
902 * comments. It escapes any HTML in the comment, but adds some CSS to format
903 * auto-generated comments (from section editing) and formats [[wikilinks]].
905 * @author Erik Moeller <moeller@scireview.de>
907 * Note: there's not always a title to pass to this function.
908 * Since you can't set a default parameter for a reference, I've turned it
909 * temporarily to a value pass. Should be adjusted further. --brion
911 * @param string $comment
912 * @param mixed $title Title object (to generate link to the section in autocomment) or null
913 * @param bool $local Whether section links should refer to local page
915 function formatComment($comment, $title = NULL, $local = false) {
916 wfProfileIn( __METHOD__
);
918 # Sanitize text a bit:
919 $comment = str_replace( "\n", " ", $comment );
920 # Allow HTML entities (for bug 13815)
921 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
923 # Render autocomments and make links:
924 $comment = $this->formatAutoComments( $comment, $title, $local );
925 $comment = $this->formatLinksInComment( $comment, $title, $local );
927 wfProfileOut( __METHOD__
);
932 * The pattern for autogen comments is / * foo * /, which makes for
934 * We look for all comments, match any text before and after the comment,
935 * add a separator where needed and format the comment itself with CSS
936 * Called by Linker::formatComment.
938 * @param string $comment Comment text
939 * @param object $title An optional title object used to links to sections
940 * @return string $comment formatted comment
942 * @todo Document the $local parameter.
944 private function formatAutocomments( $comment, $title = null, $local = false ) {
946 $this->autocommentTitle
= $title;
947 $this->autocommentLocal
= $local;
948 $comment = preg_replace_callback(
949 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
950 array( $this, 'formatAutocommentsCallback' ),
952 unset( $this->autocommentTitle
);
953 unset( $this->autocommentLocal
);
957 private function formatAutocommentsCallback( $match ) {
958 $title = $this->autocommentTitle
;
959 $local = $this->autocommentLocal
;
968 # Generate a valid anchor name from the section title.
969 # Hackish, but should generally work - we strip wiki
970 # syntax, including the magic [[: that is used to
971 # "link rather than show" in case of images and
972 # interlanguage links.
973 $section = str_replace( '[[:', '', $section );
974 $section = str_replace( '[[', '', $section );
975 $section = str_replace( ']]', '', $section );
977 $sectionTitle = Title
::newFromText( '#' . $section );
979 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
980 $title->getDBkey(), $section );
982 if ( $sectionTitle ) {
983 $link = $this->link( $sectionTitle,
984 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
990 $auto = "$link$auto";
992 # written summary $presep autocomment (summary /* section */)
993 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
996 # autocomment $postsep written summary (/* section */ summary)
997 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
999 $auto = '<span class="autocomment">' . $auto . '</span>';
1000 $comment = $pre . $auto . $post;
1005 * Formats wiki links and media links in text; all other wiki formatting
1008 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1009 * @param string $comment Text to format links in
1012 public function formatLinksInComment( $comment, $title = null, $local = false ) {
1013 $this->commentContextTitle
= $title;
1014 $this->commentLocal
= $local;
1015 $html = preg_replace_callback(
1016 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1017 array( $this, 'formatLinksInCommentCallback' ),
1019 unset( $this->commentContextTitle
);
1020 unset( $this->commentLocal
);
1024 protected function formatLinksInCommentCallback( $match ) {
1027 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1028 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1030 $comment = $match[0];
1032 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1033 if( strpos( $match[1], '%' ) !== false ) {
1034 $match[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($match[1]) );
1037 # Handle link renaming [[foo|text]] will show link as "text"
1038 if( "" != $match[3] ) {
1043 $submatch = array();
1045 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1046 # Media link; trail not supported.
1047 $linkRegexp = '/\[\[(.*?)\]\]/';
1048 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1049 $thelink = $this->makeMediaLinkObj( $title, $text );
1051 # Other kind of link
1052 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1053 $trail = $submatch[1];
1057 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1058 if (isset($match[1][0]) && $match[1][0] == ':')
1059 $match[1] = substr($match[1], 1);
1060 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1063 $linkTarget = Linker
::normalizeSubpageLink( $this->commentContextTitle
,
1064 $match[1], $linkText );
1066 $target = Title
::newFromText( $linkTarget );
1068 if( $target->getText() == '' && !$this->commentLocal
&& $this->commentContextTitle
) {
1069 $newTarget = clone( $this->commentContextTitle
);
1070 $newTarget->setFragment( '#' . $target->getFragment() );
1071 $target = $newTarget;
1073 $thelink = $this->link(
1080 // If the link is still valid, go ahead and replace it in!
1081 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1087 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1090 # :Foobar -- override special treatment of prefix (images, language links)
1091 # /Foobar -- convert to CurrentPage/Foobar
1092 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1093 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1094 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1096 wfProfileIn( __METHOD__
);
1097 $ret = $target; # default return value is no change
1099 # Some namespaces don't allow subpages,
1100 # so only perform processing if subpages are allowed
1101 if( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1102 $hash = strpos( $target, '#' );
1103 if( $hash !== false ) {
1104 $suffix = substr( $target, $hash );
1105 $target = substr( $target, 0, $hash );
1110 $target = trim( $target );
1111 # Look at the first character
1112 if( $target != '' && $target{0} === '/' ) {
1113 # / at end means we don't want the slash to be shown
1115 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1116 if( $trailingSlashes ) {
1117 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1119 $noslash = substr( $target, 1 );
1122 $ret = $contextTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1123 if( '' === $text ) {
1124 $text = $target . $suffix;
1125 } # this might be changed for ugliness reasons
1127 # check for .. subpage backlinks
1129 $nodotdot = $target;
1130 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1132 $nodotdot = substr( $nodotdot, 3 );
1134 if($dotdotcount > 0) {
1135 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1136 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1137 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1138 # / at the end means don't show full path
1139 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1140 $nodotdot = substr( $nodotdot, 0, -1 );
1141 if( '' === $text ) {
1142 $text = $nodotdot . $suffix;
1145 $nodotdot = trim( $nodotdot );
1146 if( $nodotdot != '' ) {
1147 $ret .= '/' . $nodotdot;
1155 wfProfileOut( __METHOD__
);
1160 * Wrap a comment in standard punctuation and formatting if
1161 * it's non-empty, otherwise return empty string.
1163 * @param string $comment
1164 * @param mixed $title Title object (to generate link to section in autocomment) or null
1165 * @param bool $local Whether section links should refer to local page
1169 function commentBlock( $comment, $title = NULL, $local = false ) {
1170 // '*' used to be the comment inserted by the software way back
1171 // in antiquity in case none was provided, here for backwards
1172 // compatability, acc. to brion -ævar
1173 if( $comment == '' ||
$comment == '*' ) {
1176 $formatted = $this->formatComment( $comment, $title, $local );
1177 return " <span class=\"comment\">($formatted)</span>";
1182 * Wrap and format the given revision's comment block, if the current
1183 * user is allowed to view it.
1185 * @param Revision $rev
1186 * @param bool $local Whether section links should refer to local page
1187 * @param $isPublic, show only if all users can see it
1188 * @return string HTML
1190 function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1191 if( $rev->getRawComment() == "" ) return "";
1192 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1193 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1194 } else if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1195 $block = $this->commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1196 $rev->getTitle(), $local );
1198 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1200 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1201 return " <span class=\"history-deleted\">$block</span>";
1206 public function formatRevisionSize( $size ) {
1208 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1211 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1214 $stxt = htmlspecialchars( $stxt );
1215 return "<span class=\"history-size\">$stxt</span>";
1218 /** @todo document */
1219 function tocIndent() {
1223 /** @todo document */
1224 function tocUnindent($level) {
1225 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1229 * parameter level defines if we are on an indentation level
1231 function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1232 $classes = "toclevel-$level";
1233 if ( $sectionIndex !== false )
1234 $classes .= " tocsection-$sectionIndex";
1235 return "\n<li class=\"$classes\"><a href=\"#" .
1236 $anchor . '"><span class="tocnumber">' .
1237 $tocnumber . '</span> <span class="toctext">' .
1238 $tocline . '</span></a>';
1241 /** @todo document */
1242 function tocLineEnd() {
1246 /** @todo document */
1247 function tocList($toc) {
1248 $title = wfMsgHtml('toc') ;
1250 '<table id="toc" class="toc"><tr><td>'
1251 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1253 # no trailing newline, script should not be wrapped in a
1255 . "</ul>\n</td></tr></table>"
1256 . Html
::inlineScript(
1257 'if (window.showTocToggle) {'
1258 . ' var tocShowText = "' . Xml
::escapeJsString( wfMsg('showtoc') ) . '";'
1259 . ' var tocHideText = "' . Xml
::escapeJsString( wfMsg('hidetoc') ) . '";'
1260 . ' showTocToggle();'
1266 * Generate a table of contents from a section tree
1267 * @param $tree Return value of ParserOutput::getSections()
1268 * @return string HTML
1270 public function generateTOC( $tree ) {
1273 foreach ( $tree as $section ) {
1274 if ( $section['toclevel'] > $lastLevel )
1275 $toc .= $this->tocIndent();
1276 else if ( $section['toclevel'] < $lastLevel )
1277 $toc .= $this->tocUnindent(
1278 $lastLevel - $section['toclevel'] );
1280 $toc .= $this->tocLineEnd();
1282 $toc .= $this->tocLine( $section['anchor'],
1283 $section['line'], $section['number'],
1284 $section['toclevel'], $section['index'] );
1285 $lastLevel = $section['toclevel'];
1287 $toc .= $this->tocLineEnd();
1288 return $this->tocList( $toc );
1292 * Create a section edit link. This supersedes editSectionLink() and
1293 * editSectionLinkForOther().
1295 * @param $nt Title The title being linked to (may not be the same as
1296 * $wgTitle, if the section is included from a template)
1297 * @param $section string The designation of the section being pointed to,
1298 * to be included in the link, like "§ion=$section"
1299 * @param $tooltip string The tooltip to use for the link: will be escaped
1300 * and wrapped in the 'editsectionhint' message
1301 * @return string HTML to use for edit link
1303 public function doEditSectionLink( Title
$nt, $section, $tooltip = null ) {
1305 if( !is_null( $tooltip ) ) {
1306 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1308 $link = $this->link( $nt, wfMsg('editsection'),
1310 array( 'action' => 'edit', 'section' => $section ),
1311 array( 'noclasses', 'known' )
1314 # Run the old hook. This takes up half of the function . . . hopefully
1315 # we can rid of it someday.
1318 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1319 $attribs = " title=\"$attribs\"";
1322 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result ) );
1323 if( !is_null( $result ) ) {
1324 # For reverse compatibility, add the brackets *after* the hook is
1325 # run, and even add them to hook-provided text. (This is the main
1326 # reason that the EditSectionLink hook is deprecated in favor of
1327 # DoEditSectionLink: it can't change the brackets or the span.)
1328 $result = wfMsgHtml( 'editsection-brackets', $result );
1329 return "<span class=\"editsection\">$result</span>";
1332 # Add the brackets and the span, and *then* run the nice new hook, with
1333 # clean and non-redundant arguments.
1334 $result = wfMsgHtml( 'editsection-brackets', $link );
1335 $result = "<span class=\"editsection\">$result</span>";
1337 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1342 * Create a headline for content
1344 * @param int $level The level of the headline (1-6)
1345 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1346 * This *must* be at least '>' for no attribs
1347 * @param string $anchor The anchor to give the headline (the bit after the #)
1348 * @param string $text The text of the header
1349 * @param string $link HTML to add for the section edit link
1350 * @param mixed $legacyAnchor A second, optional anchor to give for
1351 * backward compatibility (false to omit)
1353 * @return string HTML headline
1355 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1356 $ret = "<h$level$attribs"
1358 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1360 if ( $legacyAnchor !== false ) {
1361 $ret = "<a id=\"$legacyAnchor\"></a>$ret";
1367 * Split a link trail, return the "inside" portion and the remainder of the trail
1368 * as a two-element array
1372 static function splitTrail( $trail ) {
1373 static $regex = false;
1374 if ( $regex === false ) {
1376 $regex = $wgContLang->linkTrail();
1379 if ( '' != $trail ) {
1381 if ( preg_match( $regex, $trail, $m ) ) {
1386 return array( $inside, $trail );
1390 * Generate a rollback link for a given revision. Currently it's the
1391 * caller's responsibility to ensure that the revision is the top one. If
1392 * it's not, of course, the user will get an error message.
1394 * If the calling page is called with the parameter &bot=1, all rollback
1395 * links also get that parameter. It causes the edit itself and the rollback
1396 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1397 * changes, so this allows sysops to combat a busy vandal without bothering
1400 * @param Revision $rev
1402 function generateRollback( $rev ) {
1403 return '<span class="mw-rollback-link">['
1404 . $this->buildRollbackLink( $rev )
1409 * Build a raw rollback link, useful for collections of "tool" links
1411 * @param Revision $rev
1414 public function buildRollbackLink( $rev ) {
1415 global $wgRequest, $wgUser;
1416 $title = $rev->getTitle();
1418 'action' => 'rollback',
1419 'from' => $rev->getUserText()
1421 if( $wgRequest->getBool( 'bot' ) ) {
1422 $query['bot'] = '1';
1423 $query['hidediff'] = '1'; // bug 15999
1425 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1426 $rev->getUserText() ) );
1427 return $this->link( $title, wfMsgHtml( 'rollbacklink' ),
1428 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1429 $query, array( 'known', 'noclasses' ) );
1433 * Returns HTML for the "templates used on this page" list.
1435 * @param array $templates Array of templates from Article::getUsedTemplate
1437 * @param bool $preview Whether this is for a preview
1438 * @param bool $section Whether this is for a section edit
1439 * @return string HTML output
1441 public function formatTemplates( $templates, $preview = false, $section = false ) {
1442 wfProfileIn( __METHOD__
);
1445 if ( count( $templates ) > 0 ) {
1446 # Do a batch existence check
1447 $batch = new LinkBatch
;
1448 foreach( $templates as $title ) {
1449 $batch->addObj( $title );
1453 # Construct the HTML
1454 $outText = '<div class="mw-templatesUsedExplanation">';
1456 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1457 } elseif ( $section ) {
1458 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1460 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1462 $outText .= "</div><ul>\n";
1464 usort( $templates, array( 'Title', 'compare' ) );
1465 foreach ( $templates as $titleObj ) {
1466 $r = $titleObj->getRestrictions( 'edit' );
1467 if ( in_array( 'sysop', $r ) ) {
1468 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1469 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1470 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1474 if( $titleObj->quickUserCan( 'edit' ) ) {
1475 $editLink = $this->link(
1477 wfMsg( 'editlink' ),
1479 array( 'action' => 'edit' )
1482 $editLink = $this->link(
1484 wfMsg( 'viewsourcelink' ),
1486 array( 'action' => 'edit' )
1489 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1491 $outText .= '</ul>';
1493 wfProfileOut( __METHOD__
);
1498 * Returns HTML for the "hidden categories on this page" list.
1500 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1502 * @return string HTML output
1504 public function formatHiddenCategories( $hiddencats ) {
1506 wfProfileIn( __METHOD__
);
1509 if ( count( $hiddencats ) > 0 ) {
1510 # Construct the HTML
1511 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1512 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1513 $outText .= "</div><ul>\n";
1515 foreach ( $hiddencats as $titleObj ) {
1516 $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
1518 $outText .= '</ul>';
1520 wfProfileOut( __METHOD__
);
1525 * Format a size in bytes for output, using an appropriate
1526 * unit (B, KB, MB or GB) according to the magnitude in question
1528 * @param $size Size to format
1531 public function formatSize( $size ) {
1533 return htmlspecialchars( $wgLang->formatSize( $size ) );
1537 * Given the id of an interface element, constructs the appropriate title
1538 * attribute from the system messages. (Note, this is usually the id but
1539 * isn't always, because sometimes the accesskey needs to go on a different
1540 * element than the id, for reverse-compatibility, etc.)
1542 * @param string $name Id of the element, minus prefixes.
1543 * @param mixed $options null or the string 'withaccess' to add an access-
1545 * @return string Contents of the title attribute (which you must HTML-
1546 * escape), or false for no title attribute
1548 public function titleAttrib( $name, $options = null ) {
1549 wfProfileIn( __METHOD__
);
1551 $tooltip = wfMsg( "tooltip-$name" );
1552 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1553 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1555 # Message equal to '-' means suppress it.
1556 if ( wfEmptyMsg( "tooltip-$name", $tooltip ) ||
$tooltip == '-' ) {
1560 if ( $options == 'withaccess' ) {
1561 $accesskey = $this->accesskey( $name );
1562 if( $accesskey !== false ) {
1563 if ( $tooltip === false ||
$tooltip === '' ) {
1564 $tooltip = "[$accesskey]";
1566 $tooltip .= " [$accesskey]";
1571 wfProfileOut( __METHOD__
);
1576 * Given the id of an interface element, constructs the appropriate
1577 * accesskey attribute from the system messages. (Note, this is usually
1578 * the id but isn't always, because sometimes the accesskey needs to go on
1579 * a different element than the id, for reverse-compatibility, etc.)
1581 * @param string $name Id of the element, minus prefixes.
1582 * @return string Contents of the accesskey attribute (which you must HTML-
1583 * escape), or false for no accesskey attribute
1585 public function accesskey( $name ) {
1586 wfProfileIn( __METHOD__
);
1588 $accesskey = wfMsg( "accesskey-$name" );
1590 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1591 # attribute, but this is broken for accesskey: that might be a useful
1593 if( $accesskey != '' && $accesskey != '-' && !wfEmptyMsg( "accesskey-$name", $accesskey ) ) {
1594 wfProfileOut( __METHOD__
);
1598 wfProfileOut( __METHOD__
);
1603 * Creates a (show/hide) link for deleting revisions/log entries
1605 * @param array $query Query parameters to be passed to link()
1606 * @param bool $restricted Set to true to use a <strong> instead of a <span>
1608 * @return string HTML <a> link to Special:Revisiondelete, wrapped in a
1609 * span to allow for customization of appearance with CSS
1611 public function revDeleteLink( $query = array(), $restricted = false ) {
1612 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1613 $text = wfMsgHtml( 'rev-delundel' );
1614 $tag = $restricted ?
'strong' : 'span';
1615 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1616 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1619 /* Deprecated methods */
1624 function postParseLinkColour( $s = null ) {
1625 wfDeprecated( __METHOD__
);
1631 * @deprecated Use link()
1633 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1634 * it if you already have a title object handy. See makeLinkObj for further documentation.
1636 * @param $title String: the text of the title
1637 * @param $text String: link text
1638 * @param $query String: optional query part
1639 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1640 * be included in the link text. Other characters will be appended after
1641 * the end of the link.
1643 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1644 wfProfileIn( __METHOD__
);
1645 $nt = Title
::newFromText( $title );
1646 if ( $nt instanceof Title
) {
1647 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1649 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
1650 $result = $text == "" ?
$title : $text;
1653 wfProfileOut( __METHOD__
);
1658 * @deprecated Use link()
1660 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1661 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1663 * @param $title String: the text of the title
1664 * @param $text String: link text
1665 * @param $query String: optional query part
1666 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1667 * be included in the link text. Other characters will be appended after
1668 * the end of the link.
1670 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
1671 $nt = Title
::newFromText( $title );
1672 if ( $nt instanceof Title
) {
1673 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1675 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
1676 return $text == '' ?
$title : $text;
1681 * @deprecated Use link()
1683 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1684 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1686 * @param string $title The text of the title
1687 * @param string $text Link text
1688 * @param string $query Optional query part
1689 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
1690 * be included in the link text. Other characters will be appended after
1691 * the end of the link.
1693 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1694 $nt = Title
::newFromText( $title );
1695 if ( $nt instanceof Title
) {
1696 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1698 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
1699 return $text == '' ?
$title : $text;
1704 * @deprecated Use link()
1706 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1707 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1709 * @param $title String: the text of the title
1710 * @param $text String: link text
1711 * @param $query String: optional query part
1712 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1713 * be included in the link text. Other characters will be appended after
1714 * the end of the link.
1716 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1717 wfDeprecated( __METHOD__
);
1718 $nt = Title
::newFromText( $title );
1719 if ( $nt instanceof Title
) {
1720 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1722 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
1723 return $text == '' ?
$title : $text;
1728 * @deprecated Use link()
1730 * Make a link for a title which may or may not be in the database. If you need to
1731 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1732 * call to this will result in a DB query.
1734 * @param $nt Title: the title object to make the link from, e.g. from
1735 * Title::newFromText.
1736 * @param $text String: link text
1737 * @param $query String: optional query part
1738 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1739 * be included in the link text. Other characters will be appended after
1740 * the end of the link.
1741 * @param $prefix String: optional prefix. As trail, only before instead of after.
1743 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
1744 wfProfileIn( __METHOD__
);
1746 $query = wfCgiToArray( $query );
1747 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1748 if( $text === '' ) {
1749 $text = $this->linkText( $nt );
1752 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1754 wfProfileOut( __METHOD__
);
1759 * @deprecated Use link()
1761 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1762 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1765 * @param $nt Title object of target page
1766 * @param $text String: text to replace the title
1767 * @param $query String: link target
1768 * @param $trail String: text after link
1769 * @param $prefix String: text before link text
1770 * @param $aprops String: extra attributes to the a-element
1771 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1772 * @return the a-element
1774 function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
1775 wfProfileIn( __METHOD__
);
1777 if ( $text == '' ) {
1778 $text = $this->linkText( $title );
1780 $attribs = Sanitizer
::mergeAttributes(
1781 Sanitizer
::decodeTagAttributes( $aprops ),
1782 Sanitizer
::decodeTagAttributes( $style )
1784 $query = wfCgiToArray( $query );
1785 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1787 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1788 array( 'known', 'noclasses' ) ) . $trail;
1790 wfProfileOut( __METHOD__
);
1795 * @deprecated Use link()
1797 * Make a red link to the edit page of a given title.
1799 * @param $nt Title object of the target page
1800 * @param $text String: Link text
1801 * @param $query String: Optional query part
1802 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1803 * be included in the link text. Other characters will be appended after
1804 * the end of the link.
1806 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1807 wfProfileIn( __METHOD__
);
1809 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1810 if( $text === '' ) {
1811 $text = $this->linkText( $title );
1813 $nt = $this->normaliseSpecialPage( $title );
1815 $ret = $this->link( $title, "$prefix$text$inside", array(),
1816 wfCgiToArray( $query ), 'broken' ) . $trail;
1818 wfProfileOut( __METHOD__
);
1823 * @deprecated Use link()
1825 * Make a brown link to a short article.
1827 * @param $nt Title object of the target page
1828 * @param $text String: link text
1829 * @param $query String: optional query part
1830 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1831 * be included in the link text. Other characters will be appended after
1832 * the end of the link.
1834 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1835 wfDeprecated( __METHOD__
);
1836 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1840 * @deprecated Use link()
1842 * Make a coloured link.
1844 * @param $nt Title object of the target page
1845 * @param $colour Integer: colour of the link
1846 * @param $text String: link text
1847 * @param $query String: optional query part
1848 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1849 * be included in the link text. Other characters will be appended after
1850 * the end of the link.
1852 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1854 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
1856 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1859 /** Obsolete alias */
1860 function makeImage( $url, $alt = '' ) {
1861 wfDeprecated( __METHOD__
);
1862 return $this->makeExternalImage( $url, $alt );
1866 * Creates the HTML source for images
1867 * @deprecated use makeImageLink2
1869 * @param object $title
1870 * @param string $label label text
1871 * @param string $alt alt text
1872 * @param string $align horizontal alignment: none, left, center, right)
1873 * @param array $handlerParams Parameters to be passed to the media handler
1874 * @param boolean $framed shows image in original size in a frame
1875 * @param boolean $thumb shows image as thumbnail in a frame
1876 * @param string $manualthumb image name for the manual thumbnail
1877 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
1878 * @param string $time, timestamp of the file, set as false for current
1881 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
1882 $thumb = false, $manualthumb = '', $valign = '', $time = false )
1884 $frameParams = array( 'alt' => $alt, 'caption' => $label );
1886 $frameParams['align'] = $align;
1889 $frameParams['framed'] = true;
1892 $frameParams['thumbnail'] = true;
1894 if ( $manualthumb ) {
1895 $frameParams['manualthumb'] = $manualthumb;
1898 $frameParams['valign'] = $valign;
1900 $file = wfFindFile( $title, array( 'time' => $time ) );
1901 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
1904 /** @deprecated use Linker::makeMediaLinkObj() */
1905 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
1906 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
1907 return $this->makeMediaLinkObj( $nt, $text, $time );
1911 * Used to generate section edit links that point to "other" pages
1912 * (sections that are really part of included pages).
1914 * @deprecated use Linker::doEditSectionLink()
1915 * @param $title Title string.
1916 * @param $section Integer: section number.
1918 public function editSectionLinkForOther( $title, $section ) {
1919 wfDeprecated( __METHOD__
);
1920 $title = Title
::newFromText( $title );
1921 return $this->doEditSectionLink( $title, $section );
1925 * @deprecated use Linker::doEditSectionLink()
1926 * @param $nt Title object.
1927 * @param $section Integer: section number.
1928 * @param $hint Link String: title, or default if omitted or empty
1930 public function editSectionLink( Title
$nt, $section, $hint = '' ) {
1931 wfDeprecated( __METHOD__
);
1932 if( $hint === '' ) {
1933 # No way to pass an actual empty $hint here! The new interface al-
1934 # lows this, so we have to do this for compatibility.
1937 return $this->doEditSectionLink( $nt, $section, $hint );
1941 * @deprecated Returns raw bits of HTML, use titleAttrib() and accesskey()
1943 public function tooltipAndAccesskey( $name ) {
1944 global $wgEnableTooltipsAndAccesskeys;
1945 if ( !$wgEnableTooltipsAndAccesskeys )
1947 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1948 # no attribute" instead of "output '' as value for attribute", this
1949 # would be three lines.
1951 'title' => $this->titleAttrib( $name, 'withaccess' ),
1952 'accesskey' => $this->accesskey( $name )
1954 if ( $attribs['title'] === false ) {
1955 unset( $attribs['title'] );
1957 if ( $attribs['accesskey'] === false ) {
1958 unset( $attribs['accesskey'] );
1960 return Xml
::expandAttributes( $attribs );
1963 /** @deprecated Returns raw bits of HTML, use titleAttrib() */
1964 public function tooltip( $name, $options = null ) {
1965 global $wgEnableTooltipsAndAccesskeys;
1966 if ( !$wgEnableTooltipsAndAccesskeys )
1968 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1969 # no attribute" instead of "output '' as value for attribute", this
1970 # would be two lines.
1971 $tooltip = $this->titleAttrib( $name, $options );
1972 if ( $tooltip === false ) {
1975 return Xml
::expandAttributes( array(
1976 'title' => $this->titleAttrib( $name, $options )