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__
);
239 if( ! wfRunHooks('LinkerMakeLinkObj', array(&$hookRetVal, &$this, $nt, $text, $query, $trail, $prefix)) ) {
240 wfProfileOut( __METHOD__
.'-immediate' );
241 wfProfileOut( __METHOD__
);
245 # Work out link colour immediately
246 $aid = $nt->getArticleID() ;
248 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
251 if ( $nt->isContentPage() ) {
252 $threshold = $wgUser->getOption('stubthreshold');
253 if ( $threshold > 0 ) {
254 $dbr = wfGetDB( DB_SLAVE
);
255 $s = $dbr->selectRow(
258 'page_is_redirect' ),
259 array( 'page_id' => $aid ), __METHOD__
) ;
260 $stub = ( $s !== false && !$s->page_is_redirect
&&
261 $s->page_len
< $threshold );
265 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
267 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
270 wfProfileOut( __METHOD__
.'-immediate' );
272 wfProfileOut( __METHOD__
);
277 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
278 * it doesn't have to do a database query. It's also valid for interwiki titles and special
281 * @param $nt Title object of target page
282 * @param $text String: text to replace the title
283 * @param $query String: link target
284 * @param $trail String: text after link
285 * @param $prefix String: text before link text
286 * @param $aprops String: extra attributes to the a-element
287 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
288 * @return the a-element
290 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
291 wfProfileIn( __METHOD__
);
293 if ( !$nt instanceof Title
) {
295 wfProfileOut( __METHOD__
);
296 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
299 $u = $nt->escapeLocalURL( $query );
300 if ( $nt->getFragment() != '' ) {
301 if( $nt->getPrefixedDbkey() == '' ) {
304 $text = htmlspecialchars( $nt->getFragment() );
307 $u .= $nt->getFragmentForURL();
310 $text = htmlspecialchars( $nt->getPrefixedText() );
312 if ( $style == '' ) {
313 $style = $this->getInternalLinkAttributesObj( $nt, $text );
316 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
318 list( $inside, $trail ) = Linker
::splitTrail( $trail );
319 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
320 wfProfileOut( __METHOD__
);
325 * Make a red link to the edit page of a given title.
327 * @param $title String: The text of the title
328 * @param $text String: Link text
329 * @param $query String: Optional query part
330 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
331 * be included in the link text. Other characters will be appended after
332 * the end of the link.
334 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
335 wfProfileIn( __METHOD__
);
337 if ( !$nt instanceof Title
) {
339 wfProfileOut( __METHOD__
);
340 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
343 if( $nt->getNamespace() == NS_SPECIAL
) {
345 } else if ( '' == $query ) {
348 $q = 'action=edit&'.$query;
350 $u = $nt->escapeLocalURL( $q );
353 $text = htmlspecialchars( $nt->getPrefixedText() );
355 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
357 list( $inside, $trail ) = Linker
::splitTrail( $trail );
358 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
360 wfProfileOut( __METHOD__
);
365 * Make a brown link to a short article.
367 * @param $title String: the text of the title
368 * @param $text String: link text
369 * @param $query String: optional query part
370 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
371 * be included in the link text. Other characters will be appended after
372 * the end of the link.
374 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
375 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
376 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
380 * Generate either a normal exists-style link or a stub link, depending
381 * on the given page size.
383 * @param $size Integer
384 * @param $nt Title object.
385 * @param $text String
386 * @param $query String
387 * @param $trail String
388 * @param $prefix String
389 * @return string HTML of link
391 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
393 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
394 if( $size < $threshold ) {
395 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
397 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
402 * Make appropriate markup for a link to the current article. This is currently rendered
403 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
404 * despite $query not being used.
406 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
408 $text = htmlspecialchars( $nt->getPrefixedText() );
410 list( $inside, $trail ) = Linker
::splitTrail( $trail );
411 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
414 /** @todo document */
415 function fnamePart( $url ) {
416 $basename = strrchr( $url, '/' );
417 if ( false === $basename ) {
420 $basename = substr( $basename, 1 );
422 return htmlspecialchars( $basename );
425 /** Obsolete alias */
426 function makeImage( $url, $alt = '' ) {
427 return $this->makeExternalImage( $url, $alt );
430 /** @todo document */
431 function makeExternalImage( $url, $alt = '' ) {
433 $alt = $this->fnamePart( $url );
435 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
440 * Creates the HTML source for images
441 * @deprecated use makeImageLink2
443 * @param object $title
444 * @param string $label label text
445 * @param string $alt alt text
446 * @param string $align horizontal alignment: none, left, center, right)
447 * @param array $handlerParams Parameters to be passed to the media handler
448 * @param boolean $framed shows image in original size in a frame
449 * @param boolean $thumb shows image as thumbnail in a frame
450 * @param string $manualthumb image name for the manual thumbnail
451 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
454 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
455 $thumb = false, $manualthumb = '', $valign = '', $time = false )
457 $frameParams = array( 'alt' => $alt, 'caption' => $label );
459 $frameParams['align'] = $align;
462 $frameParams['framed'] = true;
465 $frameParams['thumbnail'] = true;
467 if ( $manualthumb ) {
468 $frameParams['manualthumb'] = $manualthumb;
471 $frameParams['valign'] = $valign;
473 $file = wfFindFile( $title, $time );
474 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams );
479 * @param Title $title Title object
480 * @param File $file File object, or false if it doesn't exist
482 * @param array $frameParams Associative array of parameters external to the media handler.
483 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
484 * will often be false.
485 * thumbnail If present, downscale and frame
486 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
487 * framed Shows image in original size in a frame
488 * frameless Downscale but don't frame
489 * upright If present, tweak default sizes for portrait orientation
490 * upright_factor Fudge factor for "upright" tweak (default 0.75)
491 * border If present, show a border around the image
492 * align Horizontal alignment (left, right, center, none)
493 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
494 * bottom, text-bottom)
495 * alt Alternate text for image (i.e. alt attribute). Plain text.
496 * caption HTML for image caption.
498 * @param array $handlerParams Associative array of media handler parameters, to be passed
499 * to transform(). Typical keys are "width" and "page".
501 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
502 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
503 if ( $file && !$file->allowInlineDisplay() ) {
504 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
505 return $this->makeKnownLinkObj( $title );
510 $hp =& $handlerParams;
512 // Clean up parameters
513 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
514 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
515 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
517 $prefix = $postfix = '';
519 if ( 'center' == $fp['align'] )
521 $prefix = '<div class="center">';
523 $fp['align'] = 'none';
525 if ( $file && !isset( $hp['width'] ) ) {
526 $hp['width'] = $file->getWidth( $page );
528 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
529 $wopt = $wgUser->getOption( 'thumbsize' );
531 if( !isset( $wgThumbLimits[$wopt] ) ) {
532 $wopt = User
::getDefaultOption( 'thumbsize' );
535 // Reduce width for upright images when parameter 'upright' is used
536 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
537 $fp['upright'] = $wgThumbUpright;
539 // Use width which is smaller: real image width or user preference width
540 // 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
541 $prefWidth = isset( $fp['upright'] ) ?
542 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
543 $wgThumbLimits[$wopt];
544 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
545 $hp['width'] = $prefWidth;
550 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
552 # Create a thumbnail. Alignment depends on language
553 # writing direction, # right aligned for left-to-right-
554 # languages ("Western languages"), left-aligned
555 # for right-to-left-languages ("Semitic languages")
557 # If thumbnail width has not been provided, it is set
558 # to the default user option as specified in Language*.php
559 if ( $fp['align'] == '' ) {
560 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
562 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp ).$postfix;
565 if ( $file && $hp['width'] ) {
566 # Create a resized image, without the additional thumbnail features
567 $thumb = $file->transform( $hp );
573 $s = $this->makeBrokenImageLinkObj( $title );
575 $s = $thumb->toHtml( array(
578 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
579 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false ) );
581 if ( '' != $fp['align'] ) {
582 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
584 return str_replace("\n", ' ',$prefix.$s.$postfix);
588 * Make HTML for a thumbnail including image, border and caption
589 * @param Title $title
590 * @param File $file File object or false if it doesn't exist
592 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
593 $frameParams = array(
598 if ( $framed ) $frameParams['framed'] = true;
599 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
600 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
603 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
604 global $wgStylePath, $wgContLang;
605 $exists = $file && $file->exists();
609 $hp =& $handlerParams;
611 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
612 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
613 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
614 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
616 if ( empty( $hp['width'] ) ) {
617 // Reduce width for upright images when parameter 'upright' is used
618 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
623 $outerWidth = $hp['width'] +
2;
625 if ( isset( $fp['manualthumb'] ) ) {
626 # Use manually specified thumbnail
627 $manual_title = Title
::makeTitleSafe( NS_IMAGE
, $fp['manualthumb'] );
628 if( $manual_title ) {
629 $manual_img = wfFindFile( $manual_title );
631 $thumb = $manual_img->getUnscaledThumb();
636 } elseif ( isset( $fp['framed'] ) ) {
637 // Use image dimensions, don't scale
638 $thumb = $file->getUnscaledThumb( $page );
640 # Do not present an image bigger than the source, for bitmap-style images
641 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
642 $srcWidth = $file->getWidth( $page );
643 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
644 $hp['width'] = $srcWidth;
646 $thumb = $file->transform( $hp );
650 $outerWidth = $thumb->getWidth() +
2;
652 $outerWidth = $hp['width'] +
2;
656 $query = $page ?
'page=' . urlencode( $page ) : '';
657 $url = $title->getLocalURL( $query );
659 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
660 $magnifyalign = $wgContLang->isRTL() ?
'left' : 'right';
661 $textalign = $wgContLang->isRTL() ?
' style="text-align:right"' : '';
663 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
665 $s .= $this->makeBrokenImageLinkObj( $title );
667 } elseif ( !$thumb ) {
668 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
671 $s .= $thumb->toHtml( array(
673 'img-class' => 'thumbimage',
674 'desc-link' => true ) );
675 if ( isset( $fp['framed'] ) ) {
678 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
679 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
680 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
681 'width="15" height="11" alt="" /></a></div>';
684 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$fp['caption']."</div></div></div>";
685 return str_replace("\n", ' ', $s);
689 * Make a "broken" link to an image
691 * @param Title $title Image title
692 * @param string $text Link label
693 * @param string $query Query string
694 * @param string $trail Link trail
695 * @param string $prefix Link prefix
698 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
699 global $wgEnableUploads;
700 if( $title instanceof Title
) {
701 wfProfileIn( __METHOD__
);
702 if( $wgEnableUploads ) {
703 $upload = SpecialPage
::getTitleFor( 'Upload' );
705 $text = htmlspecialchars( $title->getPrefixedText() );
706 $q = 'wpDestFile=' . $title->getPartialUrl();
709 list( $inside, $trail ) = self
::splitTrail( $trail );
710 $style = $this->getInternalLinkAttributesObj( $title, $text, 'yes' );
711 wfProfileOut( __METHOD__
);
712 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
713 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
715 wfProfileOut( __METHOD__
);
716 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
719 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
723 /** @deprecated use Linker::makeMediaLinkObj() */
724 function makeMediaLink( $name, $unused = '', $text = '' ) {
725 $nt = Title
::makeTitleSafe( NS_IMAGE
, $name );
726 return $this->makeMediaLinkObj( $nt, $text );
730 * Create a direct link to a given uploaded file.
732 * @param $title Title object.
733 * @param $text String: pre-sanitized HTML
734 * @return string HTML
737 * @todo Handle invalid or missing images better.
739 function makeMediaLinkObj( $title, $text = '' ) {
740 if( is_null( $title ) ) {
741 ### HOTFIX. Instead of breaking, return empty string.
744 $img = wfFindFile( $title );
746 $url = $img->getURL();
749 $upload = SpecialPage
::getTitleFor( 'Upload' );
750 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDbKey() ) );
753 $alt = htmlspecialchars( $title->getText() );
757 $u = htmlspecialchars( $url );
758 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
762 /** @todo document */
763 function specialLink( $name, $key = '' ) {
766 if ( '' == $key ) { $key = strtolower( $name ); }
767 $pn = $wgContLang->ucfirst( $name );
768 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
772 /** @todo document */
773 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
774 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
775 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
776 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
777 $style .= ' rel="nofollow"';
779 $url = htmlspecialchars( $url );
781 $text = htmlspecialchars( $text );
783 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
787 * Make user link (or user contributions for unregistered users)
788 * @param $userId Integer: user id in database.
789 * @param $userText String: user name in database
790 * @return string HTML fragment
793 function userLink( $userId, $userText ) {
794 $encName = htmlspecialchars( $userText );
796 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
797 return $this->makeKnownLinkObj( $contribsPage,
800 $userPage = Title
::makeTitle( NS_USER
, $userText );
801 return $this->makeLinkObj( $userPage, $encName );
806 * Generate standard user tool links (talk, contributions, block link, etc.)
808 * @param int $userId User identifier
809 * @param string $userText User name or IP address
810 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
811 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
814 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
815 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
816 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
817 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
821 $items[] = $this->userTalkLink( $userId, $userText );
824 // check if the user has an edit
825 if( $redContribsWhenNoEdits && User
::edits( $userId ) == 0 ) {
826 $style = " class='new'";
830 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
832 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
834 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
835 $items[] = $this->blockLink( $userId, $userText );
839 return ' (' . implode( ' | ', $items ) . ')';
846 * Alias for userToolLinks( $userId, $userText, true );
848 public function userToolLinksRedContribs( $userId, $userText ) {
849 return $this->userToolLinks( $userId, $userText, true );
854 * @param $userId Integer: user id in database.
855 * @param $userText String: user name in database.
856 * @return string HTML fragment with user talk link
859 function userTalkLink( $userId, $userText ) {
860 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
861 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
862 return $userTalkLink;
866 * @param $userId Integer: userid
867 * @param $userText String: user name in database.
868 * @return string HTML fragment with block link
871 function blockLink( $userId, $userText ) {
872 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
873 $blockLink = $this->makeKnownLinkObj( $blockPage,
874 wfMsgHtml( 'blocklink' ) );
879 * Generate a user link if the current user is allowed to view it
880 * @param $rev Revision object.
881 * @return string HTML
883 function revUserLink( $rev ) {
884 if( $rev->userCan( Revision
::DELETED_USER
) ) {
885 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
887 $link = wfMsgHtml( 'rev-deleted-user' );
889 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
890 return '<span class="history-deleted">' . $link . '</span>';
896 * Generate a user tool link cluster if the current user is allowed to view it
897 * @param $rev Revision object.
898 * @return string HTML
900 function revUserTools( $rev ) {
901 if( $rev->userCan( Revision
::DELETED_USER
) ) {
902 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
904 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
906 $link = wfMsgHtml( 'rev-deleted-user' );
908 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
909 return '<span class="history-deleted">' . $link . '</span>';
915 * This function is called by all recent changes variants, by the page history,
916 * and by the user contributions list. It is responsible for formatting edit
917 * comments. It escapes any HTML in the comment, but adds some CSS to format
918 * auto-generated comments (from section editing) and formats [[wikilinks]].
920 * @author Erik Moeller <moeller@scireview.de>
922 * Note: there's not always a title to pass to this function.
923 * Since you can't set a default parameter for a reference, I've turned it
924 * temporarily to a value pass. Should be adjusted further. --brion
926 * @param string $comment
927 * @param mixed $title Title object (to generate link to the section in autocomment) or null
928 * @param bool $local Whether section links should refer to local page
930 function formatComment($comment, $title = NULL, $local = false) {
931 wfProfileIn( __METHOD__
);
933 # Sanitize text a bit:
934 $comment = str_replace( "\n", " ", $comment );
935 $comment = htmlspecialchars( $comment );
937 # Render autocomments and make links:
938 $comment = $this->formatAutoComments( $comment, $title, $local );
939 $comment = $this->formatLinksInComment( $comment );
941 wfProfileOut( __METHOD__
);
946 * The pattern for autogen comments is / * foo * /, which makes for
948 * We look for all comments, match any text before and after the comment,
949 * add a separator where needed and format the comment itself with CSS
950 * Called by Linker::formatComment.
952 * @param $comment Comment text
953 * @param $title An optional title object used to links to sections
955 * @todo Document the $local parameter.
957 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
959 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
967 # Generate a valid anchor name from the section title.
968 # Hackish, but should generally work - we strip wiki
969 # syntax, including the magic [[: that is used to
970 # "link rather than show" in case of images and
971 # interlanguage links.
972 $section = str_replace( '[[:', '', $section );
973 $section = str_replace( '[[', '', $section );
974 $section = str_replace( ']]', '', $section );
976 $sectionTitle = Title
::newFromText( '#' . $section);
978 $sectionTitle = wfClone( $title );
979 $sectionTitle->mFragment
= $section;
981 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
985 if($pre) { $auto = $sep.' '.$auto; }
986 if($post) { $auto .= ' '.$sep; }
987 $auto='<span class="autocomment">'.$auto.'</span>';
988 $comment=$pre.$auto.$post;
995 * Formats wiki links and media links in text; all other wiki formatting
998 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
999 * @param string $comment Text to format links in
1002 public function formatLinksInComment( $comment ) {
1003 return preg_replace_callback(
1004 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1005 array( $this, 'formatLinksInCommentCallback' ),
1009 protected function formatLinksInCommentCallback( $match ) {
1012 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1013 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1015 $comment = $match[0];
1017 # Handle link renaming [[foo|text]] will show link as "text"
1018 if( "" != $match[3] ) {
1023 $submatch = array();
1024 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1025 # Media link; trail not supported.
1026 $linkRegexp = '/\[\[(.*?)\]\]/';
1027 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1029 # Other kind of link
1030 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1031 $trail = $submatch[1];
1035 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1036 if (isset($match[1][0]) && $match[1][0] == ':')
1037 $match[1] = substr($match[1], 1);
1038 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1040 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1046 * Wrap a comment in standard punctuation and formatting if
1047 * it's non-empty, otherwise return empty string.
1049 * @param string $comment
1050 * @param mixed $title Title object (to generate link to section in autocomment) or null
1051 * @param bool $local Whether section links should refer to local page
1055 function commentBlock( $comment, $title = NULL, $local = false ) {
1056 // '*' used to be the comment inserted by the software way back
1057 // in antiquity in case none was provided, here for backwards
1058 // compatability, acc. to brion -ævar
1059 if( $comment == '' ||
$comment == '*' ) {
1062 $formatted = $this->formatComment( $comment, $title, $local );
1063 return " <span class=\"comment\">($formatted)</span>";
1068 * Wrap and format the given revision's comment block, if the current
1069 * user is allowed to view it.
1071 * @param Revision $rev
1072 * @param bool $local Whether section links should refer to local page
1073 * @return string HTML
1075 function revComment( Revision
$rev, $local = false ) {
1076 if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1077 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1079 $block = " <span class=\"comment\">" .
1080 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1082 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1083 return " <span class=\"history-deleted\">$block</span>";
1088 /** @todo document */
1089 function tocIndent() {
1093 /** @todo document */
1094 function tocUnindent($level) {
1095 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1099 * parameter level defines if we are on an indentation level
1101 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1102 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1103 $anchor . '"><span class="tocnumber">' .
1104 $tocnumber . '</span> <span class="toctext">' .
1105 $tocline . '</span></a>';
1108 /** @todo document */
1109 function tocLineEnd() {
1113 /** @todo document */
1114 function tocList($toc) {
1115 global $wgJsMimeType;
1116 $title = wfMsgHtml('toc') ;
1118 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1119 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1121 # no trailing newline, script should not be wrapped in a
1123 . "</ul>\n</td></tr></table>"
1124 . '<script type="' . $wgJsMimeType . '">'
1125 . ' if (window.showTocToggle) {'
1126 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1127 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1128 . ' showTocToggle();'
1134 * Used to generate section edit links that point to "other" pages
1135 * (sections that are really part of included pages).
1137 * @param $title Title string.
1138 * @param $section Integer: section number.
1140 public function editSectionLinkForOther( $title, $section ) {
1141 $title = Title
::newFromText( $title );
1142 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1146 * @param $nt Title object.
1147 * @param $section Integer: section number.
1148 * @param $hint Link String: title, or default if omitted or empty
1150 public function editSectionLink( Title
$nt, $section, $hint='' ) {
1152 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1153 $hint = " title=\"$hint\"";
1155 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1159 * Implement editSectionLink and editSectionLinkForOther.
1161 * @param $nt Title object
1162 * @param $section Integer, section number
1163 * @param $hint String, for HTML title attribute
1164 * @param $hook String, name of hook to run
1165 * @return String, HTML to use for edit link
1167 protected function doEditSectionLink( Title
$nt, $section, $hint, $hook ) {
1169 $editurl = '§ion='.$section;
1170 $url = $this->makeKnownLinkObj(
1172 wfMsg('editsection'),
1173 'action=edit'.$editurl,
1178 // The two hooks have slightly different interfaces . . .
1179 if( $hook == 'EditSectionLink' ) {
1180 wfRunHooks( $hook, array( &$this, $nt, $section, $hint, $url, &$result ) );
1181 } elseif( $hook == 'EditSectionLinkForOther' ) {
1182 wfRunHooks( $hook, array( &$this, $nt, $section, $url, &$result ) );
1185 // For reverse compatibility, add the brackets *after* the hook is run,
1186 // and even add them to hook-provided text.
1187 if( is_null( $result ) ) {
1188 $result = wfMsg( 'editsection-brackets', $url );
1190 $result = wfMsg( 'editsection-brackets', $result );
1192 return "<span class=\"editsection\">$result</span>";
1196 * Create a headline for content
1198 * @param int $level The level of the headline (1-6)
1199 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1200 * This *must* be at least '>' for no attribs
1201 * @param string $anchor The anchor to give the headline (the bit after the #)
1202 * @param string $text The text of the header
1203 * @param string $link HTML to add for the section edit link
1205 * @return string HTML headline
1207 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1208 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1212 * Split a link trail, return the "inside" portion and the remainder of the trail
1213 * as a two-element array
1217 static function splitTrail( $trail ) {
1218 static $regex = false;
1219 if ( $regex === false ) {
1221 $regex = $wgContLang->linkTrail();
1224 if ( '' != $trail ) {
1226 if ( preg_match( $regex, $trail, $m ) ) {
1231 return array( $inside, $trail );
1235 * Generate a rollback link for a given revision. Currently it's the
1236 * caller's responsibility to ensure that the revision is the top one. If
1237 * it's not, of course, the user will get an error message.
1239 * If the calling page is called with the parameter &bot=1, all rollback
1240 * links also get that parameter. It causes the edit itself and the rollback
1241 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1242 * changes, so this allows sysops to combat a busy vandal without bothering
1245 * @param Revision $rev
1247 function generateRollback( $rev ) {
1248 return '<span class="mw-rollback-link">['
1249 . $this->buildRollbackLink( $rev )
1254 * Build a raw rollback link, useful for collections of "tool" links
1256 * @param Revision $rev
1259 public function buildRollbackLink( $rev ) {
1260 global $wgRequest, $wgUser;
1261 $title = $rev->getTitle();
1262 $extra = $wgRequest->getBool( 'bot' ) ?
'&bot=1' : '';
1263 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1264 $rev->getUserText() ) ) );
1265 return $this->makeKnownLinkObj(
1267 wfMsgHtml( 'rollbacklink' ),
1268 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1273 * Returns HTML for the "templates used on this page" list.
1275 * @param array $templates Array of templates from Article::getUsedTemplate
1277 * @param bool $preview Whether this is for a preview
1278 * @param bool $section Whether this is for a section edit
1279 * @return string HTML output
1281 public function formatTemplates( $templates, $preview = false, $section = false) {
1283 wfProfileIn( __METHOD__
);
1285 $sk = $wgUser->getSkin();
1288 if ( count( $templates ) > 0 ) {
1289 # Do a batch existence check
1290 $batch = new LinkBatch
;
1291 foreach( $templates as $title ) {
1292 $batch->addObj( $title );
1296 # Construct the HTML
1297 $outText = '<div class="mw-templatesUsedExplanation">';
1299 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1300 } elseif ( $section ) {
1301 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1303 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1305 $outText .= '</div><ul>';
1307 foreach ( $templates as $titleObj ) {
1308 $r = $titleObj->getRestrictions( 'edit' );
1309 if ( in_array( 'sysop', $r ) ) {
1310 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1311 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1312 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1316 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1318 $outText .= '</ul>';
1320 wfProfileOut( __METHOD__
);
1325 * Format a size in bytes for output, using an appropriate
1326 * unit (B, KB, MB or GB) according to the magnitude in question
1328 * @param $size Size to format
1331 public function formatSize( $size ) {
1333 return htmlspecialchars( $wgLang->formatSize( $size ) );
1337 * Given the id of an interface element, constructs the appropriate title
1338 * and accesskey attributes from the system messages. (Note, this is usu-
1339 * ally the id but isn't always, because sometimes the accesskey needs to
1340 * go on a different element than the id, for reverse-compatibility, etc.)
1342 * @param string $name Id of the element, minus prefixes.
1343 * @return string title and accesskey attributes, ready to drop in an
1344 * element (e.g., ' title="This does something [x]" accesskey="x"').
1346 public function tooltipAndAccesskey($name) {
1349 $tooltip = wfMsg('tooltip-'.$name);
1350 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1351 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1352 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1353 $out .= ' title="'.htmlspecialchars($tooltip);
1355 $accesskey = wfMsg('accesskey-'.$name);
1356 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1357 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1358 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1366 * Given the id of an interface element, constructs the appropriate title
1367 * attribute from the system messages. (Note, this is usually the id but
1368 * isn't always, because sometimes the accesskey needs to go on a different
1369 * element than the id, for reverse-compatibility, etc.)
1371 * @param string $name Id of the element, minus prefixes.
1372 * @return string title attribute, ready to drop in an element
1373 * (e.g., ' title="This does something"').
1375 public function tooltip($name) {
1378 $tooltip = wfMsg('tooltip-'.$name);
1379 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1380 $out = ' title="'.htmlspecialchars($tooltip).'"';