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 = false ) {
56 $link = urldecode( $link );
57 $link = str_replace( '_', ' ', $link );
58 $link = htmlspecialchars( $link );
61 $r = ' class="'.$class.'"';
66 $r .= " title=\"{$link}\"";
71 * @param $nt Title object.
72 * @param $text String: FIXME
73 * @param $broken Boolean: FIXME, default 'false'.
75 function getInternalLinkAttributesObj( &$nt, $text, $class = false ) {
77 $r = ' class="'.$class.'"';
82 $r .= ' title="' . $nt->getEscapedText() . '"';
87 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
88 * it if you already have a title object handy. See makeLinkObj for further documentation.
90 * @param $title String: the text of the title
91 * @param $text String: link text
92 * @param $query String: optional query part
93 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
94 * be included in the link text. Other characters will be appended after
95 * the end of the link.
97 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
98 wfProfileIn( __METHOD__
);
99 $nt = Title
::newFromText( $title );
100 if ( $nt instanceof Title
) {
101 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
103 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
104 $result = $text == "" ?
$title : $text;
107 wfProfileOut( __METHOD__
);
112 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
113 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
115 * @param $title String: the text of the title
116 * @param $text String: link text
117 * @param $query String: optional query part
118 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
119 * be included in the link text. Other characters will be appended after
120 * the end of the link.
122 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
123 $nt = Title
::newFromText( $title );
124 if ( $nt instanceof Title
) {
125 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
127 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
128 return $text == '' ?
$title : $text;
133 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
134 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
136 * @param string $title The text of the title
137 * @param string $text Link text
138 * @param string $query Optional query part
139 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
140 * be included in the link text. Other characters will be appended after
141 * the end of the link.
143 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
144 $nt = Title
::newFromText( $title );
145 if ( $nt instanceof Title
) {
146 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
148 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
149 return $text == '' ?
$title : $text;
154 * @deprecated use makeColouredLinkObj
156 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
157 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
159 * @param $title String: the text of the title
160 * @param $text String: link text
161 * @param $query String: optional query part
162 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
163 * be included in the link text. Other characters will be appended after
164 * the end of the link.
166 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
167 $nt = Title
::newFromText( $title );
168 if ( $nt instanceof Title
) {
169 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
171 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
172 return $text == '' ?
$title : $text;
177 * Make a link for a title which may or may not be in the database. If you need to
178 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
179 * call to this will result in a DB query.
181 * @param $nt Title: the title object to make the link from, e.g. from
182 * Title::newFromText.
183 * @param $text String: link text
184 * @param $query String: optional query part
185 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
186 * be included in the link text. Other characters will be appended after
187 * the end of the link.
188 * @param $prefix String: optional prefix. As trail, only before instead of after.
190 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
192 wfProfileIn( __METHOD__
);
194 if ( !$nt instanceof Title
) {
196 wfProfileOut( __METHOD__
);
197 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
200 if ( $nt->isExternal() ) {
201 $u = $nt->getFullURL();
202 $link = $nt->getPrefixedURL();
203 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
204 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
207 if ( '' != $trail ) {
209 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
214 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
216 wfProfileOut( __METHOD__
);
218 } elseif ( $nt->isAlwaysKnown() ) {
219 # Image links, special page links and self-links with fragements are always known.
220 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
222 wfProfileIn( __METHOD__
.'-immediate' );
224 # Handles links to special pages wich do not exist in the database:
225 if( $nt->getNamespace() == NS_SPECIAL
) {
226 if( SpecialPage
::exists( $nt->getDbKey() ) ) {
227 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
229 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
231 wfProfileOut( __METHOD__
.'-immediate' );
232 wfProfileOut( __METHOD__
);
236 # Work out link colour immediately
237 $aid = $nt->getArticleID() ;
239 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
242 if ( $nt->isContentPage() ) {
243 $threshold = $wgUser->getOption('stubthreshold');
244 if ( $threshold > 0 ) {
245 $dbr = wfGetDB( DB_SLAVE
);
246 $s = $dbr->selectRow(
249 'page_is_redirect' ),
250 array( 'page_id' => $aid ), __METHOD__
) ;
251 $stub = ( $s !== false && !$s->page_is_redirect
&&
252 $s->page_len
< $threshold );
253 $colour = $stub ?
2 : 1;
254 wfRunHooks( 'GetLinkColour', array( $dbr, $aid, &$colour ) );
257 $retVal = $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
259 wfProfileOut( __METHOD__
.'-immediate' );
261 wfProfileOut( __METHOD__
);
266 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
267 * it doesn't have to do a database query. It's also valid for interwiki titles and special
270 * @param $nt Title object of target page
271 * @param $text String: text to replace the title
272 * @param $query String: link target
273 * @param $trail String: text after link
274 * @param $prefix String: text before link text
275 * @param $aprops String: extra attributes to the a-element
276 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
277 * @return the a-element
279 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
280 wfProfileIn( __METHOD__
);
282 if ( !$nt instanceof Title
) {
284 wfProfileOut( __METHOD__
);
285 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
288 $u = $nt->escapeLocalURL( $query );
289 if ( $nt->getFragment() != '' ) {
290 if( $nt->getPrefixedDbkey() == '' ) {
293 $text = htmlspecialchars( $nt->getFragment() );
296 $u .= $nt->getFragmentForURL();
299 $text = htmlspecialchars( $nt->getPrefixedText() );
301 if ( $style == '' ) {
302 $style = $this->getInternalLinkAttributesObj( $nt, $text );
305 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
307 list( $inside, $trail ) = Linker
::splitTrail( $trail );
308 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
309 wfProfileOut( __METHOD__
);
314 * Make a red link to the edit page of a given title.
316 * @param $title String: The text of the title
317 * @param $text String: Link text
318 * @param $query String: Optional query part
319 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
320 * be included in the link text. Other characters will be appended after
321 * the end of the link.
323 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
324 wfProfileIn( __METHOD__
);
326 if ( !$nt instanceof Title
) {
328 wfProfileOut( __METHOD__
);
329 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
332 if( $nt->getNamespace() == NS_SPECIAL
) {
334 } else if ( '' == $query ) {
337 $q = 'action=edit&'.$query;
339 $u = $nt->escapeLocalURL( $q );
342 $text = htmlspecialchars( $nt->getPrefixedText() );
344 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'new' );
346 list( $inside, $trail ) = Linker
::splitTrail( $trail );
347 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
349 wfProfileOut( __METHOD__
);
354 * @deprecated use makeColouredLinkObj
356 * Make a brown link to a short article.
358 * @param $title String: the text of the title
359 * @param $text String: link text
360 * @param $query String: optional query part
361 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
362 * be included in the link text. Other characters will be appended after
363 * the end of the link.
365 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
366 makeColouredLinkObj( $nt, 2, $text, $query, $trail, $prefix );
370 * Make a coloured link.
372 * @param $title String: the text of the title
373 * @param $colour Integer: colour of the link
374 * @param $text String: link text
375 * @param $query String: optional query part
376 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
377 * be included in the link text. Other characters will be appended after
378 * the end of the link.
380 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
382 // convert colour into class name
388 // allow alternative colour code
389 wfRunHooks( 'GetLinkColourCode', array( &$colourcode ) );
391 $class = $colourcode[$colour];
394 $style = $this->getInternalLinkAttributesObj( $nt, $text, $class );
396 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
400 * Generate either a normal exists-style link or a stub link, depending
401 * on the given page size.
403 * @param $size Integer
404 * @param $nt Title object.
405 * @param $text String
406 * @param $query String
407 * @param $trail String
408 * @param $prefix String
409 * @return string HTML of link
411 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
413 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
414 $colour = ( $size < $threshold ) ?
2 : 1;
415 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
419 * Make appropriate markup for a link to the current article. This is currently rendered
420 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
421 * despite $query not being used.
423 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
425 $text = htmlspecialchars( $nt->getPrefixedText() );
427 list( $inside, $trail ) = Linker
::splitTrail( $trail );
428 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
431 /** @todo document */
432 function fnamePart( $url ) {
433 $basename = strrchr( $url, '/' );
434 if ( false === $basename ) {
437 $basename = substr( $basename, 1 );
439 return htmlspecialchars( $basename );
442 /** Obsolete alias */
443 function makeImage( $url, $alt = '' ) {
444 return $this->makeExternalImage( $url, $alt );
447 /** @todo document */
448 function makeExternalImage( $url, $alt = '' ) {
450 $alt = $this->fnamePart( $url );
452 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
457 * Creates the HTML source for images
458 * @deprecated use makeImageLink2
460 * @param object $title
461 * @param string $label label text
462 * @param string $alt alt text
463 * @param string $align horizontal alignment: none, left, center, right)
464 * @param array $handlerParams Parameters to be passed to the media handler
465 * @param boolean $framed shows image in original size in a frame
466 * @param boolean $thumb shows image as thumbnail in a frame
467 * @param string $manualthumb image name for the manual thumbnail
468 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
471 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
472 $thumb = false, $manualthumb = '', $valign = '', $time = false )
474 $frameParams = array( 'alt' => $alt, 'caption' => $label );
476 $frameParams['align'] = $align;
479 $frameParams['framed'] = true;
482 $frameParams['thumbnail'] = true;
484 if ( $manualthumb ) {
485 $frameParams['manualthumb'] = $manualthumb;
488 $frameParams['valign'] = $valign;
490 $file = wfFindFile( $title, $time );
491 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams );
496 * @param Title $title Title object
497 * @param File $file File object, or false if it doesn't exist
499 * @param array $frameParams Associative array of parameters external to the media handler.
500 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
501 * will often be false.
502 * thumbnail If present, downscale and frame
503 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
504 * framed Shows image in original size in a frame
505 * frameless Downscale but don't frame
506 * upright If present, tweak default sizes for portrait orientation
507 * upright_factor Fudge factor for "upright" tweak (default 0.75)
508 * border If present, show a border around the image
509 * align Horizontal alignment (left, right, center, none)
510 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
511 * bottom, text-bottom)
512 * alt Alternate text for image (i.e. alt attribute). Plain text.
513 * caption HTML for image caption.
515 * @param array $handlerParams Associative array of media handler parameters, to be passed
516 * to transform(). Typical keys are "width" and "page".
518 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
519 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
520 if ( $file && !$file->allowInlineDisplay() ) {
521 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
522 return $this->makeKnownLinkObj( $title );
527 $hp =& $handlerParams;
529 // Clean up parameters
530 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
531 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
532 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
534 $prefix = $postfix = '';
536 if ( 'center' == $fp['align'] )
538 $prefix = '<div class="center">';
540 $fp['align'] = 'none';
542 if ( $file && !isset( $hp['width'] ) ) {
543 $hp['width'] = $file->getWidth( $page );
545 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
546 $wopt = $wgUser->getOption( 'thumbsize' );
548 if( !isset( $wgThumbLimits[$wopt] ) ) {
549 $wopt = User
::getDefaultOption( 'thumbsize' );
552 // Reduce width for upright images when parameter 'upright' is used
553 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
554 $fp['upright'] = $wgThumbUpright;
556 // Use width which is smaller: real image width or user preference width
557 // 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
558 $prefWidth = isset( $fp['upright'] ) ?
559 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
560 $wgThumbLimits[$wopt];
561 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
562 $hp['width'] = $prefWidth;
567 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
569 # Create a thumbnail. Alignment depends on language
570 # writing direction, # right aligned for left-to-right-
571 # languages ("Western languages"), left-aligned
572 # for right-to-left-languages ("Semitic languages")
574 # If thumbnail width has not been provided, it is set
575 # to the default user option as specified in Language*.php
576 if ( $fp['align'] == '' ) {
577 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
579 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp ).$postfix;
582 if ( $file && $hp['width'] ) {
583 # Create a resized image, without the additional thumbnail features
584 $thumb = $file->transform( $hp );
590 $s = $this->makeBrokenImageLinkObj( $title );
592 $s = $thumb->toHtml( array(
595 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
596 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false ) );
598 if ( '' != $fp['align'] ) {
599 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
601 return str_replace("\n", ' ',$prefix.$s.$postfix);
605 * Make HTML for a thumbnail including image, border and caption
606 * @param Title $title
607 * @param File $file File object or false if it doesn't exist
609 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
610 $frameParams = array(
615 if ( $framed ) $frameParams['framed'] = true;
616 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
617 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
620 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
621 global $wgStylePath, $wgContLang;
622 $exists = $file && $file->exists();
626 $hp =& $handlerParams;
628 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
629 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
630 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
631 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
633 if ( empty( $hp['width'] ) ) {
634 // Reduce width for upright images when parameter 'upright' is used
635 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
640 $outerWidth = $hp['width'] +
2;
642 if ( isset( $fp['manualthumb'] ) ) {
643 # Use manually specified thumbnail
644 $manual_title = Title
::makeTitleSafe( NS_IMAGE
, $fp['manualthumb'] );
645 if( $manual_title ) {
646 $manual_img = wfFindFile( $manual_title );
648 $thumb = $manual_img->getUnscaledThumb();
653 } elseif ( isset( $fp['framed'] ) ) {
654 // Use image dimensions, don't scale
655 $thumb = $file->getUnscaledThumb( $page );
657 # Do not present an image bigger than the source, for bitmap-style images
658 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
659 $srcWidth = $file->getWidth( $page );
660 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
661 $hp['width'] = $srcWidth;
663 $thumb = $file->transform( $hp );
667 $outerWidth = $thumb->getWidth() +
2;
669 $outerWidth = $hp['width'] +
2;
673 $query = $page ?
'page=' . urlencode( $page ) : '';
674 $url = $title->getLocalURL( $query );
676 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
677 $magnifyalign = $wgContLang->isRTL() ?
'left' : 'right';
678 $textalign = $wgContLang->isRTL() ?
' style="text-align:right"' : '';
680 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
682 $s .= $this->makeBrokenImageLinkObj( $title );
684 } elseif ( !$thumb ) {
685 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
688 $s .= $thumb->toHtml( array(
690 'img-class' => 'thumbimage',
691 'desc-link' => true ) );
692 if ( isset( $fp['framed'] ) ) {
695 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
696 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
697 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
698 'width="15" height="11" alt="" /></a></div>';
701 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$fp['caption']."</div></div></div>";
702 return str_replace("\n", ' ', $s);
706 * Make a "broken" link to an image
708 * @param Title $title Image title
709 * @param string $text Link label
710 * @param string $query Query string
711 * @param string $trail Link trail
712 * @param string $prefix Link prefix
715 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
716 global $wgEnableUploads;
717 if( $title instanceof Title
) {
718 wfProfileIn( __METHOD__
);
719 if( $wgEnableUploads ) {
720 $upload = SpecialPage
::getTitleFor( 'Upload' );
722 $text = htmlspecialchars( $title->getPrefixedText() );
723 $q = 'wpDestFile=' . $title->getPartialUrl();
726 list( $inside, $trail ) = self
::splitTrail( $trail );
727 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
728 wfProfileOut( __METHOD__
);
729 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
730 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
732 wfProfileOut( __METHOD__
);
733 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
736 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
740 /** @deprecated use Linker::makeMediaLinkObj() */
741 function makeMediaLink( $name, $unused = '', $text = '' ) {
742 $nt = Title
::makeTitleSafe( NS_IMAGE
, $name );
743 return $this->makeMediaLinkObj( $nt, $text );
747 * Create a direct link to a given uploaded file.
749 * @param $title Title object.
750 * @param $text String: pre-sanitized HTML
751 * @return string HTML
754 * @todo Handle invalid or missing images better.
756 function makeMediaLinkObj( $title, $text = '' ) {
757 if( is_null( $title ) ) {
758 ### HOTFIX. Instead of breaking, return empty string.
761 $img = wfFindFile( $title );
763 $url = $img->getURL();
766 $upload = SpecialPage
::getTitleFor( 'Upload' );
767 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDbKey() ) );
770 $alt = htmlspecialchars( $title->getText() );
774 $u = htmlspecialchars( $url );
775 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
779 /** @todo document */
780 function specialLink( $name, $key = '' ) {
783 if ( '' == $key ) { $key = strtolower( $name ); }
784 $pn = $wgContLang->ucfirst( $name );
785 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
789 /** @todo document */
790 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
791 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
792 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
793 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
794 $style .= ' rel="nofollow"';
796 $url = htmlspecialchars( $url );
798 $text = htmlspecialchars( $text );
800 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
804 * Make user link (or user contributions for unregistered users)
805 * @param $userId Integer: user id in database.
806 * @param $userText String: user name in database
807 * @return string HTML fragment
810 function userLink( $userId, $userText ) {
811 $encName = htmlspecialchars( $userText );
813 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
814 return $this->makeKnownLinkObj( $contribsPage,
817 $userPage = Title
::makeTitle( NS_USER
, $userText );
818 return $this->makeLinkObj( $userPage, $encName );
823 * Generate standard user tool links (talk, contributions, block link, etc.)
825 * @param int $userId User identifier
826 * @param string $userText User name or IP address
827 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
828 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
831 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
832 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
833 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
834 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
838 $items[] = $this->userTalkLink( $userId, $userText );
841 // check if the user has an edit
842 if( $redContribsWhenNoEdits && User
::edits( $userId ) == 0 ) {
843 $style = " class='new'";
847 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
849 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
851 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
852 $items[] = $this->blockLink( $userId, $userText );
856 return ' (' . implode( ' | ', $items ) . ')';
863 * Alias for userToolLinks( $userId, $userText, true );
865 public function userToolLinksRedContribs( $userId, $userText ) {
866 return $this->userToolLinks( $userId, $userText, true );
871 * @param $userId Integer: user id in database.
872 * @param $userText String: user name in database.
873 * @return string HTML fragment with user talk link
876 function userTalkLink( $userId, $userText ) {
877 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
878 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
879 return $userTalkLink;
883 * @param $userId Integer: userid
884 * @param $userText String: user name in database.
885 * @return string HTML fragment with block link
888 function blockLink( $userId, $userText ) {
889 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
890 $blockLink = $this->makeKnownLinkObj( $blockPage,
891 wfMsgHtml( 'blocklink' ) );
896 * Generate a user link if the current user is allowed to view it
897 * @param $rev Revision object.
898 * @return string HTML
900 function revUserLink( $rev ) {
901 if( $rev->userCan( Revision
::DELETED_USER
) ) {
902 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
904 $link = wfMsgHtml( 'rev-deleted-user' );
906 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
907 return '<span class="history-deleted">' . $link . '</span>';
913 * Generate a user tool link cluster if the current user is allowed to view it
914 * @param $rev Revision object.
915 * @return string HTML
917 function revUserTools( $rev ) {
918 if( $rev->userCan( Revision
::DELETED_USER
) ) {
919 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
921 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
923 $link = wfMsgHtml( 'rev-deleted-user' );
925 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
926 return '<span class="history-deleted">' . $link . '</span>';
932 * This function is called by all recent changes variants, by the page history,
933 * and by the user contributions list. It is responsible for formatting edit
934 * comments. It escapes any HTML in the comment, but adds some CSS to format
935 * auto-generated comments (from section editing) and formats [[wikilinks]].
937 * @author Erik Moeller <moeller@scireview.de>
939 * Note: there's not always a title to pass to this function.
940 * Since you can't set a default parameter for a reference, I've turned it
941 * temporarily to a value pass. Should be adjusted further. --brion
943 * @param string $comment
944 * @param mixed $title Title object (to generate link to the section in autocomment) or null
945 * @param bool $local Whether section links should refer to local page
947 function formatComment($comment, $title = NULL, $local = false) {
948 wfProfileIn( __METHOD__
);
950 # Sanitize text a bit:
951 $comment = str_replace( "\n", " ", $comment );
952 $comment = htmlspecialchars( $comment );
954 # Render autocomments and make links:
955 $comment = $this->formatAutoComments( $comment, $title, $local );
956 $comment = $this->formatLinksInComment( $comment );
958 wfProfileOut( __METHOD__
);
963 * The pattern for autogen comments is / * foo * /, which makes for
965 * We look for all comments, match any text before and after the comment,
966 * add a separator where needed and format the comment itself with CSS
967 * Called by Linker::formatComment.
969 * @param $comment Comment text
970 * @param $title An optional title object used to links to sections
972 * @todo Document the $local parameter.
974 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
976 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
984 # Generate a valid anchor name from the section title.
985 # Hackish, but should generally work - we strip wiki
986 # syntax, including the magic [[: that is used to
987 # "link rather than show" in case of images and
988 # interlanguage links.
989 $section = str_replace( '[[:', '', $section );
990 $section = str_replace( '[[', '', $section );
991 $section = str_replace( ']]', '', $section );
993 $sectionTitle = Title
::newFromText( '#' . $section);
995 $sectionTitle = wfClone( $title );
996 $sectionTitle->mFragment
= $section;
998 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
1002 if($pre) { $auto = $sep.' '.$auto; }
1003 if($post) { $auto .= ' '.$sep; }
1004 $auto='<span class="autocomment">'.$auto.'</span>';
1005 $comment=$pre.$auto.$post;
1012 * Formats wiki links and media links in text; all other wiki formatting
1015 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1016 * @param string $comment Text to format links in
1019 public function formatLinksInComment( $comment ) {
1020 return preg_replace_callback(
1021 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1022 array( $this, 'formatLinksInCommentCallback' ),
1026 protected function formatLinksInCommentCallback( $match ) {
1029 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1030 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1032 $comment = $match[0];
1034 # Handle link renaming [[foo|text]] will show link as "text"
1035 if( "" != $match[3] ) {
1040 $submatch = array();
1041 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1042 # Media link; trail not supported.
1043 $linkRegexp = '/\[\[(.*?)\]\]/';
1044 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1046 # Other kind of link
1047 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1048 $trail = $submatch[1];
1052 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1053 if (isset($match[1][0]) && $match[1][0] == ':')
1054 $match[1] = substr($match[1], 1);
1055 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1057 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1063 * Wrap a comment in standard punctuation and formatting if
1064 * it's non-empty, otherwise return empty string.
1066 * @param string $comment
1067 * @param mixed $title Title object (to generate link to section in autocomment) or null
1068 * @param bool $local Whether section links should refer to local page
1072 function commentBlock( $comment, $title = NULL, $local = false ) {
1073 // '*' used to be the comment inserted by the software way back
1074 // in antiquity in case none was provided, here for backwards
1075 // compatability, acc. to brion -ævar
1076 if( $comment == '' ||
$comment == '*' ) {
1079 $formatted = $this->formatComment( $comment, $title, $local );
1080 return " <span class=\"comment\">($formatted)</span>";
1085 * Wrap and format the given revision's comment block, if the current
1086 * user is allowed to view it.
1088 * @param Revision $rev
1089 * @param bool $local Whether section links should refer to local page
1090 * @return string HTML
1092 function revComment( Revision
$rev, $local = false ) {
1093 if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1094 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1096 $block = " <span class=\"comment\">" .
1097 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1099 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1100 return " <span class=\"history-deleted\">$block</span>";
1105 /** @todo document */
1106 function tocIndent() {
1110 /** @todo document */
1111 function tocUnindent($level) {
1112 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1116 * parameter level defines if we are on an indentation level
1118 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1119 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1120 $anchor . '"><span class="tocnumber">' .
1121 $tocnumber . '</span> <span class="toctext">' .
1122 $tocline . '</span></a>';
1125 /** @todo document */
1126 function tocLineEnd() {
1130 /** @todo document */
1131 function tocList($toc) {
1132 global $wgJsMimeType;
1133 $title = wfMsgHtml('toc') ;
1135 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1136 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1138 # no trailing newline, script should not be wrapped in a
1140 . "</ul>\n</td></tr></table>"
1141 . '<script type="' . $wgJsMimeType . '">'
1142 . ' if (window.showTocToggle) {'
1143 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1144 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1145 . ' showTocToggle();'
1151 * Used to generate section edit links that point to "other" pages
1152 * (sections that are really part of included pages).
1154 * @param $title Title string.
1155 * @param $section Integer: section number.
1157 public function editSectionLinkForOther( $title, $section ) {
1158 $title = Title
::newFromText( $title );
1159 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1163 * @param $nt Title object.
1164 * @param $section Integer: section number.
1165 * @param $hint Link String: title, or default if omitted or empty
1167 public function editSectionLink( Title
$nt, $section, $hint='' ) {
1169 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1170 $hint = " title=\"$hint\"";
1172 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1176 * Implement editSectionLink and editSectionLinkForOther.
1178 * @param $nt Title object
1179 * @param $section Integer, section number
1180 * @param $hint String, for HTML title attribute
1181 * @param $hook String, name of hook to run
1182 * @return String, HTML to use for edit link
1184 protected function doEditSectionLink( Title
$nt, $section, $hint, $hook ) {
1186 $editurl = '§ion='.$section;
1187 $url = $this->makeKnownLinkObj(
1189 wfMsg('editsection'),
1190 'action=edit'.$editurl,
1195 // The two hooks have slightly different interfaces . . .
1196 if( $hook == 'EditSectionLink' ) {
1197 wfRunHooks( $hook, array( &$this, $nt, $section, $hint, $url, &$result ) );
1198 } elseif( $hook == 'EditSectionLinkForOther' ) {
1199 wfRunHooks( $hook, array( &$this, $nt, $section, $url, &$result ) );
1202 // For reverse compatibility, add the brackets *after* the hook is run,
1203 // and even add them to hook-provided text.
1204 if( is_null( $result ) ) {
1205 $result = wfMsg( 'editsection-brackets', $url );
1207 $result = wfMsg( 'editsection-brackets', $result );
1209 return "<span class=\"editsection\">$result</span>";
1213 * Create a headline for content
1215 * @param int $level The level of the headline (1-6)
1216 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1217 * This *must* be at least '>' for no attribs
1218 * @param string $anchor The anchor to give the headline (the bit after the #)
1219 * @param string $text The text of the header
1220 * @param string $link HTML to add for the section edit link
1222 * @return string HTML headline
1224 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1225 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1229 * Split a link trail, return the "inside" portion and the remainder of the trail
1230 * as a two-element array
1234 static function splitTrail( $trail ) {
1235 static $regex = false;
1236 if ( $regex === false ) {
1238 $regex = $wgContLang->linkTrail();
1241 if ( '' != $trail ) {
1243 if ( preg_match( $regex, $trail, $m ) ) {
1248 return array( $inside, $trail );
1252 * Generate a rollback link for a given revision. Currently it's the
1253 * caller's responsibility to ensure that the revision is the top one. If
1254 * it's not, of course, the user will get an error message.
1256 * If the calling page is called with the parameter &bot=1, all rollback
1257 * links also get that parameter. It causes the edit itself and the rollback
1258 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1259 * changes, so this allows sysops to combat a busy vandal without bothering
1262 * @param Revision $rev
1264 function generateRollback( $rev ) {
1265 return '<span class="mw-rollback-link">['
1266 . $this->buildRollbackLink( $rev )
1271 * Build a raw rollback link, useful for collections of "tool" links
1273 * @param Revision $rev
1276 public function buildRollbackLink( $rev ) {
1277 global $wgRequest, $wgUser;
1278 $title = $rev->getTitle();
1279 $extra = $wgRequest->getBool( 'bot' ) ?
'&bot=1' : '';
1280 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1281 $rev->getUserText() ) ) );
1282 return $this->makeKnownLinkObj(
1284 wfMsgHtml( 'rollbacklink' ),
1285 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1290 * Returns HTML for the "templates used on this page" list.
1292 * @param array $templates Array of templates from Article::getUsedTemplate
1294 * @param bool $preview Whether this is for a preview
1295 * @param bool $section Whether this is for a section edit
1296 * @return string HTML output
1298 public function formatTemplates( $templates, $preview = false, $section = false) {
1300 wfProfileIn( __METHOD__
);
1302 $sk = $wgUser->getSkin();
1305 if ( count( $templates ) > 0 ) {
1306 # Do a batch existence check
1307 $batch = new LinkBatch
;
1308 foreach( $templates as $title ) {
1309 $batch->addObj( $title );
1313 # Construct the HTML
1314 $outText = '<div class="mw-templatesUsedExplanation">';
1316 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1317 } elseif ( $section ) {
1318 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1320 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1322 $outText .= '</div><ul>';
1324 foreach ( $templates as $titleObj ) {
1325 $r = $titleObj->getRestrictions( 'edit' );
1326 if ( in_array( 'sysop', $r ) ) {
1327 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1328 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1329 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1333 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1335 $outText .= '</ul>';
1337 wfProfileOut( __METHOD__
);
1342 * Format a size in bytes for output, using an appropriate
1343 * unit (B, KB, MB or GB) according to the magnitude in question
1345 * @param $size Size to format
1348 public function formatSize( $size ) {
1350 return htmlspecialchars( $wgLang->formatSize( $size ) );
1354 * Given the id of an interface element, constructs the appropriate title
1355 * and accesskey attributes from the system messages. (Note, this is usu-
1356 * ally the id but isn't always, because sometimes the accesskey needs to
1357 * go on a different element than the id, for reverse-compatibility, etc.)
1359 * @param string $name Id of the element, minus prefixes.
1360 * @return string title and accesskey attributes, ready to drop in an
1361 * element (e.g., ' title="This does something [x]" accesskey="x"').
1363 public function tooltipAndAccesskey($name) {
1364 $fname="Linker::tooltipAndAccesskey";
1365 wfProfileIn($fname);
1368 $tooltip = wfMsg('tooltip-'.$name);
1369 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1370 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1371 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1372 $out .= ' title="'.htmlspecialchars($tooltip);
1374 $accesskey = wfMsg('accesskey-'.$name);
1375 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1376 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1377 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1381 wfProfileOut($fname);
1386 * Given the id of an interface element, constructs the appropriate title
1387 * attribute from the system messages. (Note, this is usually the id but
1388 * isn't always, because sometimes the accesskey needs to go on a different
1389 * element than the id, for reverse-compatibility, etc.)
1391 * @param string $name Id of the element, minus prefixes.
1392 * @return string title attribute, ready to drop in an element
1393 * (e.g., ' title="This does something"').
1395 public function tooltip($name) {
1398 $tooltip = wfMsg('tooltip-'.$name);
1399 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1400 $out = ' title="'.htmlspecialchars($tooltip).'"';