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( 'Linker::makeLink' );
103 $nt = Title
::newFromText( $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( 'Linker::makeLink' );
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 );
129 return $this->makeKnownLinkObj( Title
::newFromText( $title ), $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 );
150 return $this->makeBrokenLinkObj( Title
::newFromText( $title ), $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 );
171 return $this->makeStubLinkObj( Title
::newFromText( $title ), $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 $fname = 'Linker::makeLinkObj';
195 wfProfileIn( $fname );
198 if ( ! is_object($nt) ) {
199 # throw new MWException();
200 wfProfileOut( $fname );
201 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
204 if ( $nt->isExternal() ) {
205 $u = $nt->getFullURL();
206 $link = $nt->getPrefixedURL();
207 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
208 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
211 if ( '' != $trail ) {
213 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
218 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
220 wfProfileOut( $fname );
222 } elseif ( $nt->isAlwaysKnown() ) {
223 # Image links, special page links and self-links with fragements are always known.
224 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
226 wfProfileIn( $fname.'-immediate' );
228 # Handles links to special pages wich do not exist in the database:
229 if( $nt->getNamespace() == NS_SPECIAL
) {
230 if( SpecialPage
::exists( $nt->getDbKey() ) ) {
231 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
233 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
235 wfProfileOut( $fname.'-immediate' );
236 wfProfileOut( $fname );
240 # Work out link colour immediately
241 $aid = $nt->getArticleID() ;
243 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
246 if ( $nt->isContentPage() ) {
247 $threshold = $wgUser->getOption('stubthreshold');
248 if ( $threshold > 0 ) {
249 $dbr = wfGetDB( DB_SLAVE
);
250 $s = $dbr->selectRow(
253 'page_is_redirect' ),
254 array( 'page_id' => $aid ), $fname ) ;
255 $stub = ( $s !== false && !$s->page_is_redirect
&&
256 $s->page_len
< $threshold );
260 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
262 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
265 wfProfileOut( $fname.'-immediate' );
267 wfProfileOut( $fname );
272 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
273 * it doesn't have to do a database query. It's also valid for interwiki titles and special
276 * @param $nt Title object of target page
277 * @param $text String: text to replace the title
278 * @param $query String: link target
279 * @param $trail String: text after link
280 * @param $prefix String: text before link text
281 * @param $aprops String: extra attributes to the a-element
282 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
283 * @return the a-element
285 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
287 $fname = 'Linker::makeKnownLinkObj';
288 wfProfileIn( $fname );
290 if ( !is_object( $nt ) ) {
291 wfProfileOut( $fname );
295 $u = $nt->escapeLocalURL( $query );
296 if ( $nt->getFragment() != '' ) {
297 if( $nt->getPrefixedDbkey() == '' ) {
300 $text = htmlspecialchars( $nt->getFragment() );
303 $u .= $nt->getFragmentForURL();
306 $text = htmlspecialchars( $nt->getPrefixedText() );
308 if ( $style == '' ) {
309 $style = $this->getInternalLinkAttributesObj( $nt, $text );
312 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
314 list( $inside, $trail ) = Linker
::splitTrail( $trail );
315 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
316 wfProfileOut( $fname );
321 * Make a red link to the edit page of a given title.
323 * @param $title String: The text of the title
324 * @param $text String: Link text
325 * @param $query String: Optional query part
326 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
327 * be included in the link text. Other characters will be appended after
328 * the end of the link.
330 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
332 if ( ! isset($nt) ) {
333 # throw new MWException();
334 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
337 $fname = 'Linker::makeBrokenLinkObj';
338 wfProfileIn( $fname );
340 if( $nt->getNamespace() == NS_SPECIAL
) {
342 } else if ( '' == $query ) {
345 $q = 'action=edit&'.$query;
347 $u = $nt->escapeLocalURL( $q );
350 $text = htmlspecialchars( $nt->getPrefixedText() );
352 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
354 list( $inside, $trail ) = Linker
::splitTrail( $trail );
355 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
357 wfProfileOut( $fname );
362 * Make a brown link to a short article.
364 * @param $title String: the text of the title
365 * @param $text String: link text
366 * @param $query String: optional query part
367 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
368 * be included in the link text. Other characters will be appended after
369 * the end of the link.
371 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
372 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
373 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
377 * Generate either a normal exists-style link or a stub link, depending
378 * on the given page size.
380 * @param $size Integer
381 * @param $nt Title object.
382 * @param $text String
383 * @param $query String
384 * @param $trail String
385 * @param $prefix String
386 * @return string HTML of link
388 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
390 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
391 if( $size < $threshold ) {
392 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
394 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
399 * Make appropriate markup for a link to the current article. This is currently rendered
400 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
401 * despite $query not being used.
403 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
405 $text = htmlspecialchars( $nt->getPrefixedText() );
407 list( $inside, $trail ) = Linker
::splitTrail( $trail );
408 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
411 /** @todo document */
412 function fnamePart( $url ) {
413 $basename = strrchr( $url, '/' );
414 if ( false === $basename ) {
417 $basename = substr( $basename, 1 );
419 return htmlspecialchars( $basename );
422 /** Obsolete alias */
423 function makeImage( $url, $alt = '' ) {
424 return $this->makeExternalImage( $url, $alt );
427 /** @todo document */
428 function makeExternalImage( $url, $alt = '' ) {
430 $alt = $this->fnamePart( $url );
432 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
437 * Creates the HTML source for images
438 * @deprecated use makeImageLink2
440 * @param object $title
441 * @param string $label label text
442 * @param string $alt alt text
443 * @param string $align horizontal alignment: none, left, center, right)
444 * @param array $handlerParams Parameters to be passed to the media handler
445 * @param boolean $framed shows image in original size in a frame
446 * @param boolean $thumb shows image as thumbnail in a frame
447 * @param string $manualthumb image name for the manual thumbnail
448 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
451 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
452 $thumb = false, $manualthumb = '', $valign = '', $time = false )
454 $frameParams = array( 'alt' => $alt, 'caption' => $label );
456 $frameParams['align'] = $align;
459 $frameParams['framed'] = true;
462 $frameParams['thumb'] = true;
464 if ( $manualthumb ) {
465 $frameParams['manualthumb'] = $manualthumb;
468 $frameParams['valign'] = $valign;
470 $file = wfFindFile( $title, $time );
471 return $this->makeImageLink2( $title, $file, $label, $alt, $frameParams, $handlerParams );
476 * @param Title $title Title object
477 * @param File $file File object, or false if it doesn't exist
479 * @param array $frameParams Associative array of parameters external to the media handler.
480 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
481 * will often be false.
482 * thumbnail If present, downscale and frame
483 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
484 * framed Shows image in original size in a frame
485 * frameless Downscale but don't frame
486 * upright If present, tweak default sizes for portrait orientation
487 * upright_factor Fudge factor for "upright" tweak (default 0.75)
488 * border If present, show a border around the image
489 * align Horizontal alignment (left, right, center, none)
490 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
491 * bottom, text-bottom)
492 * alt Alternate text for image (i.e. alt attribute). Plain text.
493 * caption HTML for image caption.
495 * @param array $handlerParams Associative array of media handler parameters, to be passed
496 * to transform(). Typical keys are "width" and "page".
498 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
499 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
500 if ( $file && !$file->allowInlineDisplay() ) {
501 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
502 return $this->makeKnownLinkObj( $title );
507 $hp =& $handlerParams;
509 // Clean up parameters
510 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
511 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
512 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
514 $prefix = $postfix = '';
516 if ( 'center' == $fp['align'] )
518 $prefix = '<div class="center">';
520 $fp['align'] = 'none';
522 if ( $file && !isset( $hp['width'] ) ) {
523 $hp['width'] = $file->getWidth( $page );
525 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
526 $wopt = $wgUser->getOption( 'thumbsize' );
528 if( !isset( $wgThumbLimits[$wopt] ) ) {
529 $wopt = User
::getDefaultOption( 'thumbsize' );
532 // Reduce width for upright images when parameter 'upright' is used
533 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
534 $fp['upright'] = $wgThumbUpright;
536 // Use width which is smaller: real image width or user preference width
537 // 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
538 $prefWidth = isset( $fp['upright'] ) ?
539 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
540 $wgThumbLimits[$wopt];
541 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
542 $hp['width'] = $prefWidth;
547 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
549 # Create a thumbnail. Alignment depends on language
550 # writing direction, # right aligned for left-to-right-
551 # languages ("Western languages"), left-aligned
552 # for right-to-left-languages ("Semitic languages")
554 # If thumbnail width has not been provided, it is set
555 # to the default user option as specified in Language*.php
556 if ( $fp['align'] == '' ) {
557 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
559 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp ).$postfix;
562 if ( $file && $hp['width'] ) {
563 # Create a resized image, without the additional thumbnail features
564 $thumb = $file->transform( $hp );
570 $query = 'page=' . urlencode( $page );
574 $url = $title->getLocalURL( $query );
580 if ( isset( $fp['valign'] ) ) {
581 $imgAttribs['style'] = "vertical-align: {$fp['valign']}";
583 if ( isset( $fp['border'] ) ) {
584 $imgAttribs['class'] = "thumbborder";
586 $linkAttribs = array(
589 'title' => $fp['alt']
593 $s = $this->makeBrokenImageLinkObj( $title );
595 $s = $thumb->toHtml( $imgAttribs, $linkAttribs );
597 if ( '' != $fp['align'] ) {
598 $s = "<div class=\"float{$fp['align']}\"><span>{$s}</span></div>";
600 return str_replace("\n", ' ',$prefix.$s.$postfix);
604 * Make HTML for a thumbnail including image, border and caption
605 * @param Title $title
606 * @param File $file File object or false if it doesn't exist
608 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
609 $frameParams = array(
614 if ( $framed ) $frameParams['framed'] = true;
615 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
616 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
619 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array() ) {
620 global $wgStylePath, $wgContLang;
621 $exists = $file && $file->exists();
625 $hp =& $handlerParams;
627 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
628 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
629 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
630 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
632 if ( empty( $hp['width'] ) ) {
633 // Reduce width for upright images when parameter 'upright' is used
634 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
639 $outerWidth = $hp['width'] +
2;
641 if ( isset( $fp['manualthumb'] ) ) {
642 # Use manually specified thumbnail
643 $manual_title = Title
::makeTitleSafe( NS_IMAGE
, $fp['manualthumb'] );
644 if( $manual_title ) {
645 $manual_img = wfFindFile( $manual_title );
647 $thumb = $manual_img->getUnscaledThumb();
652 } elseif ( isset( $fp['framed'] ) ) {
653 // Use image dimensions, don't scale
654 $thumb = $file->getUnscaledThumb( $page );
656 # Do not present an image bigger than the source, for bitmap-style images
657 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
658 $srcWidth = $file->getWidth( $page );
659 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
660 $hp['width'] = $srcWidth;
662 $thumb = $file->transform( $hp );
666 $outerWidth = $thumb->getWidth() +
2;
668 $outerWidth = $hp['width'] +
2;
672 $query = $page ?
'page=' . urlencode( $page ) : '';
673 $url = $title->getLocalURL( $query );
675 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
676 $magnifyalign = $wgContLang->isRTL() ?
'left' : 'right';
677 $textalign = $wgContLang->isRTL() ?
' style="text-align:right"' : '';
679 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
681 $s .= $this->makeBrokenImageLinkObj( $title );
683 } elseif ( !$thumb ) {
684 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
690 'class' => 'thumbimage'
692 $linkAttribs = array(
694 'class' => 'internal',
695 'title' => $fp['alt']
698 $s .= $thumb->toHtml( $imgAttribs, $linkAttribs );
699 if ( isset( $fp['framed'] ) ) {
702 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
703 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
704 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
705 'width="15" height="11" alt="" /></a></div>';
708 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$fp['caption']."</div></div></div>";
709 return str_replace("\n", ' ', $s);
713 * Make a "broken" link to an image
715 * @param Title $title Image title
716 * @param string $text Link label
717 * @param string $query Query string
718 * @param string $trail Link trail
719 * @param string $prefix Link prefix
722 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
723 global $wgEnableUploads;
724 if( $title instanceof Title
) {
725 wfProfileIn( __METHOD__
);
726 if( $wgEnableUploads ) {
727 $upload = SpecialPage
::getTitleFor( 'Upload' );
729 $text = htmlspecialchars( $title->getPrefixedText() );
730 $q = 'wpDestFile=' . $title->getPartialUrl();
733 list( $inside, $trail ) = self
::splitTrail( $trail );
734 $style = $this->getInternalLinkAttributesObj( $title, $text, 'yes' );
735 wfProfileOut( __METHOD__
);
736 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
737 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
739 wfProfileOut( __METHOD__
);
740 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
743 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
747 /** @deprecated use Linker::makeMediaLinkObj() */
748 function makeMediaLink( $name, $unused = '', $text = '' ) {
749 $nt = Title
::makeTitleSafe( NS_IMAGE
, $name );
750 return $this->makeMediaLinkObj( $nt, $text );
754 * Create a direct link to a given uploaded file.
756 * @param $title Title object.
757 * @param $text String: pre-sanitized HTML
758 * @return string HTML
761 * @todo Handle invalid or missing images better.
763 function makeMediaLinkObj( $title, $text = '' ) {
764 if( is_null( $title ) ) {
765 ### HOTFIX. Instead of breaking, return empty string.
768 $img = wfFindFile( $title );
770 $url = $img->getURL();
773 $upload = SpecialPage
::getTitleFor( 'Upload' );
774 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDbKey() ) );
777 $alt = htmlspecialchars( $title->getText() );
781 $u = htmlspecialchars( $url );
782 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
786 /** @todo document */
787 function specialLink( $name, $key = '' ) {
790 if ( '' == $key ) { $key = strtolower( $name ); }
791 $pn = $wgContLang->ucfirst( $name );
792 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
796 /** @todo document */
797 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
798 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
799 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
800 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
801 $style .= ' rel="nofollow"';
803 $url = htmlspecialchars( $url );
805 $text = htmlspecialchars( $text );
807 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
811 * Make user link (or user contributions for unregistered users)
812 * @param $userId Integer: user id in database.
813 * @param $userText String: user name in database
814 * @return string HTML fragment
817 function userLink( $userId, $userText ) {
818 $encName = htmlspecialchars( $userText );
820 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
821 return $this->makeKnownLinkObj( $contribsPage,
824 $userPage = Title
::makeTitle( NS_USER
, $userText );
825 return $this->makeLinkObj( $userPage, $encName );
830 * Generate standard user tool links (talk, contributions, block link, etc.)
832 * @param int $userId User identifier
833 * @param string $userText User name or IP address
834 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
835 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
838 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
839 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
840 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
841 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
845 $items[] = $this->userTalkLink( $userId, $userText );
848 // check if the user has an edit
849 if( $redContribsWhenNoEdits && User
::edits( $userId ) == 0 ) {
850 $style = " class='new'";
854 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
856 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
858 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
859 $items[] = $this->blockLink( $userId, $userText );
863 return ' (' . implode( ' | ', $items ) . ')';
870 * Alias for userToolLinks( $userId, $userText, true );
872 public function userToolLinksRedContribs( $userId, $userText ) {
873 return $this->userToolLinks( $userId, $userText, true );
878 * @param $userId Integer: user id in database.
879 * @param $userText String: user name in database.
880 * @return string HTML fragment with user talk link
883 function userTalkLink( $userId, $userText ) {
884 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
885 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
886 return $userTalkLink;
890 * @param $userId Integer: userid
891 * @param $userText String: user name in database.
892 * @return string HTML fragment with block link
895 function blockLink( $userId, $userText ) {
896 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
897 $blockLink = $this->makeKnownLinkObj( $blockPage,
898 wfMsgHtml( 'blocklink' ) );
903 * Generate a user link if the current user is allowed to view it
904 * @param $rev Revision object.
905 * @return string HTML
907 function revUserLink( $rev ) {
908 if( $rev->userCan( Revision
::DELETED_USER
) ) {
909 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
911 $link = wfMsgHtml( 'rev-deleted-user' );
913 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
914 return '<span class="history-deleted">' . $link . '</span>';
920 * Generate a user tool link cluster if the current user is allowed to view it
921 * @param $rev Revision object.
922 * @return string HTML
924 function revUserTools( $rev ) {
925 if( $rev->userCan( Revision
::DELETED_USER
) ) {
926 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
928 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
930 $link = wfMsgHtml( 'rev-deleted-user' );
932 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
933 return '<span class="history-deleted">' . $link . '</span>';
939 * This function is called by all recent changes variants, by the page history,
940 * and by the user contributions list. It is responsible for formatting edit
941 * comments. It escapes any HTML in the comment, but adds some CSS to format
942 * auto-generated comments (from section editing) and formats [[wikilinks]].
944 * @author Erik Moeller <moeller@scireview.de>
946 * Note: there's not always a title to pass to this function.
947 * Since you can't set a default parameter for a reference, I've turned it
948 * temporarily to a value pass. Should be adjusted further. --brion
950 * @param string $comment
951 * @param mixed $title Title object (to generate link to the section in autocomment) or null
952 * @param bool $local Whether section links should refer to local page
954 function formatComment($comment, $title = NULL, $local = false) {
955 wfProfileIn( __METHOD__
);
957 # Sanitize text a bit:
958 $comment = str_replace( "\n", " ", $comment );
959 $comment = htmlspecialchars( $comment );
961 # Render autocomments and make links:
962 $comment = $this->formatAutoComments( $comment, $title, $local );
963 $comment = $this->formatLinksInComment( $comment );
965 wfProfileOut( __METHOD__
);
970 * The pattern for autogen comments is / * foo * /, which makes for
972 * We look for all comments, match any text before and after the comment,
973 * add a separator where needed and format the comment itself with CSS
974 * Called by Linker::formatComment.
976 * @param $comment Comment text
977 * @param $title An optional title object used to links to sections
979 * @todo Document the $local parameter.
981 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
983 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
991 # Generate a valid anchor name from the section title.
992 # Hackish, but should generally work - we strip wiki
993 # syntax, including the magic [[: that is used to
994 # "link rather than show" in case of images and
995 # interlanguage links.
996 $section = str_replace( '[[:', '', $section );
997 $section = str_replace( '[[', '', $section );
998 $section = str_replace( ']]', '', $section );
1000 $sectionTitle = Title
::newFromText( '#' . $section);
1002 $sectionTitle = wfClone( $title );
1003 $sectionTitle->mFragment
= $section;
1005 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
1009 if($pre) { $auto = $sep.' '.$auto; }
1010 if($post) { $auto .= ' '.$sep; }
1011 $auto='<span class="autocomment">'.$auto.'</span>';
1012 $comment=$pre.$auto.$post;
1019 * Formats wiki links and media links in text; all other wiki formatting
1022 * @param string $comment Text to format links in
1025 public function formatLinksInComment( $comment ) {
1028 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1029 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1032 while(preg_match('/\[\[:?(.*?)(\|(.*?))*\]\](.*)$/',$comment,$match)) {
1033 # Handle link renaming [[foo|text]] will show link as "text"
1034 if( "" != $match[3] ) {
1039 $submatch = array();
1040 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1041 # Media link; trail not supported.
1042 $linkRegexp = '/\[\[(.*?)\]\]/';
1043 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1045 # Other kind of link
1046 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1047 $trail = $submatch[1];
1051 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1052 if (isset($match[1][0]) && $match[1][0] == ':')
1053 $match[1] = substr($match[1], 1);
1054 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1056 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1063 * Wrap a comment in standard punctuation and formatting if
1064 * it's non-empty, otherwise return empty string.
1066 * @param string $comment
1067 * @param mixed $title Title object (to generate link to section in autocomment) or null
1068 * @param bool $local Whether section links should refer to local page
1072 function commentBlock( $comment, $title = NULL, $local = false ) {
1073 // '*' used to be the comment inserted by the software way back
1074 // in antiquity in case none was provided, here for backwards
1075 // compatability, acc. to brion -ævar
1076 if( $comment == '' ||
$comment == '*' ) {
1079 $formatted = $this->formatComment( $comment, $title, $local );
1080 return " <span class=\"comment\">($formatted)</span>";
1085 * Wrap and format the given revision's comment block, if the current
1086 * user is allowed to view it.
1088 * @param Revision $rev
1089 * @param bool $local Whether section links should refer to local page
1090 * @return string HTML
1092 function revComment( Revision
$rev, $local = false ) {
1093 if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1094 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
1096 $block = " <span class=\"comment\">" .
1097 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1099 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1100 return " <span class=\"history-deleted\">$block</span>";
1105 /** @todo document */
1106 function tocIndent() {
1110 /** @todo document */
1111 function tocUnindent($level) {
1112 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1116 * parameter level defines if we are on an indentation level
1118 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1119 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1120 $anchor . '"><span class="tocnumber">' .
1121 $tocnumber . '</span> <span class="toctext">' .
1122 $tocline . '</span></a>';
1125 /** @todo document */
1126 function tocLineEnd() {
1130 /** @todo document */
1131 function tocList($toc) {
1132 global $wgJsMimeType;
1133 $title = wfMsgHtml('toc') ;
1135 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1136 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1138 # no trailing newline, script should not be wrapped in a
1140 . "</ul>\n</td></tr></table>"
1141 . '<script type="' . $wgJsMimeType . '">'
1142 . ' if (window.showTocToggle) {'
1143 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1144 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1145 . ' showTocToggle();'
1151 * Used to generate section edit links that point to "other" pages
1152 * (sections that are really part of included pages).
1154 * @param $title Title string.
1155 * @param $section Integer: section number.
1157 public function editSectionLinkForOther( $title, $section ) {
1158 $title = Title
::newFromText( $title );
1159 return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
1163 * @param $nt Title object.
1164 * @param $section Integer: section number.
1165 * @param $hint Link String: title, or default if omitted or empty
1167 public function editSectionLink( Title
$nt, $section, $hint='' ) {
1169 $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
1170 $hint = " title=\"$hint\"";
1172 return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
1176 * Implement editSectionLink and editSectionLinkForOther.
1178 * @param $nt Title object
1179 * @param $section Integer, section number
1180 * @param $hint String, for HTML title attribute
1181 * @param $hook String, name of hook to run
1182 * @return String, HTML to use for edit link
1184 protected function doEditSectionLink( Title
$nt, $section, $hint, $hook ) {
1186 $editurl = '§ion='.$section;
1187 $url = $this->makeKnownLinkObj(
1189 wfMsg('editsection'),
1190 'action=edit'.$editurl,
1195 // The two hooks have slightly different interfaces . . .
1196 if( $hook == 'EditSectionLink' ) {
1197 wfRunHooks( $hook, array( &$this, $nt, $section, $hint, $url, &$result ) );
1198 } elseif( $hook == 'EditSectionLinkForOther' ) {
1199 wfRunHooks( $hook, array( &$this, $nt, $section, $url, &$result ) );
1202 // For reverse compatibility, add the brackets *after* the hook is run,
1203 // and even add them to hook-provided text.
1204 if( is_null( $result ) ) {
1205 $result = wfMsg( 'editsection-brackets', $url );
1207 $result = wfMsg( 'editsection-brackets', $result );
1209 return "<span class=\"editsection\">$result</span>";
1213 * Create a headline for content
1215 * @param int $level The level of the headline (1-6)
1216 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1217 * This *must* be at least '>' for no attribs
1218 * @param string $anchor The anchor to give the headline (the bit after the #)
1219 * @param string $text The text of the header
1220 * @param string $link HTML to add for the section edit link
1222 * @return string HTML headline
1224 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1225 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1229 * Split a link trail, return the "inside" portion and the remainder of the trail
1230 * as a two-element array
1234 static function splitTrail( $trail ) {
1235 static $regex = false;
1236 if ( $regex === false ) {
1238 $regex = $wgContLang->linkTrail();
1241 if ( '' != $trail ) {
1243 if ( preg_match( $regex, $trail, $m ) ) {
1248 return array( $inside, $trail );
1252 * Generate a rollback link for a given revision. Currently it's the
1253 * caller's responsibility to ensure that the revision is the top one. If
1254 * it's not, of course, the user will get an error message.
1256 * If the calling page is called with the parameter &bot=1, all rollback
1257 * links also get that parameter. It causes the edit itself and the rollback
1258 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1259 * changes, so this allows sysops to combat a busy vandal without bothering
1262 * @param Revision $rev
1264 function generateRollback( $rev ) {
1265 return '<span class="mw-rollback-link">['
1266 . $this->buildRollbackLink( $rev )
1271 * Build a raw rollback link, useful for collections of "tool" links
1273 * @param Revision $rev
1276 public function buildRollbackLink( $rev ) {
1277 global $wgRequest, $wgUser;
1278 $title = $rev->getTitle();
1279 $extra = $wgRequest->getBool( 'bot' ) ?
'&bot=1' : '';
1280 $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
1281 $rev->getUserText() ) ) );
1282 return $this->makeKnownLinkObj(
1284 wfMsgHtml( 'rollbacklink' ),
1285 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
1290 * Returns HTML for the "templates used on this page" list.
1292 * @param array $templates Array of templates from Article::getUsedTemplate
1294 * @param bool $preview Whether this is for a preview
1295 * @param bool $section Whether this is for a section edit
1296 * @return string HTML output
1298 public function formatTemplates( $templates, $preview = false, $section = false) {
1300 wfProfileIn( __METHOD__
);
1302 $sk = $wgUser->getSkin();
1305 if ( count( $templates ) > 0 ) {
1306 # Do a batch existence check
1307 $batch = new LinkBatch
;
1308 foreach( $templates as $title ) {
1309 $batch->addObj( $title );
1313 # Construct the HTML
1314 $outText = '<div class="mw-templatesUsedExplanation">';
1316 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1317 } elseif ( $section ) {
1318 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1320 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1322 $outText .= '</div><ul>';
1324 foreach ( $templates as $titleObj ) {
1325 $r = $titleObj->getRestrictions( 'edit' );
1326 if ( in_array( 'sysop', $r ) ) {
1327 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1328 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1329 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1333 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1335 $outText .= '</ul>';
1337 wfProfileOut( __METHOD__
);
1342 * Format a size in bytes for output, using an appropriate
1343 * unit (B, KB, MB or GB) according to the magnitude in question
1345 * @param $size Size to format
1348 public function formatSize( $size ) {
1350 return htmlspecialchars( $wgLang->formatSize( $size ) );
1354 * Given the id of an interface element, constructs the appropriate title
1355 * and accesskey attributes from the system messages. (Note, this is usu-
1356 * ally the id but isn't always, because sometimes the accesskey needs to
1357 * go on a different element than the id, for reverse-compatibility, etc.)
1359 * @param string $name Id of the element, minus prefixes.
1360 * @return string title and accesskey attributes, ready to drop in an
1361 * element (e.g., ' title="This does something [x]" accesskey="x"').
1363 public function tooltipAndAccesskey($name) {
1366 $tooltip = wfMsg('tooltip-'.$name);
1367 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1368 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1369 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1370 $out .= ' title="'.htmlspecialchars($tooltip);
1372 $accesskey = wfMsg('accesskey-'.$name);
1373 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1374 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1375 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1383 * Given the id of an interface element, constructs the appropriate title
1384 * attribute from the system messages. (Note, this is usually the id but
1385 * isn't always, because sometimes the accesskey needs to go on a different
1386 * element than the id, for reverse-compatibility, etc.)
1388 * @param string $name Id of the element, minus prefixes.
1389 * @return string title attribute, ready to drop in an element
1390 * (e.g., ' title="This does something"').
1392 public function tooltip($name) {
1395 $tooltip = wfMsg('tooltip-'.$name);
1396 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1397 $out = ' title="'.htmlspecialchars($tooltip).'"';