11dee27a8855a9d462966cd98513939948cb4f9d
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 = '', $title = false ) {
70 $r = ($class != '') ?
' class="' . htmlspecialchars( $class ) . '"' : '';
71 if ( $title === false ) {
72 $r .= ' title="' . $nt->getEscapedText() . '"';
74 $r .= ' title="' . htmlspecialchars( $title ) . '"';
80 * Return the CSS colour of a known link
83 * @param integer $threshold user defined threshold
84 * @return string CSS class
86 function getLinkColour( $s, $threshold ) {
92 if ( !empty( $s->page_is_redirect
) ) {
94 $colour = 'mw-redirect';
95 } elseif ( $threshold > 0 && $s->page_len
< $threshold && Namespace::isContent( $s->page_namespace
) ) {
103 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
104 * it if you already have a title object handy. See makeLinkObj for further documentation.
106 * @param $title String: the text of the title
107 * @param $text String: link text
108 * @param $query String: optional query part
109 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
110 * be included in the link text. Other characters will be appended after
111 * the end of the link.
113 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
114 wfProfileIn( __METHOD__
);
115 $nt = Title
::newFromText( $title );
116 if ( $nt instanceof Title
) {
117 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
119 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
120 $result = $text == "" ?
$title : $text;
123 wfProfileOut( __METHOD__
);
128 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
129 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
131 * @param $title String: the text of the title
132 * @param $text String: link text
133 * @param $query String: optional query part
134 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
135 * be included in the link text. Other characters will be appended after
136 * the end of the link.
138 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
139 $nt = Title
::newFromText( $title );
140 if ( $nt instanceof Title
) {
141 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
143 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
144 return $text == '' ?
$title : $text;
149 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
150 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
152 * @param string $title The text of the title
153 * @param string $text Link text
154 * @param string $query Optional query part
155 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
156 * be included in the link text. Other characters will be appended after
157 * the end of the link.
159 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
160 $nt = Title
::newFromText( $title );
161 if ( $nt instanceof Title
) {
162 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
164 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
165 return $text == '' ?
$title : $text;
170 * @deprecated use makeColouredLinkObj
172 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
173 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
175 * @param $title String: the text of the title
176 * @param $text String: link text
177 * @param $query String: optional query part
178 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
179 * be included in the link text. Other characters will be appended after
180 * the end of the link.
182 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
183 $nt = Title
::newFromText( $title );
184 if ( $nt instanceof Title
) {
185 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
187 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
188 return $text == '' ?
$title : $text;
193 * Make a link for a title which may or may not be in the database. If you need to
194 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
195 * call to this will result in a DB query.
197 * @param $nt Title: the title object to make the link from, e.g. from
198 * Title::newFromText.
199 * @param $text String: link text
200 * @param $query String: optional query part
201 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
202 * be included in the link text. Other characters will be appended after
203 * the end of the link.
204 * @param $prefix String: optional prefix. As trail, only before instead of after.
206 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
208 wfProfileIn( __METHOD__
);
210 if ( !$nt instanceof Title
) {
212 wfProfileOut( __METHOD__
);
213 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
216 if ( $nt->isExternal() ) {
217 $u = $nt->getFullURL();
218 $link = $nt->getPrefixedURL();
219 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
220 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
223 if ( '' != $trail ) {
225 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
230 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
232 wfProfileOut( __METHOD__
);
234 } elseif ( $nt->isAlwaysKnown() ) {
235 # Image links, special page links and self-links with fragements are always known.
236 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
238 wfProfileIn( __METHOD__
.'-immediate' );
240 # Handles links to special pages which do not exist in the database:
241 if( $nt->getNamespace() == NS_SPECIAL
) {
242 if( SpecialPage
::exists( $nt->getDBkey() ) ) {
243 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
245 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
247 wfProfileOut( __METHOD__
.'-immediate' );
248 wfProfileOut( __METHOD__
);
252 # Work out link colour immediately
253 $aid = $nt->getArticleID() ;
255 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
258 if ( $nt->isContentPage() ) {
259 # FIXME: This is stupid, we should combine this query with
260 # the Title::getArticleID() query above.
261 $threshold = $wgUser->getOption('stubthreshold');
262 $dbr = wfGetDB( DB_SLAVE
);
263 $s = $dbr->selectRow(
265 array( 'page_len', 'page_is_redirect', 'page_namespace' ),
266 array( 'page_id' => $aid ), __METHOD__
) ;
267 $colour = $this->getLinkColour( $s, $threshold );
269 $retVal = $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
271 wfProfileOut( __METHOD__
.'-immediate' );
273 wfProfileOut( __METHOD__
);
278 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
279 * it doesn't have to do a database query. It's also valid for interwiki titles and special
282 * @param $nt Title object of target page
283 * @param $text String: text to replace the title
284 * @param $query String: link target
285 * @param $trail String: text after link
286 * @param $prefix String: text before link text
287 * @param $aprops String: extra attributes to the a-element
288 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
289 * @return the a-element
291 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
292 wfProfileIn( __METHOD__
);
294 if ( !$nt instanceof Title
) {
296 wfProfileOut( __METHOD__
);
297 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
300 $u = $nt->escapeLocalURL( $query );
301 if ( $nt->getFragment() != '' ) {
302 if( $nt->getPrefixedDbkey() == '' ) {
305 $text = htmlspecialchars( $nt->getFragment() );
308 $u .= $nt->getFragmentForURL();
311 $text = htmlspecialchars( $nt->getPrefixedText() );
313 if ( $style == '' ) {
314 $style = $this->getInternalLinkAttributesObj( $nt, $text );
317 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
319 list( $inside, $trail ) = Linker
::splitTrail( $trail );
320 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
321 wfProfileOut( __METHOD__
);
326 * Make a red link to the edit page of a given title.
328 * @param $nt Title object of the target page
329 * @param $text String: Link text
330 * @param $query String: Optional query part
331 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
332 * be included in the link text. Other characters will be appended after
333 * the end of the link.
335 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
336 wfProfileIn( __METHOD__
);
338 if ( !$nt instanceof Title
) {
340 wfProfileOut( __METHOD__
);
341 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
344 if( $nt->getNamespace() == NS_SPECIAL
) {
346 } else if ( '' == $query ) {
347 $q = 'action=editredlink';
349 $q = 'action=editredlink&'.$query;
351 $u = $nt->escapeLocalURL( $q );
354 $text = htmlspecialchars( $nt->getPrefixedText() );
356 $title = wfMsg( 'red-link-title', $nt->getText() );
357 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'new', $title );
359 list( $inside, $trail ) = Linker
::splitTrail( $trail );
360 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
362 wfProfileOut( __METHOD__
);
367 * @deprecated use makeColouredLinkObj
369 * Make a brown link to a short article.
371 * @param $nt Title object of the target page
372 * @param $text String: link text
373 * @param $query String: optional query part
374 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
375 * be included in the link text. Other characters will be appended after
376 * the end of the link.
378 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
379 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
383 * Make a coloured link.
385 * @param $nt Title object of the target page
386 * @param $colour Integer: colour of the link
387 * @param $text String: link text
388 * @param $query String: optional query part
389 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
390 * be included in the link text. Other characters will be appended after
391 * the end of the link.
393 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
396 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
398 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
402 * Generate either a normal exists-style link or a stub link, depending
403 * on the given page size.
405 * @param $size Integer
406 * @param $nt Title object.
407 * @param $text String
408 * @param $query String
409 * @param $trail String
410 * @param $prefix String
411 * @return string HTML of link
413 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
415 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
416 $colour = ( $size < $threshold ) ?
'stub' : '';
417 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
421 * Make appropriate markup for a link to the current article. This is currently rendered
422 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
423 * despite $query not being used.
425 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
427 $text = htmlspecialchars( $nt->getPrefixedText() );
429 list( $inside, $trail ) = Linker
::splitTrail( $trail );
430 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
433 /** @todo document */
434 function fnamePart( $url ) {
435 $basename = strrchr( $url, '/' );
436 if ( false === $basename ) {
439 $basename = substr( $basename, 1 );
441 return htmlspecialchars( $basename );
444 /** Obsolete alias */
445 function makeImage( $url, $alt = '' ) {
446 return $this->makeExternalImage( $url, $alt );
449 /** @todo document */
450 function makeExternalImage( $url, $alt = '' ) {
452 $alt = $this->fnamePart( $url );
454 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
459 * Creates the HTML source for images
460 * @deprecated use makeImageLink2
462 * @param object $title
463 * @param string $label label text
464 * @param string $alt alt text
465 * @param string $align horizontal alignment: none, left, center, right)
466 * @param array $handlerParams Parameters to be passed to the media handler
467 * @param boolean $framed shows image in original size in a frame
468 * @param boolean $thumb shows image as thumbnail in a frame
469 * @param string $manualthumb image name for the manual thumbnail
470 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
471 * @param string $time, timestamp of the file, set as false for current
474 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
475 $thumb = false, $manualthumb = '', $valign = '', $time = false )
477 $frameParams = array( 'alt' => $alt, 'caption' => $label );
479 $frameParams['align'] = $align;
482 $frameParams['framed'] = true;
485 $frameParams['thumbnail'] = true;
487 if ( $manualthumb ) {
488 $frameParams['manualthumb'] = $manualthumb;
491 $frameParams['valign'] = $valign;
493 $file = wfFindFile( $title, $time );
494 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
499 * @param Title $title Title object
500 * @param File $file File object, or false if it doesn't exist
502 * @param array $frameParams Associative array of parameters external to the media handler.
503 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
504 * will often be false.
505 * thumbnail If present, downscale and frame
506 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
507 * framed Shows image in original size in a frame
508 * frameless Downscale but don't frame
509 * upright If present, tweak default sizes for portrait orientation
510 * upright_factor Fudge factor for "upright" tweak (default 0.75)
511 * border If present, show a border around the image
512 * align Horizontal alignment (left, right, center, none)
513 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
514 * bottom, text-bottom)
515 * alt Alternate text for image (i.e. alt attribute). Plain text.
516 * caption HTML for image caption.
518 * @param array $handlerParams Associative array of media handler parameters, to be passed
519 * to transform(). Typical keys are "width" and "page".
520 * @param string $time, timestamp of the file, set as false for current
522 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false ) {
523 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
524 if ( $file && !$file->allowInlineDisplay() ) {
525 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
526 return $this->makeKnownLinkObj( $title );
531 $hp =& $handlerParams;
533 // Clean up parameters
534 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
535 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
536 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
538 $prefix = $postfix = '';
540 if ( 'center' == $fp['align'] )
542 $prefix = '<div class="center">';
544 $fp['align'] = 'none';
546 if ( $file && !isset( $hp['width'] ) ) {
547 $hp['width'] = $file->getWidth( $page );
549 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
550 $wopt = $wgUser->getOption( 'thumbsize' );
552 if( !isset( $wgThumbLimits[$wopt] ) ) {
553 $wopt = User
::getDefaultOption( 'thumbsize' );
556 // Reduce width for upright images when parameter 'upright' is used
557 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
558 $fp['upright'] = $wgThumbUpright;
560 // Use width which is smaller: real image width or user preference width
561 // 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
562 $prefWidth = isset( $fp['upright'] ) ?
563 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
564 $wgThumbLimits[$wopt];
565 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
566 $hp['width'] = $prefWidth;
571 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
573 # Create a thumbnail. Alignment depends on language
574 # writing direction, # right aligned for left-to-right-
575 # languages ("Western languages"), left-aligned
576 # for right-to-left-languages ("Semitic languages")
578 # If thumbnail width has not been provided, it is set
579 # to the default user option as specified in Language*.php
580 if ( $fp['align'] == '' ) {
581 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
583 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time ).$postfix;
586 if ( $file && isset( $fp['frameless'] ) ) {
587 $srcWidth = $file->getWidth( $page );
588 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
589 # This is the same behaviour as the "thumb" option does it already.
590 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
591 $hp['width'] = $srcWidth;
595 if ( $file && $hp['width'] ) {
596 # Create a resized image, without the additional thumbnail features
597 $thumb = $file->transform( $hp );
603 $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
605 $s = $thumb->toHtml( array(
608 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
609 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false ) );
611 if ( '' != $fp['align'] ) {
612 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
614 return str_replace("\n", ' ',$prefix.$s.$postfix);
618 * Make HTML for a thumbnail including image, border and caption
619 * @param Title $title
620 * @param File $file File object or false if it doesn't exist
622 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
623 $frameParams = array(
628 if ( $framed ) $frameParams['framed'] = true;
629 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
630 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
633 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false ) {
634 global $wgStylePath, $wgContLang;
635 $exists = $file && $file->exists();
639 $hp =& $handlerParams;
641 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
642 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
643 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
644 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
646 if ( empty( $hp['width'] ) ) {
647 // Reduce width for upright images when parameter 'upright' is used
648 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
653 $outerWidth = $hp['width'] +
2;
655 if ( isset( $fp['manualthumb'] ) ) {
656 # Use manually specified thumbnail
657 $manual_title = Title
::makeTitleSafe( NS_IMAGE
, $fp['manualthumb'] );
658 if( $manual_title ) {
659 $manual_img = wfFindFile( $manual_title );
661 $thumb = $manual_img->getUnscaledThumb();
666 } elseif ( isset( $fp['framed'] ) ) {
667 // Use image dimensions, don't scale
668 $thumb = $file->getUnscaledThumb( $page );
670 # Do not present an image bigger than the source, for bitmap-style images
671 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
672 $srcWidth = $file->getWidth( $page );
673 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
674 $hp['width'] = $srcWidth;
676 $thumb = $file->transform( $hp );
680 $outerWidth = $thumb->getWidth() +
2;
682 $outerWidth = $hp['width'] +
2;
686 $query = $page ?
'page=' . urlencode( $page ) : '';
687 $url = $title->getLocalURL( $query );
689 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
691 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
693 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
695 } elseif ( !$thumb ) {
696 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
699 $s .= $thumb->toHtml( array(
701 'img-class' => 'thumbimage',
702 'desc-link' => true ) );
703 if ( isset( $fp['framed'] ) ) {
706 $zoomicon = '<div class="magnify">'.
707 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
708 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
709 'width="15" height="11" alt="" /></a></div>';
712 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
713 return str_replace("\n", ' ', $s);
717 * Make a "broken" link to an image
719 * @param Title $title Image title
720 * @param string $text Link label
721 * @param string $query Query string
722 * @param string $trail Link trail
723 * @param string $prefix Link prefix
724 * @param bool $time, a file of a certain timestamp was requested
727 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
728 global $wgEnableUploads;
729 if( $title instanceof Title
) {
730 wfProfileIn( __METHOD__
);
731 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
732 if( $wgEnableUploads && !$currentExists ) {
733 $upload = SpecialPage
::getTitleFor( 'Upload' );
735 $text = htmlspecialchars( $title->getPrefixedText() );
736 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
738 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
740 $q = 'wpDestFile=' . $title->getPartialUrl();
743 list( $inside, $trail ) = self
::splitTrail( $trail );
744 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
745 wfProfileOut( __METHOD__
);
746 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
747 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
749 wfProfileOut( __METHOD__
);
750 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
753 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
757 /** @deprecated use Linker::makeMediaLinkObj() */
758 function makeMediaLink( $name, $unused = '', $text = '' ) {
759 $nt = Title
::makeTitleSafe( NS_IMAGE
, $name );
760 return $this->makeMediaLinkObj( $nt, $text );
764 * Create a direct link to a given uploaded file.
766 * @param $title Title object.
767 * @param $text String: pre-sanitized HTML
768 * @return string HTML
771 * @todo Handle invalid or missing images better.
773 function makeMediaLinkObj( $title, $text = '' ) {
774 if( is_null( $title ) ) {
775 ### HOTFIX. Instead of breaking, return empty string.
778 $img = wfFindFile( $title );
780 $url = $img->getURL();
783 $upload = SpecialPage
::getTitleFor( 'Upload' );
784 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
787 $alt = htmlspecialchars( $title->getText() );
791 $u = htmlspecialchars( $url );
792 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
796 /** @todo document */
797 function specialLink( $name, $key = '' ) {
800 if ( '' == $key ) { $key = strtolower( $name ); }
801 $pn = $wgContLang->ucfirst( $name );
802 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
806 /** @todo document */
807 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
808 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
809 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
810 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
811 $style .= ' rel="nofollow"';
813 $url = htmlspecialchars( $url );
815 $text = htmlspecialchars( $text );
817 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
821 * Make user link (or user contributions for unregistered users)
822 * @param $userId Integer: user id in database.
823 * @param $userText String: user name in database
824 * @return string HTML fragment
827 function userLink( $userId, $userText ) {
828 $encName = htmlspecialchars( $userText );
830 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
831 return $this->makeKnownLinkObj( $contribsPage,
834 $userPage = Title
::makeTitle( NS_USER
, $userText );
835 return $this->makeLinkObj( $userPage, $encName );
840 * Generate standard user tool links (talk, contributions, block link, etc.)
842 * @param int $userId User identifier
843 * @param string $userText User name or IP address
844 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
845 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
848 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
849 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
850 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
851 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
855 $items[] = $this->userTalkLink( $userId, $userText );
858 // check if the user has an edit
859 if( $redContribsWhenNoEdits && User
::edits( $userId ) == 0 ) {
860 $style = " class='new'";
864 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
866 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
868 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
869 $items[] = $this->blockLink( $userId, $userText );
873 return ' (' . implode( ' | ', $items ) . ')';
880 * Alias for userToolLinks( $userId, $userText, true );
882 public function userToolLinksRedContribs( $userId, $userText ) {
883 return $this->userToolLinks( $userId, $userText, true );
888 * @param $userId Integer: user id in database.
889 * @param $userText String: user name in database.
890 * @return string HTML fragment with user talk link
893 function userTalkLink( $userId, $userText ) {
894 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
895 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
896 return $userTalkLink;
900 * @param $userId Integer: userid
901 * @param $userText String: user name in database.
902 * @return string HTML fragment with block link
905 function blockLink( $userId, $userText ) {
906 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
907 $blockLink = $this->makeKnownLinkObj( $blockPage,
908 wfMsgHtml( 'blocklink' ) );
913 * Generate a user link if the current user is allowed to view it
914 * @param $rev Revision object.
915 * @return string HTML
917 function revUserLink( $rev ) {
918 if( $rev->userCan( Revision
::DELETED_USER
) ) {
919 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
921 $link = wfMsgHtml( 'rev-deleted-user' );
923 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
924 return '<span class="history-deleted">' . $link . '</span>';
930 * Generate a user tool link cluster if the current user is allowed to view it
931 * @param $rev Revision object.
932 * @return string HTML
934 function revUserTools( $rev ) {
935 if( $rev->userCan( Revision
::DELETED_USER
) ) {
936 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
938 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
940 $link = wfMsgHtml( 'rev-deleted-user' );
942 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
943 return '<span class="history-deleted">' . $link . '</span>';
949 * This function is called by all recent changes variants, by the page history,
950 * and by the user contributions list. It is responsible for formatting edit
951 * comments. It escapes any HTML in the comment, but adds some CSS to format
952 * auto-generated comments (from section editing) and formats [[wikilinks]].
954 * @author Erik Moeller <moeller@scireview.de>
956 * Note: there's not always a title to pass to this function.
957 * Since you can't set a default parameter for a reference, I've turned it
958 * temporarily to a value pass. Should be adjusted further. --brion
960 * @param string $comment
961 * @param mixed $title Title object (to generate link to the section in autocomment) or null
962 * @param bool $local Whether section links should refer to local page
964 function formatComment($comment, $title = NULL, $local = false) {
965 wfProfileIn( __METHOD__
);
967 # Sanitize text a bit:
968 $comment = str_replace( "\n", " ", $comment );
969 $comment = htmlspecialchars( $comment );
971 # Render autocomments and make links:
972 $comment = $this->formatAutoComments( $comment, $title, $local );
973 $comment = $this->formatLinksInComment( $comment );
975 wfProfileOut( __METHOD__
);
980 * The pattern for autogen comments is / * foo * /, which makes for
982 * We look for all comments, match any text before and after the comment,
983 * add a separator where needed and format the comment itself with CSS
984 * Called by Linker::formatComment.
986 * @param string $comment Comment text
987 * @param object $title An optional title object used to links to sections
988 * @return string $comment formatted comment
990 * @todo Document the $local parameter.
992 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
994 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
1002 # Generate a valid anchor name from the section title.
1003 # Hackish, but should generally work - we strip wiki
1004 # syntax, including the magic [[: that is used to
1005 # "link rather than show" in case of images and
1006 # interlanguage links.
1007 $section = str_replace( '[[:', '', $section );
1008 $section = str_replace( '[[', '', $section );
1009 $section = str_replace( ']]', '', $section );
1011 $sectionTitle = Title
::newFromText( '#' . $section);
1013 $sectionTitle = wfClone( $title );
1014 $sectionTitle->mFragment
= $section;
1016 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsgForContent( 'sectionlink' ) );
1018 $auto = $link . $auto;
1020 $auto = '- ' . $auto; # written summary $presep autocomment (summary /* section */)
1023 $auto .= ': '; # autocomment $postsep written summary (/* section */ summary)
1025 $auto = '<span class="autocomment">' . $auto . '</span>';
1026 $comment = $pre . $auto . $post;
1033 * Formats wiki links and media links in text; all other wiki formatting
1036 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1037 * @param string $comment Text to format links in
1040 public function formatLinksInComment( $comment ) {
1041 return preg_replace_callback(
1042 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1043 array( $this, 'formatLinksInCommentCallback' ),
1047 protected function formatLinksInCommentCallback( $match ) {
1050 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1051 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1053 $comment = $match[0];
1055 # Handle link renaming [[foo|text]] will show link as "text"
1056 if( "" != $match[3] ) {
1061 $submatch = array();
1062 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1063 # Media link; trail not supported.
1064 $linkRegexp = '/\[\[(.*?)\]\]/';
1065 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1067 # Other kind of link
1068 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1069 $trail = $submatch[1];
1073 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1074 if (isset($match[1][0]) && $match[1][0] == ':')
1075 $match[1] = substr($match[1], 1);
1076 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1078 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1084 * Wrap a comment in standard punctuation and formatting if
1085 * it's non-empty, otherwise return empty string.
1087 * @param string $comment
1088 * @param mixed $title Title object (to generate link to section in autocomment) or null
1089 * @param bool $local Whether section links should refer to local page
1093 function commentBlock( $comment, $title = NULL, $local = false ) {
1094 // '*' used to be the comment inserted by the software way back
1095 // in antiquity in case none was provided, here for backwards
1096 // compatability, acc. to brion -ævar
1097 if( $comment == '' ||
$comment == '*' ) {
1100 $formatted = $this->formatComment( $comment, $title, $local );
1101 return " <span class=\"comment\">($formatted)</span>";
1106 * Wrap and format the given revision's comment block, if the current
1107 * user is allowed to view it.
1109 * @param Revision $rev
1110 * @param bool $local Whether section links should refer to local page
1111 * @return string HTML
1113 function revComment( Revision
$rev, $local = false ) {
1114 if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1115 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1117 $block = " <span class=\"comment\">" .
1118 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1120 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1121 return " <span class=\"history-deleted\">$block</span>";
1126 /** @todo document */
1127 function tocIndent() {
1131 /** @todo document */
1132 function tocUnindent($level) {
1133 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1137 * parameter level defines if we are on an indentation level
1139 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1140 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1141 $anchor . '"><span class="tocnumber">' .
1142 $tocnumber . '</span> <span class="toctext">' .
1143 $tocline . '</span></a>';
1146 /** @todo document */
1147 function tocLineEnd() {
1151 /** @todo document */
1152 function tocList($toc) {
1153 global $wgJsMimeType;
1154 $title = wfMsgHtml('toc') ;
1156 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1157 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1159 # no trailing newline, script should not be wrapped in a
1161 . "</ul>\n</td></tr></table>"
1162 . '<script type="' . $wgJsMimeType . '">'
1163 . ' if (window.showTocToggle) {'
1164 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1165 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1166 . ' showTocToggle();'
1172 * Used to generate section edit links that point to "other" pages
1173 * (sections that are really part of included pages).
1175 * @param $title Title string.
1176 * @param $section Integer: section number.
1178 public function editSectionLinkForOther( $title, $section ) {
1179 $title = Title
::newFromText( $title );
1180 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1184 * @param $nt Title object.
1185 * @param $section Integer: section number.
1186 * @param $hint Link String: title, or default if omitted or empty
1188 public function editSectionLink( Title
$nt, $section, $hint='' ) {
1190 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1191 $hint = " title=\"$hint\"";
1193 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1197 * Implement editSectionLink and editSectionLinkForOther.
1199 * @param $nt Title object
1200 * @param $section Integer, section number
1201 * @param $hint String, for HTML title attribute
1202 * @param $hook String, name of hook to run
1203 * @return String, HTML to use for edit link
1205 protected function doEditSectionLink( Title
$nt, $section, $hint, $hook ) {
1207 $editurl = '§ion='.$section;
1208 $url = $this->makeKnownLinkObj(
1210 wfMsg('editsection'),
1211 'action=edit'.$editurl,
1216 // The two hooks have slightly different interfaces . . .
1217 if( $hook == 'EditSectionLink' ) {
1218 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $hint, $url, &$result ) );
1219 } elseif( $hook == 'EditSectionLinkForOther' ) {
1220 wfRunHooks( 'EditSectionLinkForOther', array( &$this, $nt, $section, $url, &$result ) );
1223 // For reverse compatibility, add the brackets *after* the hook is run,
1224 // and even add them to hook-provided text.
1225 if( is_null( $result ) ) {
1226 $result = wfMsg( 'editsection-brackets', $url );
1228 $result = wfMsg( 'editsection-brackets', $result );
1230 return "<span class=\"editsection\">$result</span>";
1234 * Create a headline for content
1236 * @param int $level The level of the headline (1-6)
1237 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1238 * This *must* be at least '>' for no attribs
1239 * @param string $anchor The anchor to give the headline (the bit after the #)
1240 * @param string $text The text of the header
1241 * @param string $link HTML to add for the section edit link
1243 * @return string HTML headline
1245 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1246 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1250 * Split a link trail, return the "inside" portion and the remainder of the trail
1251 * as a two-element array
1255 static function splitTrail( $trail ) {
1256 static $regex = false;
1257 if ( $regex === false ) {
1259 $regex = $wgContLang->linkTrail();
1262 if ( '' != $trail ) {
1264 if ( preg_match( $regex, $trail, $m ) ) {
1269 return array( $inside, $trail );
1273 * Generate a rollback link for a given revision. Currently it's the
1274 * caller's responsibility to ensure that the revision is the top one. If
1275 * it's not, of course, the user will get an error message.
1277 * If the calling page is called with the parameter &bot=1, all rollback
1278 * links also get that parameter. It causes the edit itself and the rollback
1279 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1280 * changes, so this allows sysops to combat a busy vandal without bothering
1283 * @param Revision $rev
1285 function generateRollback( $rev ) {
1286 return '<span class="mw-rollback-link">['
1287 . $this->buildRollbackLink( $rev )
1292 * Build a raw rollback link, useful for collections of "tool" links
1294 * @param Revision $rev
1297 public function buildRollbackLink( $rev ) {
1298 global $wgRequest, $wgUser;
1299 $title = $rev->getTitle();
1300 $extra = $wgRequest->getBool( 'bot' ) ?
'&bot=1' : '';
1301 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1302 $rev->getUserText() ) ) );
1303 return $this->makeKnownLinkObj(
1305 wfMsgHtml( 'rollbacklink' ),
1306 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1311 * Returns HTML for the "templates used on this page" list.
1313 * @param array $templates Array of templates from Article::getUsedTemplate
1315 * @param bool $preview Whether this is for a preview
1316 * @param bool $section Whether this is for a section edit
1317 * @return string HTML output
1319 public function formatTemplates( $templates, $preview = false, $section = false) {
1321 wfProfileIn( __METHOD__
);
1323 $sk = $wgUser->getSkin();
1326 if ( count( $templates ) > 0 ) {
1327 # Do a batch existence check
1328 $batch = new LinkBatch
;
1329 foreach( $templates as $title ) {
1330 $batch->addObj( $title );
1334 # Construct the HTML
1335 $outText = '<div class="mw-templatesUsedExplanation">';
1337 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1338 } elseif ( $section ) {
1339 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1341 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1343 $outText .= '</div><ul>';
1345 foreach ( $templates as $titleObj ) {
1346 $r = $titleObj->getRestrictions( 'edit' );
1347 if ( in_array( 'sysop', $r ) ) {
1348 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1349 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1350 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1354 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1356 $outText .= '</ul>';
1358 wfProfileOut( __METHOD__
);
1363 * Format a size in bytes for output, using an appropriate
1364 * unit (B, KB, MB or GB) according to the magnitude in question
1366 * @param $size Size to format
1369 public function formatSize( $size ) {
1371 return htmlspecialchars( $wgLang->formatSize( $size ) );
1375 * Given the id of an interface element, constructs the appropriate title
1376 * and accesskey attributes from the system messages. (Note, this is usu-
1377 * ally the id but isn't always, because sometimes the accesskey needs to
1378 * go on a different element than the id, for reverse-compatibility, etc.)
1380 * @param string $name Id of the element, minus prefixes.
1381 * @return string title and accesskey attributes, ready to drop in an
1382 * element (e.g., ' title="This does something [x]" accesskey="x"').
1384 public function tooltipAndAccesskey($name) {
1385 $fname="Linker::tooltipAndAccesskey";
1386 wfProfileIn($fname);
1389 $tooltip = wfMsg('tooltip-'.$name);
1390 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1391 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1392 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1393 $out .= ' title="'.htmlspecialchars($tooltip);
1395 $accesskey = wfMsg('accesskey-'.$name);
1396 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1397 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1398 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1402 wfProfileOut($fname);
1407 * Given the id of an interface element, constructs the appropriate title
1408 * attribute from the system messages. (Note, this is usually the id but
1409 * isn't always, because sometimes the accesskey needs to go on a different
1410 * element than the id, for reverse-compatibility, etc.)
1412 * @param string $name Id of the element, minus prefixes.
1413 * @return string title attribute, ready to drop in an element
1414 * (e.g., ' title="This does something"').
1416 public function tooltip($name) {
1419 $tooltip = wfMsg('tooltip-'.$name);
1420 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1421 $out = ' title="'.htmlspecialchars($tooltip).'"';