3 * Split off some of the internal bits from Skin.php.
4 * These functions are used for primarily page content:
5 * links, embedded images, table of contents. Links are
6 * also used in the skin.
7 * For the moment, Skin is a descendent class of Linker.
8 * In the future, it should probably be further split
9 * so that ever other bit of the wiki doesn't have to
10 * go loading up Skin to get at it.
17 * Flags for userToolLinks()
19 const TOOL_LINKS_NOBLOCK
= 1;
21 function __construct() {}
26 function postParseLinkColour( $s = NULL ) {
31 function getExternalLinkAttributes( $link, $text, $class='' ) {
32 $link = htmlspecialchars( $link );
34 $r = ($class != '') ?
" class=\"$class\"" : " class=\"external\"";
36 $r .= " title=\"{$link}\"";
40 function getInterwikiLinkAttributes( $link, $text, $class='' ) {
43 $link = urldecode( $link );
44 $link = $wgContLang->checkTitleEncoding( $link );
45 $link = preg_replace( '/[\\x00-\\x1f]/', ' ', $link );
46 $link = htmlspecialchars( $link );
48 $r = ($class != '') ?
" class=\"$class\"" : " class=\"external\"";
50 $r .= " title=\"{$link}\"";
55 function getInternalLinkAttributes( $link, $text, $class='' ) {
56 $link = urldecode( $link );
57 $link = str_replace( '_', ' ', $link );
58 $link = htmlspecialchars( $link );
59 $r = ($class != '') ?
' class="' . htmlspecialchars( $class ) . '"' : '';
60 $r .= " title=\"{$link}\"";
65 * @param $nt Title object.
66 * @param $text String: FIXME
67 * @param $class String: CSS class of the link, default ''.
69 function getInternalLinkAttributesObj( &$nt, $text, $class='' ) {
70 $r = ($class != '') ?
' class="' . htmlspecialchars( $class ) . '"' : '';
71 $r .= ' title="' . $nt->getEscapedText() . '"';
76 * Return the CSS colour of a known link
80 * @param integer $threshold
82 function getLinkColour( $s, $threshold ) {
83 if( $threshold > 0 && $s!=false ) {
84 $colour = ( $s->page_len
>= $threshold ||
85 $s->page_is_redirect ||
86 !Namespace::isContent( $s->page_namespace
)
96 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
97 * it if you already have a title object handy. See makeLinkObj for further documentation.
99 * @param $title String: the text of the title
100 * @param $text String: link text
101 * @param $query String: optional query part
102 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
103 * be included in the link text. Other characters will be appended after
104 * the end of the link.
106 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
107 wfProfileIn( __METHOD__
);
108 $nt = Title
::newFromText( $title );
109 if ( $nt instanceof Title
) {
110 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
112 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
113 $result = $text == "" ?
$title : $text;
116 wfProfileOut( __METHOD__
);
121 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
122 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
124 * @param $title String: the text of the title
125 * @param $text String: link text
126 * @param $query String: optional query part
127 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
128 * be included in the link text. Other characters will be appended after
129 * the end of the link.
131 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
132 $nt = Title
::newFromText( $title );
133 if ( $nt instanceof Title
) {
134 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
136 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
137 return $text == '' ?
$title : $text;
142 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
143 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
145 * @param string $title The text of the title
146 * @param string $text Link text
147 * @param string $query Optional query part
148 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
149 * be included in the link text. Other characters will be appended after
150 * the end of the link.
152 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
153 $nt = Title
::newFromText( $title );
154 if ( $nt instanceof Title
) {
155 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
157 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
158 return $text == '' ?
$title : $text;
163 * @deprecated use makeColouredLinkObj
165 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
166 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
168 * @param $title String: the text of the title
169 * @param $text String: link text
170 * @param $query String: optional query part
171 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
172 * be included in the link text. Other characters will be appended after
173 * the end of the link.
175 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
176 $nt = Title
::newFromText( $title );
177 if ( $nt instanceof Title
) {
178 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
180 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
181 return $text == '' ?
$title : $text;
186 * Make a link for a title which may or may not be in the database. If you need to
187 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
188 * call to this will result in a DB query.
190 * @param $nt Title: the title object to make the link from, e.g. from
191 * Title::newFromText.
192 * @param $text String: link text
193 * @param $query String: optional query part
194 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
195 * be included in the link text. Other characters will be appended after
196 * the end of the link.
197 * @param $prefix String: optional prefix. As trail, only before instead of after.
199 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
201 wfProfileIn( __METHOD__
);
203 if ( !$nt instanceof Title
) {
205 wfProfileOut( __METHOD__
);
206 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
209 if ( $nt->isExternal() ) {
210 $u = $nt->getFullURL();
211 $link = $nt->getPrefixedURL();
212 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
213 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
216 if ( '' != $trail ) {
218 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
223 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
225 wfProfileOut( __METHOD__
);
227 } elseif ( $nt->isAlwaysKnown() ) {
228 # Image links, special page links and self-links with fragements are always known.
229 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
231 wfProfileIn( __METHOD__
.'-immediate' );
233 # Handles links to special pages wich do not exist in the database:
234 if( $nt->getNamespace() == NS_SPECIAL
) {
235 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
236 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
238 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
240 wfProfileOut( __METHOD__
.'-immediate' );
241 wfProfileOut( __METHOD__
);
245 # Work out link colour immediately
246 $aid = $nt->getArticleID() ;
248 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
251 if ( $nt->isContentPage() ) {
252 $threshold = $wgUser->getOption('stubthreshold');
253 if ( $threshold > 0 ) {
254 $dbr = wfGetDB( DB_SLAVE
);
255 $s = $dbr->selectRow(
257 array( 'page_len', 'page_is_redirect', 'page_namespace' ),
258 array( 'page_id' => $aid ), __METHOD__
) ;
259 $colour = $this->getLinkColour( $s, $threshold );
262 $retVal = $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
264 wfProfileOut( __METHOD__
.'-immediate' );
266 wfProfileOut( __METHOD__
);
271 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
272 * it doesn't have to do a database query. It's also valid for interwiki titles and special
275 * @param $nt Title object of target page
276 * @param $text String: text to replace the title
277 * @param $query String: link target
278 * @param $trail String: text after link
279 * @param $prefix String: text before link text
280 * @param $aprops String: extra attributes to the a-element
281 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
282 * @return the a-element
284 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
285 wfProfileIn( __METHOD__
);
287 if ( !$nt instanceof Title
) {
289 wfProfileOut( __METHOD__
);
290 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
293 $u = $nt->escapeLocalURL( $query );
294 if ( $nt->getFragment() != '' ) {
295 if( $nt->getPrefixedDbkey() == '' ) {
298 $text = htmlspecialchars( $nt->getFragment() );
301 $u .= $nt->getFragmentForURL();
304 $text = htmlspecialchars( $nt->getPrefixedText() );
306 if ( $style == '' ) {
307 $style = $this->getInternalLinkAttributesObj( $nt, $text );
310 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
312 list( $inside, $trail ) = Linker
::splitTrail( $trail );
313 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
314 wfProfileOut( __METHOD__
);
319 * Make a red link to the edit page of a given title.
321 * @param $nt Title object of the target page
322 * @param $text String: Link text
323 * @param $query String: Optional query part
324 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
325 * be included in the link text. Other characters will be appended after
326 * the end of the link.
328 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
329 wfProfileIn( __METHOD__
);
331 if ( !$nt instanceof Title
) {
333 wfProfileOut( __METHOD__
);
334 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
337 if( $nt->getNamespace() == NS_SPECIAL
) {
339 } else if ( '' == $query ) {
342 $q = 'action=edit&'.$query;
344 $u = $nt->escapeLocalURL( $q );
347 $text = htmlspecialchars( $nt->getPrefixedText() );
349 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'new' );
351 list( $inside, $trail ) = Linker
::splitTrail( $trail );
352 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
354 wfProfileOut( __METHOD__
);
359 * @deprecated use makeColouredLinkObj
361 * Make a brown link to a short article.
363 * @param $nt Title object of the target page
364 * @param $text String: link text
365 * @param $query String: optional query part
366 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
367 * be included in the link text. Other characters will be appended after
368 * the end of the link.
370 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
371 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
375 * Make a coloured link.
377 * @param $nt Title object of the target page
378 * @param $colour Integer: colour of the link
379 * @param $text String: link text
380 * @param $query String: optional query part
381 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
382 * be included in the link text. Other characters will be appended after
383 * the end of the link.
385 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
388 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
390 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
394 * Generate either a normal exists-style link or a stub link, depending
395 * on the given page size.
397 * @param $size Integer
398 * @param $nt Title object.
399 * @param $text String
400 * @param $query String
401 * @param $trail String
402 * @param $prefix String
403 * @return string HTML of link
405 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
407 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
408 $colour = ( $size < $threshold ) ?
'stub' : '';
409 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
413 * Make appropriate markup for a link to the current article. This is currently rendered
414 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
415 * despite $query not being used.
417 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
419 $text = htmlspecialchars( $nt->getPrefixedText() );
421 list( $inside, $trail ) = Linker
::splitTrail( $trail );
422 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
425 /** @todo document */
426 function fnamePart( $url ) {
427 $basename = strrchr( $url, '/' );
428 if ( false === $basename ) {
431 $basename = substr( $basename, 1 );
433 return htmlspecialchars( $basename );
436 /** Obsolete alias */
437 function makeImage( $url, $alt = '' ) {
438 return $this->makeExternalImage( $url, $alt );
441 /** @todo document */
442 function makeExternalImage( $url, $alt = '' ) {
444 $alt = $this->fnamePart( $url );
446 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
451 * Creates the HTML source for images
452 * @deprecated use makeImageLink2
454 * @param object $title
455 * @param string $label label text
456 * @param string $alt alt text
457 * @param string $align horizontal alignment: none, left, center, right)
458 * @param array $handlerParams Parameters to be passed to the media handler
459 * @param boolean $framed shows image in original size in a frame
460 * @param boolean $thumb shows image as thumbnail in a frame
461 * @param string $manualthumb image name for the manual thumbnail
462 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
463 * @param string $time, timestamp of the file, set as false for current
466 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
467 $thumb = false, $manualthumb = '', $valign = '', $time = false )
469 $frameParams = array( 'alt' => $alt, 'caption' => $label );
471 $frameParams['align'] = $align;
474 $frameParams['framed'] = true;
477 $frameParams['thumbnail'] = true;
479 if ( $manualthumb ) {
480 $frameParams['manualthumb'] = $manualthumb;
483 $frameParams['valign'] = $valign;
485 $file = wfFindFile( $title, $time );
486 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
491 * @param Title $title Title object
492 * @param File $file File object, or false if it doesn't exist
494 * @param array $frameParams Associative array of parameters external to the media handler.
495 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
496 * will often be false.
497 * thumbnail If present, downscale and frame
498 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
499 * framed Shows image in original size in a frame
500 * frameless Downscale but don't frame
501 * upright If present, tweak default sizes for portrait orientation
502 * upright_factor Fudge factor for "upright" tweak (default 0.75)
503 * border If present, show a border around the image
504 * align Horizontal alignment (left, right, center, none)
505 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
506 * bottom, text-bottom)
507 * alt Alternate text for image (i.e. alt attribute). Plain text.
508 * caption HTML for image caption.
510 * @param array $handlerParams Associative array of media handler parameters, to be passed
511 * to transform(). Typical keys are "width" and "page".
512 * @param string $time, timestamp of the file, set as false for current
514 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false ) {
515 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
516 if ( $file && !$file->allowInlineDisplay() ) {
517 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
518 return $this->makeKnownLinkObj( $title );
523 $hp =& $handlerParams;
525 // Clean up parameters
526 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
527 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
528 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
530 $prefix = $postfix = '';
532 if ( 'center' == $fp['align'] )
534 $prefix = '<div class="center">';
536 $fp['align'] = 'none';
538 if ( $file && !isset( $hp['width'] ) ) {
539 $hp['width'] = $file->getWidth( $page );
541 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
542 $wopt = $wgUser->getOption( 'thumbsize' );
544 if( !isset( $wgThumbLimits[$wopt] ) ) {
545 $wopt = User
::getDefaultOption( 'thumbsize' );
548 // Reduce width for upright images when parameter 'upright' is used
549 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
550 $fp['upright'] = $wgThumbUpright;
552 // Use width which is smaller: real image width or user preference width
553 // 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
554 $prefWidth = isset( $fp['upright'] ) ?
555 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
556 $wgThumbLimits[$wopt];
557 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
558 $hp['width'] = $prefWidth;
563 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
565 # Create a thumbnail. Alignment depends on language
566 # writing direction, # right aligned for left-to-right-
567 # languages ("Western languages"), left-aligned
568 # for right-to-left-languages ("Semitic languages")
570 # If thumbnail width has not been provided, it is set
571 # to the default user option as specified in Language*.php
572 if ( $fp['align'] == '' ) {
573 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
575 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time ).$postfix;
578 if ( $file && isset( $fp['frameless'] ) ) {
579 $srcWidth = $file->getWidth( $page );
580 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
581 # This is the same behaviour as the "thumb" option does it already.
582 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
583 $hp['width'] = $srcWidth;
587 if ( $file && $hp['width'] ) {
588 # Create a resized image, without the additional thumbnail features
589 $thumb = $file->transform( $hp );
595 $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
597 $s = $thumb->toHtml( array(
600 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
601 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false ) );
603 if ( '' != $fp['align'] ) {
604 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
606 return str_replace("\n", ' ',$prefix.$s.$postfix);
610 * Make HTML for a thumbnail including image, border and caption
611 * @param Title $title
612 * @param File $file File object or false if it doesn't exist
614 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
615 $frameParams = array(
620 if ( $framed ) $frameParams['framed'] = true;
621 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
622 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
625 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false ) {
626 global $wgStylePath, $wgContLang;
627 $exists = $file && $file->exists();
631 $hp =& $handlerParams;
633 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
634 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
635 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
636 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
638 if ( empty( $hp['width'] ) ) {
639 // Reduce width for upright images when parameter 'upright' is used
640 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
645 $outerWidth = $hp['width'] +
2;
647 if ( isset( $fp['manualthumb'] ) ) {
648 # Use manually specified thumbnail
649 $manual_title = Title
::makeTitleSafe( NS_IMAGE
, $fp['manualthumb'] );
650 if( $manual_title ) {
651 $manual_img = wfFindFile( $manual_title );
653 $thumb = $manual_img->getUnscaledThumb();
658 } elseif ( isset( $fp['framed'] ) ) {
659 // Use image dimensions, don't scale
660 $thumb = $file->getUnscaledThumb( $page );
662 # Do not present an image bigger than the source, for bitmap-style images
663 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
664 $srcWidth = $file->getWidth( $page );
665 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
666 $hp['width'] = $srcWidth;
668 $thumb = $file->transform( $hp );
672 $outerWidth = $thumb->getWidth() +
2;
674 $outerWidth = $hp['width'] +
2;
678 $query = $page ?
'page=' . urlencode( $page ) : '';
679 $url = $title->getLocalURL( $query );
681 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
683 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
685 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
687 } elseif ( !$thumb ) {
688 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
691 $s .= $thumb->toHtml( array(
693 'img-class' => 'thumbimage',
694 'desc-link' => true ) );
695 if ( isset( $fp['framed'] ) ) {
698 $zoomicon = '<div class="magnify">'.
699 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
700 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
701 'width="15" height="11" alt="" /></a></div>';
704 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
705 return str_replace("\n", ' ', $s);
709 * Make a "broken" link to an image
711 * @param Title $title Image title
712 * @param string $text Link label
713 * @param string $query Query string
714 * @param string $trail Link trail
715 * @param string $prefix Link prefix
716 * @param bool $time, a file of a certain timestamp was requested
719 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
720 global $wgEnableUploads;
721 if( $title instanceof Title
) {
722 wfProfileIn( __METHOD__
);
723 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
724 if( $wgEnableUploads && !$currentExists ) {
725 $upload = SpecialPage
::getTitleFor( 'Upload' );
727 $text = htmlspecialchars( $title->getPrefixedText() );
728 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
730 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
732 $q = 'wpDestFile=' . $title->getPartialUrl();
735 list( $inside, $trail ) = self
::splitTrail( $trail );
736 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
737 wfProfileOut( __METHOD__
);
738 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
739 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
741 wfProfileOut( __METHOD__
);
742 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
745 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
749 /** @deprecated use Linker::makeMediaLinkObj() */
750 function makeMediaLink( $name, $unused = '', $text = '' ) {
751 $nt = Title
::makeTitleSafe( NS_IMAGE
, $name );
752 return $this->makeMediaLinkObj( $nt, $text );
756 * Create a direct link to a given uploaded file.
758 * @param $title Title object.
759 * @param $text String: pre-sanitized HTML
760 * @return string HTML
763 * @todo Handle invalid or missing images better.
765 function makeMediaLinkObj( $title, $text = '' ) {
766 if( is_null( $title ) ) {
767 ### HOTFIX. Instead of breaking, return empty string.
770 $img = wfFindFile( $title );
772 $url = $img->getURL();
775 $upload = SpecialPage
::getTitleFor( 'Upload' );
776 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
779 $alt = htmlspecialchars( $title->getText() );
783 $u = htmlspecialchars( $url );
784 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
788 /** @todo document */
789 function specialLink( $name, $key = '' ) {
792 if ( '' == $key ) { $key = strtolower( $name ); }
793 $pn = $wgContLang->ucfirst( $name );
794 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
798 /** @todo document */
799 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
800 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
801 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
802 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
803 $style .= ' rel="nofollow"';
805 $url = htmlspecialchars( $url );
807 $text = htmlspecialchars( $text );
809 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
813 * Make user link (or user contributions for unregistered users)
814 * @param $userId Integer: user id in database.
815 * @param $userText String: user name in database
816 * @return string HTML fragment
819 function userLink( $userId, $userText ) {
820 $encName = htmlspecialchars( $userText );
822 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
823 return $this->makeKnownLinkObj( $contribsPage,
826 $userPage = Title
::makeTitle( NS_USER
, $userText );
827 return $this->makeLinkObj( $userPage, $encName );
832 * Generate standard user tool links (talk, contributions, block link, etc.)
834 * @param int $userId User identifier
835 * @param string $userText User name or IP address
836 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
837 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
840 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
841 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
842 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
843 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
847 $items[] = $this->userTalkLink( $userId, $userText );
850 // check if the user has an edit
851 if( $redContribsWhenNoEdits && User
::edits( $userId ) == 0 ) {
852 $style = " class='new'";
856 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
858 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
860 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
861 $items[] = $this->blockLink( $userId, $userText );
865 return ' (' . implode( ' | ', $items ) . ')';
872 * Alias for userToolLinks( $userId, $userText, true );
874 public function userToolLinksRedContribs( $userId, $userText ) {
875 return $this->userToolLinks( $userId, $userText, true );
880 * @param $userId Integer: user id in database.
881 * @param $userText String: user name in database.
882 * @return string HTML fragment with user talk link
885 function userTalkLink( $userId, $userText ) {
886 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
887 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
888 return $userTalkLink;
892 * @param $userId Integer: userid
893 * @param $userText String: user name in database.
894 * @return string HTML fragment with block link
897 function blockLink( $userId, $userText ) {
898 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
899 $blockLink = $this->makeKnownLinkObj( $blockPage,
900 wfMsgHtml( 'blocklink' ) );
905 * Generate a user link if the current user is allowed to view it
906 * @param $rev Revision object.
907 * @return string HTML
909 function revUserLink( $rev ) {
910 if( $rev->userCan( Revision
::DELETED_USER
) ) {
911 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
913 $link = wfMsgHtml( 'rev-deleted-user' );
915 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
916 return '<span class="history-deleted">' . $link . '</span>';
922 * Generate a user tool link cluster if the current user is allowed to view it
923 * @param $rev Revision object.
924 * @return string HTML
926 function revUserTools( $rev ) {
927 if( $rev->userCan( Revision
::DELETED_USER
) ) {
928 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
930 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
932 $link = wfMsgHtml( 'rev-deleted-user' );
934 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
935 return '<span class="history-deleted">' . $link . '</span>';
941 * This function is called by all recent changes variants, by the page history,
942 * and by the user contributions list. It is responsible for formatting edit
943 * comments. It escapes any HTML in the comment, but adds some CSS to format
944 * auto-generated comments (from section editing) and formats [[wikilinks]].
946 * @author Erik Moeller <moeller@scireview.de>
948 * Note: there's not always a title to pass to this function.
949 * Since you can't set a default parameter for a reference, I've turned it
950 * temporarily to a value pass. Should be adjusted further. --brion
952 * @param string $comment
953 * @param mixed $title Title object (to generate link to the section in autocomment) or null
954 * @param bool $local Whether section links should refer to local page
956 function formatComment($comment, $title = NULL, $local = false) {
957 wfProfileIn( __METHOD__
);
959 # Sanitize text a bit:
960 $comment = str_replace( "\n", " ", $comment );
961 $comment = htmlspecialchars( $comment );
963 # Render autocomments and make links:
964 $comment = $this->formatAutoComments( $comment, $title, $local );
965 $comment = $this->formatLinksInComment( $comment );
967 wfProfileOut( __METHOD__
);
972 * The pattern for autogen comments is / * foo * /, which makes for
974 * We look for all comments, match any text before and after the comment,
975 * add a separator where needed and format the comment itself with CSS
976 * Called by Linker::formatComment.
978 * @param string $comment Comment text
979 * @param object $title An optional title object used to links to sections
980 * @return string $comment formatted comment
982 * @todo Document the $local parameter.
984 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
986 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
994 # Generate a valid anchor name from the section title.
995 # Hackish, but should generally work - we strip wiki
996 # syntax, including the magic [[: that is used to
997 # "link rather than show" in case of images and
998 # interlanguage links.
999 $section = str_replace( '[[:', '', $section );
1000 $section = str_replace( '[[', '', $section );
1001 $section = str_replace( ']]', '', $section );
1003 $sectionTitle = Title
::newFromText( '#' . $section);
1005 $sectionTitle = wfClone( $title );
1006 $sectionTitle->mFragment
= $section;
1008 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsgForContent( 'sectionlink' ) );
1010 $auto = $link . $auto;
1012 $auto = '- ' . $auto; # written summary $presep autocomment (summary /* section */)
1015 $auto .= ': '; # autocomment $postsep written summary (/* section */ summary)
1017 $auto = '<span class="autocomment">' . $auto . '</span>';
1018 $comment = $pre . $auto . $post;
1025 * Formats wiki links and media links in text; all other wiki formatting
1028 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1029 * @param string $comment Text to format links in
1032 public function formatLinksInComment( $comment ) {
1033 return preg_replace_callback(
1034 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1035 array( $this, 'formatLinksInCommentCallback' ),
1039 protected function formatLinksInCommentCallback( $match ) {
1042 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1043 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1045 $comment = $match[0];
1047 # Handle link renaming [[foo|text]] will show link as "text"
1048 if( "" != $match[3] ) {
1053 $submatch = array();
1054 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1055 # Media link; trail not supported.
1056 $linkRegexp = '/\[\[(.*?)\]\]/';
1057 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1059 # Other kind of link
1060 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1061 $trail = $submatch[1];
1065 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1066 if (isset($match[1][0]) && $match[1][0] == ':')
1067 $match[1] = substr($match[1], 1);
1068 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1070 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1076 * Wrap a comment in standard punctuation and formatting if
1077 * it's non-empty, otherwise return empty string.
1079 * @param string $comment
1080 * @param mixed $title Title object (to generate link to section in autocomment) or null
1081 * @param bool $local Whether section links should refer to local page
1085 function commentBlock( $comment, $title = NULL, $local = false ) {
1086 // '*' used to be the comment inserted by the software way back
1087 // in antiquity in case none was provided, here for backwards
1088 // compatability, acc. to brion -ævar
1089 if( $comment == '' ||
$comment == '*' ) {
1092 $formatted = $this->formatComment( $comment, $title, $local );
1093 return " <span class=\"comment\">($formatted)</span>";
1098 * Wrap and format the given revision's comment block, if the current
1099 * user is allowed to view it.
1101 * @param Revision $rev
1102 * @param bool $local Whether section links should refer to local page
1103 * @return string HTML
1105 function revComment( Revision
$rev, $local = false ) {
1106 if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1107 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1109 $block = " <span class=\"comment\">" .
1110 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1112 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1113 return " <span class=\"history-deleted\">$block</span>";
1118 /** @todo document */
1119 function tocIndent() {
1123 /** @todo document */
1124 function tocUnindent($level) {
1125 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1129 * parameter level defines if we are on an indentation level
1131 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1132 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1133 $anchor . '"><span class="tocnumber">' .
1134 $tocnumber . '</span> <span class="toctext">' .
1135 $tocline . '</span></a>';
1138 /** @todo document */
1139 function tocLineEnd() {
1143 /** @todo document */
1144 function tocList($toc) {
1145 global $wgJsMimeType;
1146 $title = wfMsgHtml('toc') ;
1148 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1149 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1151 # no trailing newline, script should not be wrapped in a
1153 . "</ul>\n</td></tr></table>"
1154 . '<script type="' . $wgJsMimeType . '">'
1155 . ' if (window.showTocToggle) {'
1156 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1157 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1158 . ' showTocToggle();'
1164 * Used to generate section edit links that point to "other" pages
1165 * (sections that are really part of included pages).
1167 * @param $title Title string.
1168 * @param $section Integer: section number.
1170 public function editSectionLinkForOther( $title, $section ) {
1171 $title = Title
::newFromText( $title );
1172 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1176 * @param $nt Title object.
1177 * @param $section Integer: section number.
1178 * @param $hint Link String: title, or default if omitted or empty
1180 public function editSectionLink( Title
$nt, $section, $hint='' ) {
1182 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1183 $hint = " title=\"$hint\"";
1185 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1189 * Implement editSectionLink and editSectionLinkForOther.
1191 * @param $nt Title object
1192 * @param $section Integer, section number
1193 * @param $hint String, for HTML title attribute
1194 * @param $hook String, name of hook to run
1195 * @return String, HTML to use for edit link
1197 protected function doEditSectionLink( Title
$nt, $section, $hint, $hook ) {
1199 $editurl = '§ion='.$section;
1200 $url = $this->makeKnownLinkObj(
1202 wfMsg('editsection'),
1203 'action=edit'.$editurl,
1208 // The two hooks have slightly different interfaces . . .
1209 if( $hook == 'EditSectionLink' ) {
1210 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $hint, $url, &$result ) );
1211 } elseif( $hook == 'EditSectionLinkForOther' ) {
1212 wfRunHooks( 'EditSectionLinkForOther', array( &$this, $nt, $section, $url, &$result ) );
1215 // For reverse compatibility, add the brackets *after* the hook is run,
1216 // and even add them to hook-provided text.
1217 if( is_null( $result ) ) {
1218 $result = wfMsg( 'editsection-brackets', $url );
1220 $result = wfMsg( 'editsection-brackets', $result );
1222 return "<span class=\"editsection\">$result</span>";
1226 * Create a headline for content
1228 * @param int $level The level of the headline (1-6)
1229 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1230 * This *must* be at least '>' for no attribs
1231 * @param string $anchor The anchor to give the headline (the bit after the #)
1232 * @param string $text The text of the header
1233 * @param string $link HTML to add for the section edit link
1235 * @return string HTML headline
1237 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1238 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1242 * Split a link trail, return the "inside" portion and the remainder of the trail
1243 * as a two-element array
1247 static function splitTrail( $trail ) {
1248 static $regex = false;
1249 if ( $regex === false ) {
1251 $regex = $wgContLang->linkTrail();
1254 if ( '' != $trail ) {
1256 if ( preg_match( $regex, $trail, $m ) ) {
1261 return array( $inside, $trail );
1265 * Generate a rollback link for a given revision. Currently it's the
1266 * caller's responsibility to ensure that the revision is the top one. If
1267 * it's not, of course, the user will get an error message.
1269 * If the calling page is called with the parameter &bot=1, all rollback
1270 * links also get that parameter. It causes the edit itself and the rollback
1271 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1272 * changes, so this allows sysops to combat a busy vandal without bothering
1275 * @param Revision $rev
1277 function generateRollback( $rev ) {
1278 return '<span class="mw-rollback-link">['
1279 . $this->buildRollbackLink( $rev )
1284 * Build a raw rollback link, useful for collections of "tool" links
1286 * @param Revision $rev
1289 public function buildRollbackLink( $rev ) {
1290 global $wgRequest, $wgUser;
1291 $title = $rev->getTitle();
1292 $extra = $wgRequest->getBool( 'bot' ) ?
'&bot=1' : '';
1293 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1294 $rev->getUserText() ) ) );
1295 return $this->makeKnownLinkObj(
1297 wfMsgHtml( 'rollbacklink' ),
1298 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1303 * Returns HTML for the "templates used on this page" list.
1305 * @param array $templates Array of templates from Article::getUsedTemplate
1307 * @param bool $preview Whether this is for a preview
1308 * @param bool $section Whether this is for a section edit
1309 * @return string HTML output
1311 public function formatTemplates( $templates, $preview = false, $section = false) {
1313 wfProfileIn( __METHOD__
);
1315 $sk = $wgUser->getSkin();
1318 if ( count( $templates ) > 0 ) {
1319 # Do a batch existence check
1320 $batch = new LinkBatch
;
1321 foreach( $templates as $title ) {
1322 $batch->addObj( $title );
1326 # Construct the HTML
1327 $outText = '<div class="mw-templatesUsedExplanation">';
1329 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1330 } elseif ( $section ) {
1331 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1333 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1335 $outText .= '</div><ul>';
1337 foreach ( $templates as $titleObj ) {
1338 $r = $titleObj->getRestrictions( 'edit' );
1339 if ( in_array( 'sysop', $r ) ) {
1340 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1341 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1342 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1346 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1348 $outText .= '</ul>';
1350 wfProfileOut( __METHOD__
);
1355 * Format a size in bytes for output, using an appropriate
1356 * unit (B, KB, MB or GB) according to the magnitude in question
1358 * @param $size Size to format
1361 public function formatSize( $size ) {
1363 return htmlspecialchars( $wgLang->formatSize( $size ) );
1367 * Given the id of an interface element, constructs the appropriate title
1368 * and accesskey attributes from the system messages. (Note, this is usu-
1369 * ally the id but isn't always, because sometimes the accesskey needs to
1370 * go on a different element than the id, for reverse-compatibility, etc.)
1372 * @param string $name Id of the element, minus prefixes.
1373 * @return string title and accesskey attributes, ready to drop in an
1374 * element (e.g., ' title="This does something [x]" accesskey="x"').
1376 public function tooltipAndAccesskey($name) {
1377 $fname="Linker::tooltipAndAccesskey";
1378 wfProfileIn($fname);
1381 $tooltip = wfMsg('tooltip-'.$name);
1382 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1383 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1384 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1385 $out .= ' title="'.htmlspecialchars($tooltip);
1387 $accesskey = wfMsg('accesskey-'.$name);
1388 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1389 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1390 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1394 wfProfileOut($fname);
1399 * Given the id of an interface element, constructs the appropriate title
1400 * attribute from the system messages. (Note, this is usually the id but
1401 * isn't always, because sometimes the accesskey needs to go on a different
1402 * element than the id, for reverse-compatibility, etc.)
1404 * @param string $name Id of the element, minus prefixes.
1405 * @return string title attribute, ready to drop in an element
1406 * (e.g., ' title="This does something"').
1408 public function tooltip($name) {
1411 $tooltip = wfMsg('tooltip-'.$name);
1412 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1413 $out = ' title="'.htmlspecialchars($tooltip).'"';