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
465 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
466 $thumb = false, $manualthumb = '', $valign = '', $time = false )
468 $frameParams = array( 'alt' => $alt, 'caption' => $label );
470 $frameParams['align'] = $align;
473 $frameParams['framed'] = true;
476 $frameParams['thumbnail'] = true;
478 if ( $manualthumb ) {
479 $frameParams['manualthumb'] = $manualthumb;
482 $frameParams['valign'] = $valign;
484 $file = wfFindFile( $title, $time );
485 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams );
490 * @param Title $title Title object
491 * @param File $file File object, or false if it doesn't exist
493 * @param array $frameParams Associative array of parameters external to the media handler.
494 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
495 * will often be false.
496 * thumbnail If present, downscale and frame
497 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
498 * framed Shows image in original size in a frame
499 * frameless Downscale but don't frame
500 * upright If present, tweak default sizes for portrait orientation
501 * upright_factor Fudge factor for "upright" tweak (default 0.75)
502 * border If present, show a border around the image
503 * align Horizontal alignment (left, right, center, none)
504 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
505 * bottom, text-bottom)
506 * alt Alternate text for image (i.e. alt attribute). Plain text.
507 * caption HTML for image caption.
509 * @param array $handlerParams Associative array of media handler parameters, to be passed
510 * to transform(). Typical keys are "width" and "page".
512 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
513 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
514 if ( $file && !$file->allowInlineDisplay() ) {
515 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
516 return $this->makeKnownLinkObj( $title );
521 $hp =& $handlerParams;
523 // Clean up parameters
524 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
525 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
526 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
528 $prefix = $postfix = '';
530 if ( 'center' == $fp['align'] )
532 $prefix = '<div class="center">';
534 $fp['align'] = 'none';
536 if ( $file && !isset( $hp['width'] ) ) {
537 $hp['width'] = $file->getWidth( $page );
539 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
540 $wopt = $wgUser->getOption( 'thumbsize' );
542 if( !isset( $wgThumbLimits[$wopt] ) ) {
543 $wopt = User
::getDefaultOption( 'thumbsize' );
546 // Reduce width for upright images when parameter 'upright' is used
547 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
548 $fp['upright'] = $wgThumbUpright;
550 // Use width which is smaller: real image width or user preference width
551 // 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
552 $prefWidth = isset( $fp['upright'] ) ?
553 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
554 $wgThumbLimits[$wopt];
555 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
556 $hp['width'] = $prefWidth;
561 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
563 # Create a thumbnail. Alignment depends on language
564 # writing direction, # right aligned for left-to-right-
565 # languages ("Western languages"), left-aligned
566 # for right-to-left-languages ("Semitic languages")
568 # If thumbnail width has not been provided, it is set
569 # to the default user option as specified in Language*.php
570 if ( $fp['align'] == '' ) {
571 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
573 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp ).$postfix;
576 if ( $file && isset( $fp['frameless'] ) ) {
577 $srcWidth = $file->getWidth( $page );
578 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
579 # This is the same behaviour as the "thumb" option does it already.
580 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
581 $hp['width'] = $srcWidth;
585 if ( $file && $hp['width'] ) {
586 # Create a resized image, without the additional thumbnail features
587 $thumb = $file->transform( $hp );
593 $s = $this->makeBrokenImageLinkObj( $title );
595 $s = $thumb->toHtml( array(
598 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
599 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false ) );
601 if ( '' != $fp['align'] ) {
602 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
604 return str_replace("\n", ' ',$prefix.$s.$postfix);
608 * Make HTML for a thumbnail including image, border and caption
609 * @param Title $title
610 * @param File $file File object or false if it doesn't exist
612 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
613 $frameParams = array(
618 if ( $framed ) $frameParams['framed'] = true;
619 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
620 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
623 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
624 global $wgStylePath, $wgContLang;
625 $exists = $file && $file->exists();
629 $hp =& $handlerParams;
631 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
632 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
633 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
634 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
636 if ( empty( $hp['width'] ) ) {
637 // Reduce width for upright images when parameter 'upright' is used
638 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
643 $outerWidth = $hp['width'] +
2;
645 if ( isset( $fp['manualthumb'] ) ) {
646 # Use manually specified thumbnail
647 $manual_title = Title
::makeTitleSafe( NS_IMAGE
, $fp['manualthumb'] );
648 if( $manual_title ) {
649 $manual_img = wfFindFile( $manual_title );
651 $thumb = $manual_img->getUnscaledThumb();
656 } elseif ( isset( $fp['framed'] ) ) {
657 // Use image dimensions, don't scale
658 $thumb = $file->getUnscaledThumb( $page );
660 # Do not present an image bigger than the source, for bitmap-style images
661 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
662 $srcWidth = $file->getWidth( $page );
663 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
664 $hp['width'] = $srcWidth;
666 $thumb = $file->transform( $hp );
670 $outerWidth = $thumb->getWidth() +
2;
672 $outerWidth = $hp['width'] +
2;
676 $query = $page ?
'page=' . urlencode( $page ) : '';
677 $url = $title->getLocalURL( $query );
679 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
681 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
683 $s .= $this->makeBrokenImageLinkObj( $title );
685 } elseif ( !$thumb ) {
686 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
689 $s .= $thumb->toHtml( array(
691 'img-class' => 'thumbimage',
692 'desc-link' => true ) );
693 if ( isset( $fp['framed'] ) ) {
696 $zoomicon = '<div class="magnify">'.
697 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
698 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
699 'width="15" height="11" alt="" /></a></div>';
702 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
703 return str_replace("\n", ' ', $s);
707 * Make a "broken" link to an image
709 * @param Title $title Image title
710 * @param string $text Link label
711 * @param string $query Query string
712 * @param string $trail Link trail
713 * @param string $prefix Link prefix
716 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
717 global $wgEnableUploads;
718 if( $title instanceof Title
) {
719 wfProfileIn( __METHOD__
);
720 $currentFile = wfFindFile( $title );
721 if( $wgEnableUploads && !$currentFile ) {
722 $upload = SpecialPage
::getTitleFor( 'Upload' );
724 $text = htmlspecialchars( $title->getPrefixedText() );
725 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
727 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
729 $q = 'wpDestFile=' . $title->getPartialUrl();
732 list( $inside, $trail ) = self
::splitTrail( $trail );
733 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
734 wfProfileOut( __METHOD__
);
735 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
736 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
738 wfProfileOut( __METHOD__
);
739 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
742 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
746 /** @deprecated use Linker::makeMediaLinkObj() */
747 function makeMediaLink( $name, $unused = '', $text = '' ) {
748 $nt = Title
::makeTitleSafe( NS_IMAGE
, $name );
749 return $this->makeMediaLinkObj( $nt, $text );
753 * Create a direct link to a given uploaded file.
755 * @param $title Title object.
756 * @param $text String: pre-sanitized HTML
757 * @return string HTML
760 * @todo Handle invalid or missing images better.
762 function makeMediaLinkObj( $title, $text = '' ) {
763 if( is_null( $title ) ) {
764 ### HOTFIX. Instead of breaking, return empty string.
767 $img = wfFindFile( $title );
769 $url = $img->getURL();
772 $upload = SpecialPage
::getTitleFor( 'Upload' );
773 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
776 $alt = htmlspecialchars( $title->getText() );
780 $u = htmlspecialchars( $url );
781 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
785 /** @todo document */
786 function specialLink( $name, $key = '' ) {
789 if ( '' == $key ) { $key = strtolower( $name ); }
790 $pn = $wgContLang->ucfirst( $name );
791 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
795 /** @todo document */
796 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
797 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
798 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
799 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
800 $style .= ' rel="nofollow"';
802 $url = htmlspecialchars( $url );
804 $text = htmlspecialchars( $text );
806 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
810 * Make user link (or user contributions for unregistered users)
811 * @param $userId Integer: user id in database.
812 * @param $userText String: user name in database
813 * @return string HTML fragment
816 function userLink( $userId, $userText ) {
817 $encName = htmlspecialchars( $userText );
819 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
820 return $this->makeKnownLinkObj( $contribsPage,
823 $userPage = Title
::makeTitle( NS_USER
, $userText );
824 return $this->makeLinkObj( $userPage, $encName );
829 * Generate standard user tool links (talk, contributions, block link, etc.)
831 * @param int $userId User identifier
832 * @param string $userText User name or IP address
833 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
834 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
837 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
838 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
839 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
840 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
844 $items[] = $this->userTalkLink( $userId, $userText );
847 // check if the user has an edit
848 if( $redContribsWhenNoEdits && User
::edits( $userId ) == 0 ) {
849 $style = " class='new'";
853 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
855 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
857 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
858 $items[] = $this->blockLink( $userId, $userText );
862 return ' (' . implode( ' | ', $items ) . ')';
869 * Alias for userToolLinks( $userId, $userText, true );
871 public function userToolLinksRedContribs( $userId, $userText ) {
872 return $this->userToolLinks( $userId, $userText, true );
877 * @param $userId Integer: user id in database.
878 * @param $userText String: user name in database.
879 * @return string HTML fragment with user talk link
882 function userTalkLink( $userId, $userText ) {
883 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
884 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
885 return $userTalkLink;
889 * @param $userId Integer: userid
890 * @param $userText String: user name in database.
891 * @return string HTML fragment with block link
894 function blockLink( $userId, $userText ) {
895 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
896 $blockLink = $this->makeKnownLinkObj( $blockPage,
897 wfMsgHtml( 'blocklink' ) );
902 * Generate a user link if the current user is allowed to view it
903 * @param $rev Revision object.
904 * @return string HTML
906 function revUserLink( $rev ) {
907 if( $rev->userCan( Revision
::DELETED_USER
) ) {
908 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
910 $link = wfMsgHtml( 'rev-deleted-user' );
912 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
913 return '<span class="history-deleted">' . $link . '</span>';
919 * Generate a user tool link cluster if the current user is allowed to view it
920 * @param $rev Revision object.
921 * @return string HTML
923 function revUserTools( $rev ) {
924 if( $rev->userCan( Revision
::DELETED_USER
) ) {
925 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
927 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
929 $link = wfMsgHtml( 'rev-deleted-user' );
931 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
932 return '<span class="history-deleted">' . $link . '</span>';
938 * This function is called by all recent changes variants, by the page history,
939 * and by the user contributions list. It is responsible for formatting edit
940 * comments. It escapes any HTML in the comment, but adds some CSS to format
941 * auto-generated comments (from section editing) and formats [[wikilinks]].
943 * @author Erik Moeller <moeller@scireview.de>
945 * Note: there's not always a title to pass to this function.
946 * Since you can't set a default parameter for a reference, I've turned it
947 * temporarily to a value pass. Should be adjusted further. --brion
949 * @param string $comment
950 * @param mixed $title Title object (to generate link to the section in autocomment) or null
951 * @param bool $local Whether section links should refer to local page
953 function formatComment($comment, $title = NULL, $local = false) {
954 wfProfileIn( __METHOD__
);
956 # Sanitize text a bit:
957 $comment = str_replace( "\n", " ", $comment );
958 $comment = htmlspecialchars( $comment );
960 # Render autocomments and make links:
961 $comment = $this->formatAutoComments( $comment, $title, $local );
962 $comment = $this->formatLinksInComment( $comment );
964 wfProfileOut( __METHOD__
);
969 * The pattern for autogen comments is / * foo * /, which makes for
971 * We look for all comments, match any text before and after the comment,
972 * add a separator where needed and format the comment itself with CSS
973 * Called by Linker::formatComment.
975 * @param string $comment Comment text
976 * @param object $title An optional title object used to links to sections
977 * @return string $comment formatted comment
979 * @todo Document the $local parameter.
981 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
983 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
991 # Generate a valid anchor name from the section title.
992 # Hackish, but should generally work - we strip wiki
993 # syntax, including the magic [[: that is used to
994 # "link rather than show" in case of images and
995 # interlanguage links.
996 $section = str_replace( '[[:', '', $section );
997 $section = str_replace( '[[', '', $section );
998 $section = str_replace( ']]', '', $section );
1000 $sectionTitle = Title
::newFromText( '#' . $section);
1002 $sectionTitle = wfClone( $title );
1003 $sectionTitle->mFragment
= $section;
1005 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsgForContent( 'sectionlink' ) );
1007 $auto = $link . $auto;
1009 $auto = '- ' . $auto; # written summary $presep autocomment (summary /* section */)
1012 $auto .= ': '; # autocomment $postsep written summary (/* section */ summary)
1014 $auto = '<span class="autocomment">' . $auto . '</span>';
1015 $comment = $pre . $auto . $post;
1022 * Formats wiki links and media links in text; all other wiki formatting
1025 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1026 * @param string $comment Text to format links in
1029 public function formatLinksInComment( $comment ) {
1030 return preg_replace_callback(
1031 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1032 array( $this, 'formatLinksInCommentCallback' ),
1036 protected function formatLinksInCommentCallback( $match ) {
1039 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1040 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1042 $comment = $match[0];
1044 # Handle link renaming [[foo|text]] will show link as "text"
1045 if( "" != $match[3] ) {
1050 $submatch = array();
1051 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1052 # Media link; trail not supported.
1053 $linkRegexp = '/\[\[(.*?)\]\]/';
1054 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1056 # Other kind of link
1057 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1058 $trail = $submatch[1];
1062 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1063 if (isset($match[1][0]) && $match[1][0] == ':')
1064 $match[1] = substr($match[1], 1);
1065 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1067 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1073 * Wrap a comment in standard punctuation and formatting if
1074 * it's non-empty, otherwise return empty string.
1076 * @param string $comment
1077 * @param mixed $title Title object (to generate link to section in autocomment) or null
1078 * @param bool $local Whether section links should refer to local page
1082 function commentBlock( $comment, $title = NULL, $local = false ) {
1083 // '*' used to be the comment inserted by the software way back
1084 // in antiquity in case none was provided, here for backwards
1085 // compatability, acc. to brion -ævar
1086 if( $comment == '' ||
$comment == '*' ) {
1089 $formatted = $this->formatComment( $comment, $title, $local );
1090 return " <span class=\"comment\">($formatted)</span>";
1095 * Wrap and format the given revision's comment block, if the current
1096 * user is allowed to view it.
1098 * @param Revision $rev
1099 * @param bool $local Whether section links should refer to local page
1100 * @return string HTML
1102 function revComment( Revision
$rev, $local = false ) {
1103 if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1104 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1106 $block = " <span class=\"comment\">" .
1107 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1109 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1110 return " <span class=\"history-deleted\">$block</span>";
1115 /** @todo document */
1116 function tocIndent() {
1120 /** @todo document */
1121 function tocUnindent($level) {
1122 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1126 * parameter level defines if we are on an indentation level
1128 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1129 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1130 $anchor . '"><span class="tocnumber">' .
1131 $tocnumber . '</span> <span class="toctext">' .
1132 $tocline . '</span></a>';
1135 /** @todo document */
1136 function tocLineEnd() {
1140 /** @todo document */
1141 function tocList($toc) {
1142 global $wgJsMimeType;
1143 $title = wfMsgHtml('toc') ;
1145 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1146 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1148 # no trailing newline, script should not be wrapped in a
1150 . "</ul>\n</td></tr></table>"
1151 . '<script type="' . $wgJsMimeType . '">'
1152 . ' if (window.showTocToggle) {'
1153 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1154 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1155 . ' showTocToggle();'
1161 * Used to generate section edit links that point to "other" pages
1162 * (sections that are really part of included pages).
1164 * @param $title Title string.
1165 * @param $section Integer: section number.
1167 public function editSectionLinkForOther( $title, $section ) {
1168 $title = Title
::newFromText( $title );
1169 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1173 * @param $nt Title object.
1174 * @param $section Integer: section number.
1175 * @param $hint Link String: title, or default if omitted or empty
1177 public function editSectionLink( Title
$nt, $section, $hint='' ) {
1179 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1180 $hint = " title=\"$hint\"";
1182 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1186 * Implement editSectionLink and editSectionLinkForOther.
1188 * @param $nt Title object
1189 * @param $section Integer, section number
1190 * @param $hint String, for HTML title attribute
1191 * @param $hook String, name of hook to run
1192 * @return String, HTML to use for edit link
1194 protected function doEditSectionLink( Title
$nt, $section, $hint, $hook ) {
1196 $editurl = '§ion='.$section;
1197 $url = $this->makeKnownLinkObj(
1199 wfMsg('editsection'),
1200 'action=edit'.$editurl,
1205 // The two hooks have slightly different interfaces . . .
1206 if( $hook == 'EditSectionLink' ) {
1207 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $hint, $url, &$result ) );
1208 } elseif( $hook == 'EditSectionLinkForOther' ) {
1209 wfRunHooks( 'EditSectionLinkForOther', array( &$this, $nt, $section, $url, &$result ) );
1212 // For reverse compatibility, add the brackets *after* the hook is run,
1213 // and even add them to hook-provided text.
1214 if( is_null( $result ) ) {
1215 $result = wfMsg( 'editsection-brackets', $url );
1217 $result = wfMsg( 'editsection-brackets', $result );
1219 return "<span class=\"editsection\">$result</span>";
1223 * Create a headline for content
1225 * @param int $level The level of the headline (1-6)
1226 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1227 * This *must* be at least '>' for no attribs
1228 * @param string $anchor The anchor to give the headline (the bit after the #)
1229 * @param string $text The text of the header
1230 * @param string $link HTML to add for the section edit link
1232 * @return string HTML headline
1234 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1235 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1239 * Split a link trail, return the "inside" portion and the remainder of the trail
1240 * as a two-element array
1244 static function splitTrail( $trail ) {
1245 static $regex = false;
1246 if ( $regex === false ) {
1248 $regex = $wgContLang->linkTrail();
1251 if ( '' != $trail ) {
1253 if ( preg_match( $regex, $trail, $m ) ) {
1258 return array( $inside, $trail );
1262 * Generate a rollback link for a given revision. Currently it's the
1263 * caller's responsibility to ensure that the revision is the top one. If
1264 * it's not, of course, the user will get an error message.
1266 * If the calling page is called with the parameter &bot=1, all rollback
1267 * links also get that parameter. It causes the edit itself and the rollback
1268 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1269 * changes, so this allows sysops to combat a busy vandal without bothering
1272 * @param Revision $rev
1274 function generateRollback( $rev ) {
1275 return '<span class="mw-rollback-link">['
1276 . $this->buildRollbackLink( $rev )
1281 * Build a raw rollback link, useful for collections of "tool" links
1283 * @param Revision $rev
1286 public function buildRollbackLink( $rev ) {
1287 global $wgRequest, $wgUser;
1288 $title = $rev->getTitle();
1289 $extra = $wgRequest->getBool( 'bot' ) ?
'&bot=1' : '';
1290 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1291 $rev->getUserText() ) ) );
1292 return $this->makeKnownLinkObj(
1294 wfMsgHtml( 'rollbacklink' ),
1295 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1300 * Returns HTML for the "templates used on this page" list.
1302 * @param array $templates Array of templates from Article::getUsedTemplate
1304 * @param bool $preview Whether this is for a preview
1305 * @param bool $section Whether this is for a section edit
1306 * @return string HTML output
1308 public function formatTemplates( $templates, $preview = false, $section = false) {
1310 wfProfileIn( __METHOD__
);
1312 $sk = $wgUser->getSkin();
1315 if ( count( $templates ) > 0 ) {
1316 # Do a batch existence check
1317 $batch = new LinkBatch
;
1318 foreach( $templates as $title ) {
1319 $batch->addObj( $title );
1323 # Construct the HTML
1324 $outText = '<div class="mw-templatesUsedExplanation">';
1326 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1327 } elseif ( $section ) {
1328 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1330 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1332 $outText .= '</div><ul>';
1334 foreach ( $templates as $titleObj ) {
1335 $r = $titleObj->getRestrictions( 'edit' );
1336 if ( in_array( 'sysop', $r ) ) {
1337 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1338 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1339 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1343 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1345 $outText .= '</ul>';
1347 wfProfileOut( __METHOD__
);
1352 * Format a size in bytes for output, using an appropriate
1353 * unit (B, KB, MB or GB) according to the magnitude in question
1355 * @param $size Size to format
1358 public function formatSize( $size ) {
1360 return htmlspecialchars( $wgLang->formatSize( $size ) );
1364 * Given the id of an interface element, constructs the appropriate title
1365 * and accesskey attributes from the system messages. (Note, this is usu-
1366 * ally the id but isn't always, because sometimes the accesskey needs to
1367 * go on a different element than the id, for reverse-compatibility, etc.)
1369 * @param string $name Id of the element, minus prefixes.
1370 * @return string title and accesskey attributes, ready to drop in an
1371 * element (e.g., ' title="This does something [x]" accesskey="x"').
1373 public function tooltipAndAccesskey($name) {
1374 $fname="Linker::tooltipAndAccesskey";
1375 wfProfileIn($fname);
1378 $tooltip = wfMsg('tooltip-'.$name);
1379 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1380 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1381 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1382 $out .= ' title="'.htmlspecialchars($tooltip);
1384 $accesskey = wfMsg('accesskey-'.$name);
1385 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1386 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1387 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1391 wfProfileOut($fname);
1396 * Given the id of an interface element, constructs the appropriate title
1397 * attribute from the system messages. (Note, this is usually the id but
1398 * isn't always, because sometimes the accesskey needs to go on a different
1399 * element than the id, for reverse-compatibility, etc.)
1401 * @param string $name Id of the element, minus prefixes.
1402 * @return string title attribute, ready to drop in an element
1403 * (e.g., ' title="This does something"').
1405 public function tooltip($name) {
1408 $tooltip = wfMsg('tooltip-'.$name);
1409 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1410 $out = ' title="'.htmlspecialchars($tooltip).'"';