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, $broken = false ) {
56 $link = urldecode( $link );
57 $link = str_replace( '_', ' ', $link );
58 $link = htmlspecialchars( $link );
60 if( $broken == 'stub' ) {
62 } else if ( $broken == 'yes' ) {
68 $r .= " title=\"{$link}\"";
73 * @param $nt Title object.
74 * @param $text String: FIXME
75 * @param $broken Boolean: FIXME, default 'false'.
77 function getInternalLinkAttributesObj( &$nt, $text, $broken = false ) {
78 if( $broken == 'stub' ) {
80 } else if ( $broken == 'yes' ) {
86 $r .= ' title="' . $nt->getEscapedText() . '"';
91 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
92 * it if you already have a title object handy. See makeLinkObj for further documentation.
94 * @param $title String: the text of the title
95 * @param $text String: link text
96 * @param $query String: optional query part
97 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
98 * be included in the link text. Other characters will be appended after
99 * the end of the link.
101 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
102 wfProfileIn( __METHOD__
);
103 $nt = Title
::newFromText( $title );
104 if ( $nt instanceof Title
) {
105 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
107 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
108 $result = $text == "" ?
$title : $text;
111 wfProfileOut( __METHOD__
);
116 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
117 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
119 * @param $title String: the text of the title
120 * @param $text String: link text
121 * @param $query String: optional query part
122 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
123 * be included in the link text. Other characters will be appended after
124 * the end of the link.
126 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
127 $nt = Title
::newFromText( $title );
128 if ( $nt instanceof Title
) {
129 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
131 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
132 return $text == '' ?
$title : $text;
137 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
138 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
140 * @param string $title The text of the title
141 * @param string $text Link text
142 * @param string $query Optional query part
143 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
144 * be included in the link text. Other characters will be appended after
145 * the end of the link.
147 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
148 $nt = Title
::newFromText( $title );
149 if ( $nt instanceof Title
) {
150 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
152 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
153 return $text == '' ?
$title : $text;
158 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
159 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
161 * @param $title String: the text of the title
162 * @param $text String: link text
163 * @param $query String: optional query part
164 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
165 * be included in the link text. Other characters will be appended after
166 * the end of the link.
168 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
169 $nt = Title
::newFromText( $title );
170 if ( $nt instanceof Title
) {
171 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
173 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
174 return $text == '' ?
$title : $text;
179 * Make a link for a title which may or may not be in the database. If you need to
180 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
181 * call to this will result in a DB query.
183 * @param $nt Title: the title object to make the link from, e.g. from
184 * Title::newFromText.
185 * @param $text String: link text
186 * @param $query String: optional query part
187 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
188 * be included in the link text. Other characters will be appended after
189 * the end of the link.
190 * @param $prefix String: optional prefix. As trail, only before instead of after.
192 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
194 wfProfileIn( __METHOD__
);
196 if ( !$nt instanceof Title
) {
198 wfProfileOut( __METHOD__
);
199 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
202 if ( $nt->isExternal() ) {
203 $u = $nt->getFullURL();
204 $link = $nt->getPrefixedURL();
205 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
206 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
209 if ( '' != $trail ) {
211 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
216 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
218 wfProfileOut( __METHOD__
);
220 } elseif ( $nt->isAlwaysKnown() ) {
221 # Image links, special page links and self-links with fragements are always known.
222 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
224 wfProfileIn( __METHOD__
.'-immediate' );
226 # Handles links to special pages wich do not exist in the database:
227 if( $nt->getNamespace() == NS_SPECIAL
) {
228 if( SpecialPage
::exists( $nt->getDbKey() ) ) {
229 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
231 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
233 wfProfileOut( __METHOD__
.'-immediate' );
234 wfProfileOut( __METHOD__
);
238 # Work out link colour immediately
239 $aid = $nt->getArticleID() ;
241 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
244 if ( $nt->isContentPage() ) {
245 $threshold = $wgUser->getOption('stubthreshold');
246 if ( $threshold > 0 ) {
247 $dbr = wfGetDB( DB_SLAVE
);
248 $s = $dbr->selectRow(
251 'page_is_redirect' ),
252 array( 'page_id' => $aid ), __METHOD__
) ;
253 $stub = ( $s !== false && !$s->page_is_redirect
&&
254 $s->page_len
< $threshold );
258 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
260 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
263 wfProfileOut( __METHOD__
.'-immediate' );
265 wfProfileOut( __METHOD__
);
270 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
271 * it doesn't have to do a database query. It's also valid for interwiki titles and special
274 * @param $nt Title object of target page
275 * @param $text String: text to replace the title
276 * @param $query String: link target
277 * @param $trail String: text after link
278 * @param $prefix String: text before link text
279 * @param $aprops String: extra attributes to the a-element
280 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
281 * @return the a-element
283 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
284 wfProfileIn( __METHOD__
);
286 if ( !$nt instanceof Title
) {
288 wfProfileOut( __METHOD__
);
289 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
292 $u = $nt->escapeLocalURL( $query );
293 if ( $nt->getFragment() != '' ) {
294 if( $nt->getPrefixedDbkey() == '' ) {
297 $text = htmlspecialchars( $nt->getFragment() );
300 $u .= $nt->getFragmentForURL();
303 $text = htmlspecialchars( $nt->getPrefixedText() );
305 if ( $style == '' ) {
306 $style = $this->getInternalLinkAttributesObj( $nt, $text );
309 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
311 list( $inside, $trail ) = Linker
::splitTrail( $trail );
312 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
313 wfProfileOut( __METHOD__
);
318 * Make a red link to the edit page of a given title.
320 * @param $title String: The text of the title
321 * @param $text String: Link text
322 * @param $query String: Optional query part
323 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
324 * be included in the link text. Other characters will be appended after
325 * the end of the link.
327 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
328 wfProfileIn( __METHOD__
);
330 if ( !$nt instanceof Title
) {
332 wfProfileOut( __METHOD__
);
333 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
336 if( $nt->getNamespace() == NS_SPECIAL
) {
338 } else if ( '' == $query ) {
341 $q = 'action=edit&'.$query;
343 $u = $nt->escapeLocalURL( $q );
346 $text = htmlspecialchars( $nt->getPrefixedText() );
348 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
350 list( $inside, $trail ) = Linker
::splitTrail( $trail );
351 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
353 wfProfileOut( __METHOD__
);
358 * Make a brown link to a short article.
360 * @param $title String: the text of the title
361 * @param $text String: link text
362 * @param $query String: optional query part
363 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
364 * be included in the link text. Other characters will be appended after
365 * the end of the link.
367 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
368 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
369 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
373 * Generate either a normal exists-style link or a stub link, depending
374 * on the given page size.
376 * @param $size Integer
377 * @param $nt Title object.
378 * @param $text String
379 * @param $query String
380 * @param $trail String
381 * @param $prefix String
382 * @return string HTML of link
384 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
386 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
387 if( $size < $threshold ) {
388 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
390 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
395 * Make appropriate markup for a link to the current article. This is currently rendered
396 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
397 * despite $query not being used.
399 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
401 $text = htmlspecialchars( $nt->getPrefixedText() );
403 list( $inside, $trail ) = Linker
::splitTrail( $trail );
404 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
407 /** @todo document */
408 function fnamePart( $url ) {
409 $basename = strrchr( $url, '/' );
410 if ( false === $basename ) {
413 $basename = substr( $basename, 1 );
415 return htmlspecialchars( $basename );
418 /** Obsolete alias */
419 function makeImage( $url, $alt = '' ) {
420 return $this->makeExternalImage( $url, $alt );
423 /** @todo document */
424 function makeExternalImage( $url, $alt = '' ) {
426 $alt = $this->fnamePart( $url );
428 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
433 * Creates the HTML source for images
434 * @deprecated use makeImageLink2
436 * @param object $title
437 * @param string $label label text
438 * @param string $alt alt text
439 * @param string $align horizontal alignment: none, left, center, right)
440 * @param array $handlerParams Parameters to be passed to the media handler
441 * @param boolean $framed shows image in original size in a frame
442 * @param boolean $thumb shows image as thumbnail in a frame
443 * @param string $manualthumb image name for the manual thumbnail
444 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
447 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
448 $thumb = false, $manualthumb = '', $valign = '', $time = false )
450 $frameParams = array( 'alt' => $alt, 'caption' => $label );
452 $frameParams['align'] = $align;
455 $frameParams['framed'] = true;
458 $frameParams['thumbnail'] = true;
460 if ( $manualthumb ) {
461 $frameParams['manualthumb'] = $manualthumb;
464 $frameParams['valign'] = $valign;
466 $file = wfFindFile( $title, $time );
467 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams );
472 * @param Title $title Title object
473 * @param File $file File object, or false if it doesn't exist
475 * @param array $frameParams Associative array of parameters external to the media handler.
476 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
477 * will often be false.
478 * thumbnail If present, downscale and frame
479 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
480 * framed Shows image in original size in a frame
481 * frameless Downscale but don't frame
482 * upright If present, tweak default sizes for portrait orientation
483 * upright_factor Fudge factor for "upright" tweak (default 0.75)
484 * border If present, show a border around the image
485 * align Horizontal alignment (left, right, center, none)
486 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
487 * bottom, text-bottom)
488 * alt Alternate text for image (i.e. alt attribute). Plain text.
489 * caption HTML for image caption.
491 * @param array $handlerParams Associative array of media handler parameters, to be passed
492 * to transform(). Typical keys are "width" and "page".
494 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
495 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
496 if ( $file && !$file->allowInlineDisplay() ) {
497 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
498 return $this->makeKnownLinkObj( $title );
503 $hp =& $handlerParams;
505 // Clean up parameters
506 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
507 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
508 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
510 $prefix = $postfix = '';
512 if ( 'center' == $fp['align'] )
514 $prefix = '<div class="center">';
516 $fp['align'] = 'none';
518 if ( $file && !isset( $hp['width'] ) ) {
519 $hp['width'] = $file->getWidth( $page );
521 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
522 $wopt = $wgUser->getOption( 'thumbsize' );
524 if( !isset( $wgThumbLimits[$wopt] ) ) {
525 $wopt = User
::getDefaultOption( 'thumbsize' );
528 // Reduce width for upright images when parameter 'upright' is used
529 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
530 $fp['upright'] = $wgThumbUpright;
532 // Use width which is smaller: real image width or user preference width
533 // 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
534 $prefWidth = isset( $fp['upright'] ) ?
535 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
536 $wgThumbLimits[$wopt];
537 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
538 $hp['width'] = $prefWidth;
543 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
545 # Create a thumbnail. Alignment depends on language
546 # writing direction, # right aligned for left-to-right-
547 # languages ("Western languages"), left-aligned
548 # for right-to-left-languages ("Semitic languages")
550 # If thumbnail width has not been provided, it is set
551 # to the default user option as specified in Language*.php
552 if ( $fp['align'] == '' ) {
553 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
555 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp ).$postfix;
558 if ( $file && $hp['width'] ) {
559 # Create a resized image, without the additional thumbnail features
560 $thumb = $file->transform( $hp );
566 $s = $this->makeBrokenImageLinkObj( $title );
568 $s = $thumb->toHtml( array(
571 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
572 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false ) );
574 if ( '' != $fp['align'] ) {
575 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
577 return str_replace("\n", ' ',$prefix.$s.$postfix);
581 * Make HTML for a thumbnail including image, border and caption
582 * @param Title $title
583 * @param File $file File object or false if it doesn't exist
585 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
586 $frameParams = array(
591 if ( $framed ) $frameParams['framed'] = true;
592 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
593 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
596 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
597 global $wgStylePath, $wgContLang;
598 $exists = $file && $file->exists();
602 $hp =& $handlerParams;
604 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
605 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
606 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
607 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
609 if ( empty( $hp['width'] ) ) {
610 // Reduce width for upright images when parameter 'upright' is used
611 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
616 $outerWidth = $hp['width'] +
2;
618 if ( isset( $fp['manualthumb'] ) ) {
619 # Use manually specified thumbnail
620 $manual_title = Title
::makeTitleSafe( NS_IMAGE
, $fp['manualthumb'] );
621 if( $manual_title ) {
622 $manual_img = wfFindFile( $manual_title );
624 $thumb = $manual_img->getUnscaledThumb();
629 } elseif ( isset( $fp['framed'] ) ) {
630 // Use image dimensions, don't scale
631 $thumb = $file->getUnscaledThumb( $page );
633 # Do not present an image bigger than the source, for bitmap-style images
634 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
635 $srcWidth = $file->getWidth( $page );
636 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
637 $hp['width'] = $srcWidth;
639 $thumb = $file->transform( $hp );
643 $outerWidth = $thumb->getWidth() +
2;
645 $outerWidth = $hp['width'] +
2;
649 $query = $page ?
'page=' . urlencode( $page ) : '';
650 $url = $title->getLocalURL( $query );
652 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
653 $magnifyalign = $wgContLang->isRTL() ?
'left' : 'right';
654 $textalign = $wgContLang->isRTL() ?
' style="text-align:right"' : '';
656 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
658 $s .= $this->makeBrokenImageLinkObj( $title );
660 } elseif ( !$thumb ) {
661 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
664 $s .= $thumb->toHtml( array(
666 'img-class' => 'thumbimage',
667 'desc-link' => true ) );
668 if ( isset( $fp['framed'] ) ) {
671 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
672 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
673 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
674 'width="15" height="11" alt="" /></a></div>';
677 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$fp['caption']."</div></div></div>";
678 return str_replace("\n", ' ', $s);
682 * Make a "broken" link to an image
684 * @param Title $title Image title
685 * @param string $text Link label
686 * @param string $query Query string
687 * @param string $trail Link trail
688 * @param string $prefix Link prefix
691 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
692 global $wgEnableUploads;
693 if( $title instanceof Title
) {
694 wfProfileIn( __METHOD__
);
695 if( $wgEnableUploads ) {
696 $upload = SpecialPage
::getTitleFor( 'Upload' );
698 $text = htmlspecialchars( $title->getPrefixedText() );
699 $q = 'wpDestFile=' . $title->getPartialUrl();
702 list( $inside, $trail ) = self
::splitTrail( $trail );
703 $style = $this->getInternalLinkAttributesObj( $title, $text, 'yes' );
704 wfProfileOut( __METHOD__
);
705 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
706 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
708 wfProfileOut( __METHOD__
);
709 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
712 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
716 /** @deprecated use Linker::makeMediaLinkObj() */
717 function makeMediaLink( $name, $unused = '', $text = '' ) {
718 $nt = Title
::makeTitleSafe( NS_IMAGE
, $name );
719 return $this->makeMediaLinkObj( $nt, $text );
723 * Create a direct link to a given uploaded file.
725 * @param $title Title object.
726 * @param $text String: pre-sanitized HTML
727 * @return string HTML
730 * @todo Handle invalid or missing images better.
732 function makeMediaLinkObj( $title, $text = '' ) {
733 if( is_null( $title ) ) {
734 ### HOTFIX. Instead of breaking, return empty string.
737 $img = wfFindFile( $title );
739 $url = $img->getURL();
742 $upload = SpecialPage
::getTitleFor( 'Upload' );
743 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDbKey() ) );
746 $alt = htmlspecialchars( $title->getText() );
750 $u = htmlspecialchars( $url );
751 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
755 /** @todo document */
756 function specialLink( $name, $key = '' ) {
759 if ( '' == $key ) { $key = strtolower( $name ); }
760 $pn = $wgContLang->ucfirst( $name );
761 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
765 /** @todo document */
766 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
767 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
768 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
769 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
770 $style .= ' rel="nofollow"';
772 $url = htmlspecialchars( $url );
774 $text = htmlspecialchars( $text );
776 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
780 * Make user link (or user contributions for unregistered users)
781 * @param $userId Integer: user id in database.
782 * @param $userText String: user name in database
783 * @return string HTML fragment
786 function userLink( $userId, $userText ) {
787 $encName = htmlspecialchars( $userText );
789 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
790 return $this->makeKnownLinkObj( $contribsPage,
793 $userPage = Title
::makeTitle( NS_USER
, $userText );
794 return $this->makeLinkObj( $userPage, $encName );
799 * Generate standard user tool links (talk, contributions, block link, etc.)
801 * @param int $userId User identifier
802 * @param string $userText User name or IP address
803 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
804 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
807 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
808 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
809 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
810 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
814 $items[] = $this->userTalkLink( $userId, $userText );
817 // check if the user has an edit
818 if( $redContribsWhenNoEdits && User
::edits( $userId ) == 0 ) {
819 $style = " class='new'";
823 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
825 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
827 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
828 $items[] = $this->blockLink( $userId, $userText );
832 return ' (' . implode( ' | ', $items ) . ')';
839 * Alias for userToolLinks( $userId, $userText, true );
841 public function userToolLinksRedContribs( $userId, $userText ) {
842 return $this->userToolLinks( $userId, $userText, true );
847 * @param $userId Integer: user id in database.
848 * @param $userText String: user name in database.
849 * @return string HTML fragment with user talk link
852 function userTalkLink( $userId, $userText ) {
853 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
854 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
855 return $userTalkLink;
859 * @param $userId Integer: userid
860 * @param $userText String: user name in database.
861 * @return string HTML fragment with block link
864 function blockLink( $userId, $userText ) {
865 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
866 $blockLink = $this->makeKnownLinkObj( $blockPage,
867 wfMsgHtml( 'blocklink' ) );
872 * Generate a user link if the current user is allowed to view it
873 * @param $rev Revision object.
874 * @return string HTML
876 function revUserLink( $rev ) {
877 if( $rev->userCan( Revision
::DELETED_USER
) ) {
878 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
880 $link = wfMsgHtml( 'rev-deleted-user' );
882 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
883 return '<span class="history-deleted">' . $link . '</span>';
889 * Generate a user tool link cluster if the current user is allowed to view it
890 * @param $rev Revision object.
891 * @return string HTML
893 function revUserTools( $rev ) {
894 if( $rev->userCan( Revision
::DELETED_USER
) ) {
895 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
897 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
899 $link = wfMsgHtml( 'rev-deleted-user' );
901 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
902 return '<span class="history-deleted">' . $link . '</span>';
908 * This function is called by all recent changes variants, by the page history,
909 * and by the user contributions list. It is responsible for formatting edit
910 * comments. It escapes any HTML in the comment, but adds some CSS to format
911 * auto-generated comments (from section editing) and formats [[wikilinks]].
913 * @author Erik Moeller <moeller@scireview.de>
915 * Note: there's not always a title to pass to this function.
916 * Since you can't set a default parameter for a reference, I've turned it
917 * temporarily to a value pass. Should be adjusted further. --brion
919 * @param string $comment
920 * @param mixed $title Title object (to generate link to the section in autocomment) or null
921 * @param bool $local Whether section links should refer to local page
923 function formatComment($comment, $title = NULL, $local = false) {
924 wfProfileIn( __METHOD__
);
926 # Sanitize text a bit:
927 $comment = str_replace( "\n", " ", $comment );
928 $comment = htmlspecialchars( $comment );
930 # Render autocomments and make links:
931 $comment = $this->formatAutoComments( $comment, $title, $local );
932 $comment = $this->formatLinksInComment( $comment );
934 wfProfileOut( __METHOD__
);
939 * The pattern for autogen comments is / * foo * /, which makes for
941 * We look for all comments, match any text before and after the comment,
942 * add a separator where needed and format the comment itself with CSS
943 * Called by Linker::formatComment.
945 * @param $comment Comment text
946 * @param $title An optional title object used to links to sections
948 * @todo Document the $local parameter.
950 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
952 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
960 # Generate a valid anchor name from the section title.
961 # Hackish, but should generally work - we strip wiki
962 # syntax, including the magic [[: that is used to
963 # "link rather than show" in case of images and
964 # interlanguage links.
965 $section = str_replace( '[[:', '', $section );
966 $section = str_replace( '[[', '', $section );
967 $section = str_replace( ']]', '', $section );
969 $sectionTitle = Title
::newFromText( '#' . $section);
971 $sectionTitle = wfClone( $title );
972 $sectionTitle->mFragment
= $section;
974 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
978 if($pre) { $auto = $sep.' '.$auto; }
979 if($post) { $auto .= ' '.$sep; }
980 $auto='<span class="autocomment">'.$auto.'</span>';
981 $comment=$pre.$auto.$post;
988 * Formats wiki links and media links in text; all other wiki formatting
991 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
992 * @param string $comment Text to format links in
995 public function formatLinksInComment( $comment ) {
996 return preg_replace_callback(
997 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
998 array( $this, 'formatLinksInCommentCallback' ),
1002 protected function formatLinksInCommentCallback( $match ) {
1005 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1006 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1008 $comment = $match[0];
1010 # Handle link renaming [[foo|text]] will show link as "text"
1011 if( "" != $match[3] ) {
1016 $submatch = array();
1017 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1018 # Media link; trail not supported.
1019 $linkRegexp = '/\[\[(.*?)\]\]/';
1020 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1022 # Other kind of link
1023 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1024 $trail = $submatch[1];
1028 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1029 if (isset($match[1][0]) && $match[1][0] == ':')
1030 $match[1] = substr($match[1], 1);
1031 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1033 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1039 * Wrap a comment in standard punctuation and formatting if
1040 * it's non-empty, otherwise return empty string.
1042 * @param string $comment
1043 * @param mixed $title Title object (to generate link to section in autocomment) or null
1044 * @param bool $local Whether section links should refer to local page
1048 function commentBlock( $comment, $title = NULL, $local = false ) {
1049 // '*' used to be the comment inserted by the software way back
1050 // in antiquity in case none was provided, here for backwards
1051 // compatability, acc. to brion -ævar
1052 if( $comment == '' ||
$comment == '*' ) {
1055 $formatted = $this->formatComment( $comment, $title, $local );
1056 return " <span class=\"comment\">($formatted)</span>";
1061 * Wrap and format the given revision's comment block, if the current
1062 * user is allowed to view it.
1064 * @param Revision $rev
1065 * @param bool $local Whether section links should refer to local page
1066 * @return string HTML
1068 function revComment( Revision
$rev, $local = false ) {
1069 if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1070 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1072 $block = " <span class=\"comment\">" .
1073 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1075 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1076 return " <span class=\"history-deleted\">$block</span>";
1081 /** @todo document */
1082 function tocIndent() {
1086 /** @todo document */
1087 function tocUnindent($level) {
1088 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1092 * parameter level defines if we are on an indentation level
1094 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1095 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1096 $anchor . '"><span class="tocnumber">' .
1097 $tocnumber . '</span> <span class="toctext">' .
1098 $tocline . '</span></a>';
1101 /** @todo document */
1102 function tocLineEnd() {
1106 /** @todo document */
1107 function tocList($toc) {
1108 global $wgJsMimeType;
1109 $title = wfMsgHtml('toc') ;
1111 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1112 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1114 # no trailing newline, script should not be wrapped in a
1116 . "</ul>\n</td></tr></table>"
1117 . '<script type="' . $wgJsMimeType . '">'
1118 . ' if (window.showTocToggle) {'
1119 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1120 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1121 . ' showTocToggle();'
1127 * Used to generate section edit links that point to "other" pages
1128 * (sections that are really part of included pages).
1130 * @param $title Title string.
1131 * @param $section Integer: section number.
1133 public function editSectionLinkForOther( $title, $section ) {
1134 $title = Title
::newFromText( $title );
1135 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1139 * @param $nt Title object.
1140 * @param $section Integer: section number.
1141 * @param $hint Link String: title, or default if omitted or empty
1143 public function editSectionLink( Title
$nt, $section, $hint='' ) {
1145 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1146 $hint = " title=\"$hint\"";
1148 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1152 * Implement editSectionLink and editSectionLinkForOther.
1154 * @param $nt Title object
1155 * @param $section Integer, section number
1156 * @param $hint String, for HTML title attribute
1157 * @param $hook String, name of hook to run
1158 * @return String, HTML to use for edit link
1160 protected function doEditSectionLink( Title
$nt, $section, $hint, $hook ) {
1162 $editurl = '§ion='.$section;
1163 $url = $this->makeKnownLinkObj(
1165 wfMsg('editsection'),
1166 'action=edit'.$editurl,
1171 // The two hooks have slightly different interfaces . . .
1172 if( $hook == 'EditSectionLink' ) {
1173 wfRunHooks( $hook, array( &$this, $nt, $section, $hint, $url, &$result ) );
1174 } elseif( $hook == 'EditSectionLinkForOther' ) {
1175 wfRunHooks( $hook, array( &$this, $nt, $section, $url, &$result ) );
1178 // For reverse compatibility, add the brackets *after* the hook is run,
1179 // and even add them to hook-provided text.
1180 if( is_null( $result ) ) {
1181 $result = wfMsg( 'editsection-brackets', $url );
1183 $result = wfMsg( 'editsection-brackets', $result );
1185 return "<span class=\"editsection\">$result</span>";
1189 * Create a headline for content
1191 * @param int $level The level of the headline (1-6)
1192 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1193 * This *must* be at least '>' for no attribs
1194 * @param string $anchor The anchor to give the headline (the bit after the #)
1195 * @param string $text The text of the header
1196 * @param string $link HTML to add for the section edit link
1198 * @return string HTML headline
1200 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1201 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1205 * Split a link trail, return the "inside" portion and the remainder of the trail
1206 * as a two-element array
1210 static function splitTrail( $trail ) {
1211 static $regex = false;
1212 if ( $regex === false ) {
1214 $regex = $wgContLang->linkTrail();
1217 if ( '' != $trail ) {
1219 if ( preg_match( $regex, $trail, $m ) ) {
1224 return array( $inside, $trail );
1228 * Generate a rollback link for a given revision. Currently it's the
1229 * caller's responsibility to ensure that the revision is the top one. If
1230 * it's not, of course, the user will get an error message.
1232 * If the calling page is called with the parameter &bot=1, all rollback
1233 * links also get that parameter. It causes the edit itself and the rollback
1234 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1235 * changes, so this allows sysops to combat a busy vandal without bothering
1238 * @param Revision $rev
1240 function generateRollback( $rev ) {
1241 return '<span class="mw-rollback-link">['
1242 . $this->buildRollbackLink( $rev )
1247 * Build a raw rollback link, useful for collections of "tool" links
1249 * @param Revision $rev
1252 public function buildRollbackLink( $rev ) {
1253 global $wgRequest, $wgUser;
1254 $title = $rev->getTitle();
1255 $extra = $wgRequest->getBool( 'bot' ) ?
'&bot=1' : '';
1256 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1257 $rev->getUserText() ) ) );
1258 return $this->makeKnownLinkObj(
1260 wfMsgHtml( 'rollbacklink' ),
1261 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1266 * Returns HTML for the "templates used on this page" list.
1268 * @param array $templates Array of templates from Article::getUsedTemplate
1270 * @param bool $preview Whether this is for a preview
1271 * @param bool $section Whether this is for a section edit
1272 * @return string HTML output
1274 public function formatTemplates( $templates, $preview = false, $section = false) {
1276 wfProfileIn( __METHOD__
);
1278 $sk = $wgUser->getSkin();
1281 if ( count( $templates ) > 0 ) {
1282 # Do a batch existence check
1283 $batch = new LinkBatch
;
1284 foreach( $templates as $title ) {
1285 $batch->addObj( $title );
1289 # Construct the HTML
1290 $outText = '<div class="mw-templatesUsedExplanation">';
1292 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1293 } elseif ( $section ) {
1294 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1296 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1298 $outText .= '</div><ul>';
1300 foreach ( $templates as $titleObj ) {
1301 $r = $titleObj->getRestrictions( 'edit' );
1302 if ( in_array( 'sysop', $r ) ) {
1303 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1304 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1305 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1309 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1311 $outText .= '</ul>';
1313 wfProfileOut( __METHOD__
);
1318 * Format a size in bytes for output, using an appropriate
1319 * unit (B, KB, MB or GB) according to the magnitude in question
1321 * @param $size Size to format
1324 public function formatSize( $size ) {
1326 return htmlspecialchars( $wgLang->formatSize( $size ) );
1330 * Given the id of an interface element, constructs the appropriate title
1331 * and accesskey attributes from the system messages. (Note, this is usu-
1332 * ally the id but isn't always, because sometimes the accesskey needs to
1333 * go on a different element than the id, for reverse-compatibility, etc.)
1335 * @param string $name Id of the element, minus prefixes.
1336 * @return string title and accesskey attributes, ready to drop in an
1337 * element (e.g., ' title="This does something [x]" accesskey="x"').
1339 public function tooltipAndAccesskey($name) {
1342 $tooltip = wfMsg('tooltip-'.$name);
1343 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1344 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1345 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1346 $out .= ' title="'.htmlspecialchars($tooltip);
1348 $accesskey = wfMsg('accesskey-'.$name);
1349 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1350 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1351 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1359 * Given the id of an interface element, constructs the appropriate title
1360 * attribute from the system messages. (Note, this is usually the id but
1361 * isn't always, because sometimes the accesskey needs to go on a different
1362 * element than the id, for reverse-compatibility, etc.)
1364 * @param string $name Id of the element, minus prefixes.
1365 * @return string title attribute, ready to drop in an element
1366 * (e.g., ' title="This does something"').
1368 public function tooltip($name) {
1371 $tooltip = wfMsg('tooltip-'.$name);
1372 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1373 $out = ' title="'.htmlspecialchars($tooltip).'"';