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
79 * @param integer $threshold user defined threshold
80 * @return string CSS class
82 function getLinkColour( $s, $threshold ) {
88 if ( !empty( $s->page_is_redirect
) ) {
90 $colour = 'mw-redirect';
91 } elseif ( $threshold > 0 && $s->page_len
< $threshold && Namespace::isContent( $s->page_namespace
) ) {
99 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
100 * it if you already have a title object handy. See makeLinkObj for further documentation.
102 * @param $title String: the text of the title
103 * @param $text String: link text
104 * @param $query String: optional query part
105 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
106 * be included in the link text. Other characters will be appended after
107 * the end of the link.
109 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
110 wfProfileIn( __METHOD__
);
111 $nt = Title
::newFromText( $title );
112 if ( $nt instanceof Title
) {
113 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
115 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
116 $result = $text == "" ?
$title : $text;
119 wfProfileOut( __METHOD__
);
124 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
125 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
127 * @param $title String: the text of the title
128 * @param $text String: link text
129 * @param $query String: optional query part
130 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
131 * be included in the link text. Other characters will be appended after
132 * the end of the link.
134 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
135 $nt = Title
::newFromText( $title );
136 if ( $nt instanceof Title
) {
137 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
139 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
140 return $text == '' ?
$title : $text;
145 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
146 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
148 * @param string $title The text of the title
149 * @param string $text Link text
150 * @param string $query Optional query part
151 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
152 * be included in the link text. Other characters will be appended after
153 * the end of the link.
155 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
156 $nt = Title
::newFromText( $title );
157 if ( $nt instanceof Title
) {
158 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
160 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
161 return $text == '' ?
$title : $text;
166 * @deprecated use makeColouredLinkObj
168 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
169 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
171 * @param $title String: the text of the title
172 * @param $text String: link text
173 * @param $query String: optional query part
174 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
175 * be included in the link text. Other characters will be appended after
176 * the end of the link.
178 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
179 $nt = Title
::newFromText( $title );
180 if ( $nt instanceof Title
) {
181 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
183 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
184 return $text == '' ?
$title : $text;
189 * Make a link for a title which may or may not be in the database. If you need to
190 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
191 * call to this will result in a DB query.
193 * @param $nt Title: the title object to make the link from, e.g. from
194 * Title::newFromText.
195 * @param $text String: link text
196 * @param $query String: optional query part
197 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
198 * be included in the link text. Other characters will be appended after
199 * the end of the link.
200 * @param $prefix String: optional prefix. As trail, only before instead of after.
202 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
204 wfProfileIn( __METHOD__
);
206 if ( !$nt instanceof Title
) {
208 wfProfileOut( __METHOD__
);
209 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
212 if ( $nt->isExternal() ) {
213 $u = $nt->getFullURL();
214 $link = $nt->getPrefixedURL();
215 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
216 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
219 if ( '' != $trail ) {
221 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
226 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
228 wfProfileOut( __METHOD__
);
230 } elseif ( $nt->isAlwaysKnown() ) {
231 # Image links, special page links and self-links with fragements are always known.
232 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
234 wfProfileIn( __METHOD__
.'-immediate' );
236 # Handles links to special pages which do not exist in the database:
237 if( $nt->getNamespace() == NS_SPECIAL
) {
238 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
239 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
241 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
243 wfProfileOut( __METHOD__
.'-immediate' );
244 wfProfileOut( __METHOD__
);
248 # Work out link colour immediately
249 $aid = $nt->getArticleID() ;
251 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
254 # FIXME: This is stupid, we should combine this query with
255 # the Title::getArticleID() query above.
256 $threshold = $wgUser->getOption('stubthreshold');
257 $dbr = wfGetDB( DB_SLAVE
);
258 $s = $dbr->selectRow(
260 array( 'page_len', 'page_is_redirect', 'page_namespace' ),
261 array( 'page_id' => $aid ), __METHOD__
) ;
262 $colour = $this->getLinkColour( $s, $threshold );
264 $retVal = $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
266 wfProfileOut( __METHOD__
.'-immediate' );
268 wfProfileOut( __METHOD__
);
273 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
274 * it doesn't have to do a database query. It's also valid for interwiki titles and special
277 * @param $nt Title object of target page
278 * @param $text String: text to replace the title
279 * @param $query String: link target
280 * @param $trail String: text after link
281 * @param $prefix String: text before link text
282 * @param $aprops String: extra attributes to the a-element
283 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
284 * @return the a-element
286 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
287 wfProfileIn( __METHOD__
);
289 if ( !$nt instanceof Title
) {
291 wfProfileOut( __METHOD__
);
292 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
295 $u = $nt->escapeLocalURL( $query );
296 if ( $nt->getFragment() != '' ) {
297 if( $nt->getPrefixedDbkey() == '' ) {
300 $text = htmlspecialchars( $nt->getFragment() );
303 $u .= $nt->getFragmentForURL();
306 $text = htmlspecialchars( $nt->getPrefixedText() );
308 if ( $style == '' ) {
309 $style = $this->getInternalLinkAttributesObj( $nt, $text );
312 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
314 list( $inside, $trail ) = Linker
::splitTrail( $trail );
315 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
316 wfProfileOut( __METHOD__
);
321 * Make a red link to the edit page of a given title.
323 * @param $nt Title object of the target page
324 * @param $text String: Link text
325 * @param $query String: Optional query part
326 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
327 * be included in the link text. Other characters will be appended after
328 * the end of the link.
330 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
331 wfProfileIn( __METHOD__
);
333 if ( !$nt instanceof Title
) {
335 wfProfileOut( __METHOD__
);
336 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
339 if( $nt->getNamespace() == NS_SPECIAL
) {
341 } else if ( '' == $query ) {
344 $q = 'action=edit&'.$query;
346 $u = $nt->escapeLocalURL( $q );
349 $text = htmlspecialchars( $nt->getPrefixedText() );
351 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'new' );
353 list( $inside, $trail ) = Linker
::splitTrail( $trail );
354 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
356 wfProfileOut( __METHOD__
);
361 * @deprecated use makeColouredLinkObj
363 * Make a brown link to a short article.
365 * @param $nt Title object of the target page
366 * @param $text String: link text
367 * @param $query String: optional query part
368 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
369 * be included in the link text. Other characters will be appended after
370 * the end of the link.
372 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
373 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
377 * Make a coloured link.
379 * @param $nt Title object of the target page
380 * @param $colour Integer: colour of the link
381 * @param $text String: link text
382 * @param $query String: optional query part
383 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
384 * be included in the link text. Other characters will be appended after
385 * the end of the link.
387 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
390 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
392 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
396 * Generate either a normal exists-style link or a stub link, depending
397 * on the given page size.
399 * @param $size Integer
400 * @param $nt Title object.
401 * @param $text String
402 * @param $query String
403 * @param $trail String
404 * @param $prefix String
405 * @return string HTML of link
407 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
409 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
410 $colour = ( $size < $threshold ) ?
'stub' : '';
411 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
415 * Make appropriate markup for a link to the current article. This is currently rendered
416 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
417 * despite $query not being used.
419 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
421 $text = htmlspecialchars( $nt->getPrefixedText() );
423 list( $inside, $trail ) = Linker
::splitTrail( $trail );
424 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
427 /** @todo document */
428 function fnamePart( $url ) {
429 $basename = strrchr( $url, '/' );
430 if ( false === $basename ) {
433 $basename = substr( $basename, 1 );
435 return htmlspecialchars( $basename );
438 /** Obsolete alias */
439 function makeImage( $url, $alt = '' ) {
440 return $this->makeExternalImage( $url, $alt );
443 /** @todo document */
444 function makeExternalImage( $url, $alt = '' ) {
446 $alt = $this->fnamePart( $url );
448 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
453 * Creates the HTML source for images
454 * @deprecated use makeImageLink2
456 * @param object $title
457 * @param string $label label text
458 * @param string $alt alt text
459 * @param string $align horizontal alignment: none, left, center, right)
460 * @param array $handlerParams Parameters to be passed to the media handler
461 * @param boolean $framed shows image in original size in a frame
462 * @param boolean $thumb shows image as thumbnail in a frame
463 * @param string $manualthumb image name for the manual thumbnail
464 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
465 * @param string $time, timestamp of the file, set as false for current
468 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
469 $thumb = false, $manualthumb = '', $valign = '', $time = false )
471 $frameParams = array( 'alt' => $alt, 'caption' => $label );
473 $frameParams['align'] = $align;
476 $frameParams['framed'] = true;
479 $frameParams['thumbnail'] = true;
481 if ( $manualthumb ) {
482 $frameParams['manualthumb'] = $manualthumb;
485 $frameParams['valign'] = $valign;
487 $file = wfFindFile( $title, $time );
488 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
493 * @param Title $title Title object
494 * @param File $file File object, or false if it doesn't exist
496 * @param array $frameParams Associative array of parameters external to the media handler.
497 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
498 * will often be false.
499 * thumbnail If present, downscale and frame
500 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
501 * framed Shows image in original size in a frame
502 * frameless Downscale but don't frame
503 * upright If present, tweak default sizes for portrait orientation
504 * upright_factor Fudge factor for "upright" tweak (default 0.75)
505 * border If present, show a border around the image
506 * align Horizontal alignment (left, right, center, none)
507 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
508 * bottom, text-bottom)
509 * alt Alternate text for image (i.e. alt attribute). Plain text.
510 * caption HTML for image caption.
512 * @param array $handlerParams Associative array of media handler parameters, to be passed
513 * to transform(). Typical keys are "width" and "page".
514 * @param string $time, timestamp of the file, set as false for current
516 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false ) {
517 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
518 if ( $file && !$file->allowInlineDisplay() ) {
519 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
520 return $this->makeKnownLinkObj( $title );
525 $hp =& $handlerParams;
527 // Clean up parameters
528 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
529 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
530 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
532 $prefix = $postfix = '';
534 if ( 'center' == $fp['align'] )
536 $prefix = '<div class="center">';
538 $fp['align'] = 'none';
540 if ( $file && !isset( $hp['width'] ) ) {
541 $hp['width'] = $file->getWidth( $page );
543 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
544 $wopt = $wgUser->getOption( 'thumbsize' );
546 if( !isset( $wgThumbLimits[$wopt] ) ) {
547 $wopt = User
::getDefaultOption( 'thumbsize' );
550 // Reduce width for upright images when parameter 'upright' is used
551 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
552 $fp['upright'] = $wgThumbUpright;
554 // Use width which is smaller: real image width or user preference width
555 // 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
556 $prefWidth = isset( $fp['upright'] ) ?
557 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
558 $wgThumbLimits[$wopt];
559 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
560 $hp['width'] = $prefWidth;
565 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
567 # Create a thumbnail. Alignment depends on language
568 # writing direction, # right aligned for left-to-right-
569 # languages ("Western languages"), left-aligned
570 # for right-to-left-languages ("Semitic languages")
572 # If thumbnail width has not been provided, it is set
573 # to the default user option as specified in Language*.php
574 if ( $fp['align'] == '' ) {
575 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
577 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time ).$postfix;
580 if ( $file && isset( $fp['frameless'] ) ) {
581 $srcWidth = $file->getWidth( $page );
582 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
583 # This is the same behaviour as the "thumb" option does it already.
584 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
585 $hp['width'] = $srcWidth;
589 if ( $file && $hp['width'] ) {
590 # Create a resized image, without the additional thumbnail features
591 $thumb = $file->transform( $hp );
597 $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
599 $s = $thumb->toHtml( array(
602 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
603 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false ) );
605 if ( '' != $fp['align'] ) {
606 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
608 return str_replace("\n", ' ',$prefix.$s.$postfix);
612 * Make HTML for a thumbnail including image, border and caption
613 * @param Title $title
614 * @param File $file File object or false if it doesn't exist
616 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
617 $frameParams = array(
622 if ( $framed ) $frameParams['framed'] = true;
623 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
624 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
627 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false ) {
628 global $wgStylePath, $wgContLang;
629 $exists = $file && $file->exists();
633 $hp =& $handlerParams;
635 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
636 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
637 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
638 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
640 if ( empty( $hp['width'] ) ) {
641 // Reduce width for upright images when parameter 'upright' is used
642 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
647 $outerWidth = $hp['width'] +
2;
649 if ( isset( $fp['manualthumb'] ) ) {
650 # Use manually specified thumbnail
651 $manual_title = Title
::makeTitleSafe( NS_IMAGE
, $fp['manualthumb'] );
652 if( $manual_title ) {
653 $manual_img = wfFindFile( $manual_title );
655 $thumb = $manual_img->getUnscaledThumb();
660 } elseif ( isset( $fp['framed'] ) ) {
661 // Use image dimensions, don't scale
662 $thumb = $file->getUnscaledThumb( $page );
664 # Do not present an image bigger than the source, for bitmap-style images
665 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
666 $srcWidth = $file->getWidth( $page );
667 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
668 $hp['width'] = $srcWidth;
670 $thumb = $file->transform( $hp );
674 $outerWidth = $thumb->getWidth() +
2;
676 $outerWidth = $hp['width'] +
2;
680 $query = $page ?
'page=' . urlencode( $page ) : '';
681 $url = $title->getLocalURL( $query );
683 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
685 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
687 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
689 } elseif ( !$thumb ) {
690 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
693 $s .= $thumb->toHtml( array(
695 'img-class' => 'thumbimage',
696 'desc-link' => true ) );
697 if ( isset( $fp['framed'] ) ) {
700 $zoomicon = '<div class="magnify">'.
701 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
702 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
703 'width="15" height="11" alt="" /></a></div>';
706 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
707 return str_replace("\n", ' ', $s);
711 * Make a "broken" link to an image
713 * @param Title $title Image title
714 * @param string $text Link label
715 * @param string $query Query string
716 * @param string $trail Link trail
717 * @param string $prefix Link prefix
718 * @param bool $time, a file of a certain timestamp was requested
721 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
722 global $wgEnableUploads;
723 if( $title instanceof Title
) {
724 wfProfileIn( __METHOD__
);
725 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
726 if( $wgEnableUploads && !$currentExists ) {
727 $upload = SpecialPage
::getTitleFor( 'Upload' );
729 $text = htmlspecialchars( $title->getPrefixedText() );
730 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
732 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
734 $q = 'wpDestFile=' . $title->getPartialUrl();
737 list( $inside, $trail ) = self
::splitTrail( $trail );
738 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
739 wfProfileOut( __METHOD__
);
740 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
741 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
743 wfProfileOut( __METHOD__
);
744 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
747 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
751 /** @deprecated use Linker::makeMediaLinkObj() */
752 function makeMediaLink( $name, $unused = '', $text = '' ) {
753 $nt = Title
::makeTitleSafe( NS_IMAGE
, $name );
754 return $this->makeMediaLinkObj( $nt, $text );
758 * Create a direct link to a given uploaded file.
760 * @param $title Title object.
761 * @param $text String: pre-sanitized HTML
762 * @return string HTML
765 * @todo Handle invalid or missing images better.
767 function makeMediaLinkObj( $title, $text = '' ) {
768 if( is_null( $title ) ) {
769 ### HOTFIX. Instead of breaking, return empty string.
772 $img = wfFindFile( $title );
774 $url = $img->getURL();
777 $upload = SpecialPage
::getTitleFor( 'Upload' );
778 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
781 $alt = htmlspecialchars( $title->getText() );
785 $u = htmlspecialchars( $url );
786 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
790 /** @todo document */
791 function specialLink( $name, $key = '' ) {
794 if ( '' == $key ) { $key = strtolower( $name ); }
795 $pn = $wgContLang->ucfirst( $name );
796 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
800 /** @todo document */
801 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
802 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
803 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
804 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
805 $style .= ' rel="nofollow"';
807 $url = htmlspecialchars( $url );
809 $text = htmlspecialchars( $text );
811 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
815 * Make user link (or user contributions for unregistered users)
816 * @param $userId Integer: user id in database.
817 * @param $userText String: user name in database
818 * @return string HTML fragment
821 function userLink( $userId, $userText ) {
822 $encName = htmlspecialchars( $userText );
824 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
825 return $this->makeKnownLinkObj( $contribsPage,
828 $userPage = Title
::makeTitle( NS_USER
, $userText );
829 return $this->makeLinkObj( $userPage, $encName );
834 * Generate standard user tool links (talk, contributions, block link, etc.)
836 * @param int $userId User identifier
837 * @param string $userText User name or IP address
838 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
839 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
842 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
843 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
844 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
845 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
849 $items[] = $this->userTalkLink( $userId, $userText );
852 // check if the user has an edit
853 if( $redContribsWhenNoEdits && User
::edits( $userId ) == 0 ) {
854 $style = " class='new'";
858 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
860 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
862 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
863 $items[] = $this->blockLink( $userId, $userText );
867 return ' (' . implode( ' | ', $items ) . ')';
874 * Alias for userToolLinks( $userId, $userText, true );
876 public function userToolLinksRedContribs( $userId, $userText ) {
877 return $this->userToolLinks( $userId, $userText, true );
882 * @param $userId Integer: user id in database.
883 * @param $userText String: user name in database.
884 * @return string HTML fragment with user talk link
887 function userTalkLink( $userId, $userText ) {
888 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
889 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
890 return $userTalkLink;
894 * @param $userId Integer: userid
895 * @param $userText String: user name in database.
896 * @return string HTML fragment with block link
899 function blockLink( $userId, $userText ) {
900 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
901 $blockLink = $this->makeKnownLinkObj( $blockPage,
902 wfMsgHtml( 'blocklink' ) );
907 * Generate a user link if the current user is allowed to view it
908 * @param $rev Revision object.
909 * @return string HTML
911 function revUserLink( $rev ) {
912 if( $rev->userCan( Revision
::DELETED_USER
) ) {
913 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
915 $link = wfMsgHtml( 'rev-deleted-user' );
917 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
918 return '<span class="history-deleted">' . $link . '</span>';
924 * Generate a user tool link cluster if the current user is allowed to view it
925 * @param $rev Revision object.
926 * @return string HTML
928 function revUserTools( $rev ) {
929 if( $rev->userCan( Revision
::DELETED_USER
) ) {
930 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
932 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
934 $link = wfMsgHtml( 'rev-deleted-user' );
936 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
937 return '<span class="history-deleted">' . $link . '</span>';
943 * This function is called by all recent changes variants, by the page history,
944 * and by the user contributions list. It is responsible for formatting edit
945 * comments. It escapes any HTML in the comment, but adds some CSS to format
946 * auto-generated comments (from section editing) and formats [[wikilinks]].
948 * @author Erik Moeller <moeller@scireview.de>
950 * Note: there's not always a title to pass to this function.
951 * Since you can't set a default parameter for a reference, I've turned it
952 * temporarily to a value pass. Should be adjusted further. --brion
954 * @param string $comment
955 * @param mixed $title Title object (to generate link to the section in autocomment) or null
956 * @param bool $local Whether section links should refer to local page
958 function formatComment($comment, $title = NULL, $local = false) {
959 wfProfileIn( __METHOD__
);
961 # Sanitize text a bit:
962 $comment = str_replace( "\n", " ", $comment );
963 $comment = htmlspecialchars( $comment );
965 # Render autocomments and make links:
966 $comment = $this->formatAutoComments( $comment, $title, $local );
967 $comment = $this->formatLinksInComment( $comment );
969 wfProfileOut( __METHOD__
);
974 * The pattern for autogen comments is / * foo * /, which makes for
976 * We look for all comments, match any text before and after the comment,
977 * add a separator where needed and format the comment itself with CSS
978 * Called by Linker::formatComment.
980 * @param string $comment Comment text
981 * @param object $title An optional title object used to links to sections
982 * @return string $comment formatted comment
984 * @todo Document the $local parameter.
986 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
988 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
996 # Generate a valid anchor name from the section title.
997 # Hackish, but should generally work - we strip wiki
998 # syntax, including the magic [[: that is used to
999 # "link rather than show" in case of images and
1000 # interlanguage links.
1001 $section = str_replace( '[[:', '', $section );
1002 $section = str_replace( '[[', '', $section );
1003 $section = str_replace( ']]', '', $section );
1005 $sectionTitle = Title
::newFromText( '#' . $section);
1007 $sectionTitle = wfClone( $title );
1008 $sectionTitle->mFragment
= $section;
1010 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsgForContent( 'sectionlink' ) );
1012 $auto = $link . $auto;
1014 $auto = '- ' . $auto; # written summary $presep autocomment (summary /* section */)
1017 $auto .= ': '; # autocomment $postsep written summary (/* section */ summary)
1019 $auto = '<span class="autocomment">' . $auto . '</span>';
1020 $comment = $pre . $auto . $post;
1027 * Formats wiki links and media links in text; all other wiki formatting
1030 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1031 * @param string $comment Text to format links in
1034 public function formatLinksInComment( $comment ) {
1035 return preg_replace_callback(
1036 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1037 array( $this, 'formatLinksInCommentCallback' ),
1041 protected function formatLinksInCommentCallback( $match ) {
1044 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1045 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1047 $comment = $match[0];
1049 # Handle link renaming [[foo|text]] will show link as "text"
1050 if( "" != $match[3] ) {
1055 $submatch = array();
1056 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1057 # Media link; trail not supported.
1058 $linkRegexp = '/\[\[(.*?)\]\]/';
1059 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1061 # Other kind of link
1062 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1063 $trail = $submatch[1];
1067 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1068 if (isset($match[1][0]) && $match[1][0] == ':')
1069 $match[1] = substr($match[1], 1);
1070 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1072 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1078 * Wrap a comment in standard punctuation and formatting if
1079 * it's non-empty, otherwise return empty string.
1081 * @param string $comment
1082 * @param mixed $title Title object (to generate link to section in autocomment) or null
1083 * @param bool $local Whether section links should refer to local page
1087 function commentBlock( $comment, $title = NULL, $local = false ) {
1088 // '*' used to be the comment inserted by the software way back
1089 // in antiquity in case none was provided, here for backwards
1090 // compatability, acc. to brion -ævar
1091 if( $comment == '' ||
$comment == '*' ) {
1094 $formatted = $this->formatComment( $comment, $title, $local );
1095 return " <span class=\"comment\">($formatted)</span>";
1100 * Wrap and format the given revision's comment block, if the current
1101 * user is allowed to view it.
1103 * @param Revision $rev
1104 * @param bool $local Whether section links should refer to local page
1105 * @return string HTML
1107 function revComment( Revision
$rev, $local = false ) {
1108 if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1109 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1111 $block = " <span class=\"comment\">" .
1112 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1114 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1115 return " <span class=\"history-deleted\">$block</span>";
1120 /** @todo document */
1121 function tocIndent() {
1125 /** @todo document */
1126 function tocUnindent($level) {
1127 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1131 * parameter level defines if we are on an indentation level
1133 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1134 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1135 $anchor . '"><span class="tocnumber">' .
1136 $tocnumber . '</span> <span class="toctext">' .
1137 $tocline . '</span></a>';
1140 /** @todo document */
1141 function tocLineEnd() {
1145 /** @todo document */
1146 function tocList($toc) {
1147 global $wgJsMimeType;
1148 $title = wfMsgHtml('toc') ;
1150 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1151 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1153 # no trailing newline, script should not be wrapped in a
1155 . "</ul>\n</td></tr></table>"
1156 . '<script type="' . $wgJsMimeType . '">'
1157 . ' if (window.showTocToggle) {'
1158 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1159 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1160 . ' showTocToggle();'
1166 * Used to generate section edit links that point to "other" pages
1167 * (sections that are really part of included pages).
1169 * @param $title Title string.
1170 * @param $section Integer: section number.
1172 public function editSectionLinkForOther( $title, $section ) {
1173 $title = Title
::newFromText( $title );
1174 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1178 * @param $nt Title object.
1179 * @param $section Integer: section number.
1180 * @param $hint Link String: title, or default if omitted or empty
1182 public function editSectionLink( Title
$nt, $section, $hint='' ) {
1184 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1185 $hint = " title=\"$hint\"";
1187 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1191 * Implement editSectionLink and editSectionLinkForOther.
1193 * @param $nt Title object
1194 * @param $section Integer, section number
1195 * @param $hint String, for HTML title attribute
1196 * @param $hook String, name of hook to run
1197 * @return String, HTML to use for edit link
1199 protected function doEditSectionLink( Title
$nt, $section, $hint, $hook ) {
1201 $editurl = '§ion='.$section;
1202 $url = $this->makeKnownLinkObj(
1204 wfMsg('editsection'),
1205 'action=edit'.$editurl,
1210 // The two hooks have slightly different interfaces . . .
1211 if( $hook == 'EditSectionLink' ) {
1212 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $hint, $url, &$result ) );
1213 } elseif( $hook == 'EditSectionLinkForOther' ) {
1214 wfRunHooks( 'EditSectionLinkForOther', array( &$this, $nt, $section, $url, &$result ) );
1217 // For reverse compatibility, add the brackets *after* the hook is run,
1218 // and even add them to hook-provided text.
1219 if( is_null( $result ) ) {
1220 $result = wfMsg( 'editsection-brackets', $url );
1222 $result = wfMsg( 'editsection-brackets', $result );
1224 return "<span class=\"editsection\">$result</span>";
1228 * Create a headline for content
1230 * @param int $level The level of the headline (1-6)
1231 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1232 * This *must* be at least '>' for no attribs
1233 * @param string $anchor The anchor to give the headline (the bit after the #)
1234 * @param string $text The text of the header
1235 * @param string $link HTML to add for the section edit link
1237 * @return string HTML headline
1239 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1240 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1244 * Split a link trail, return the "inside" portion and the remainder of the trail
1245 * as a two-element array
1249 static function splitTrail( $trail ) {
1250 static $regex = false;
1251 if ( $regex === false ) {
1253 $regex = $wgContLang->linkTrail();
1256 if ( '' != $trail ) {
1258 if ( preg_match( $regex, $trail, $m ) ) {
1263 return array( $inside, $trail );
1267 * Generate a rollback link for a given revision. Currently it's the
1268 * caller's responsibility to ensure that the revision is the top one. If
1269 * it's not, of course, the user will get an error message.
1271 * If the calling page is called with the parameter &bot=1, all rollback
1272 * links also get that parameter. It causes the edit itself and the rollback
1273 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1274 * changes, so this allows sysops to combat a busy vandal without bothering
1277 * @param Revision $rev
1279 function generateRollback( $rev ) {
1280 return '<span class="mw-rollback-link">['
1281 . $this->buildRollbackLink( $rev )
1286 * Build a raw rollback link, useful for collections of "tool" links
1288 * @param Revision $rev
1291 public function buildRollbackLink( $rev ) {
1292 global $wgRequest, $wgUser;
1293 $title = $rev->getTitle();
1294 $extra = $wgRequest->getBool( 'bot' ) ?
'&bot=1' : '';
1295 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1296 $rev->getUserText() ) ) );
1297 return $this->makeKnownLinkObj(
1299 wfMsgHtml( 'rollbacklink' ),
1300 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1305 * Returns HTML for the "templates used on this page" list.
1307 * @param array $templates Array of templates from Article::getUsedTemplate
1309 * @param bool $preview Whether this is for a preview
1310 * @param bool $section Whether this is for a section edit
1311 * @return string HTML output
1313 public function formatTemplates( $templates, $preview = false, $section = false) {
1315 wfProfileIn( __METHOD__
);
1317 $sk = $wgUser->getSkin();
1320 if ( count( $templates ) > 0 ) {
1321 # Do a batch existence check
1322 $batch = new LinkBatch
;
1323 foreach( $templates as $title ) {
1324 $batch->addObj( $title );
1328 # Construct the HTML
1329 $outText = '<div class="mw-templatesUsedExplanation">';
1331 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1332 } elseif ( $section ) {
1333 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1335 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1337 $outText .= '</div><ul>';
1339 foreach ( $templates as $titleObj ) {
1340 $r = $titleObj->getRestrictions( 'edit' );
1341 if ( in_array( 'sysop', $r ) ) {
1342 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1343 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1344 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1348 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1350 $outText .= '</ul>';
1352 wfProfileOut( __METHOD__
);
1357 * Format a size in bytes for output, using an appropriate
1358 * unit (B, KB, MB or GB) according to the magnitude in question
1360 * @param $size Size to format
1363 public function formatSize( $size ) {
1365 return htmlspecialchars( $wgLang->formatSize( $size ) );
1369 * Given the id of an interface element, constructs the appropriate title
1370 * and accesskey attributes from the system messages. (Note, this is usu-
1371 * ally the id but isn't always, because sometimes the accesskey needs to
1372 * go on a different element than the id, for reverse-compatibility, etc.)
1374 * @param string $name Id of the element, minus prefixes.
1375 * @return string title and accesskey attributes, ready to drop in an
1376 * element (e.g., ' title="This does something [x]" accesskey="x"').
1378 public function tooltipAndAccesskey($name) {
1379 $fname="Linker::tooltipAndAccesskey";
1380 wfProfileIn($fname);
1383 $tooltip = wfMsg('tooltip-'.$name);
1384 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1385 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1386 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1387 $out .= ' title="'.htmlspecialchars($tooltip);
1389 $accesskey = wfMsg('accesskey-'.$name);
1390 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1391 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1392 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1396 wfProfileOut($fname);
1401 * Given the id of an interface element, constructs the appropriate title
1402 * attribute from the system messages. (Note, this is usually the id but
1403 * isn't always, because sometimes the accesskey needs to go on a different
1404 * element than the id, for reverse-compatibility, etc.)
1406 * @param string $name Id of the element, minus prefixes.
1407 * @return string title attribute, ready to drop in an element
1408 * (e.g., ' title="This does something"').
1410 public function tooltip($name) {
1413 $tooltip = wfMsg('tooltip-'.$name);
1414 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1415 $out = ' title="'.htmlspecialchars($tooltip).'"';