Fix regression in even sizing of diff columns; forgot to restore a couple bits I...
[mediawiki.git] / includes / Linker.php
blobf293a89ad08d4cc43b8beb2fca9b4e545f8ed118
1 <?php
2 /**
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.
12 * @addtogroup Skins
14 class Linker {
15 function __construct() {}
17 /**
18 * @deprecated
20 function postParseLinkColour( $s = NULL ) {
21 return NULL;
24 /** @todo document */
25 function getExternalLinkAttributes( $link, $text, $class='' ) {
26 $link = htmlspecialchars( $link );
28 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
30 $r .= " title=\"{$link}\"";
31 return $r;
34 function getInterwikiLinkAttributes( $link, $text, $class='' ) {
35 global $wgContLang;
37 $link = urldecode( $link );
38 $link = $wgContLang->checkTitleEncoding( $link );
39 $link = preg_replace( '/[\\x00-\\x1f]/', ' ', $link );
40 $link = htmlspecialchars( $link );
42 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
44 $r .= " title=\"{$link}\"";
45 return $r;
48 /** @todo document */
49 function getInternalLinkAttributes( $link, $text, $broken = false ) {
50 $link = urldecode( $link );
51 $link = str_replace( '_', ' ', $link );
52 $link = htmlspecialchars( $link );
54 if( $broken == 'stub' ) {
55 $r = ' class="stub"';
56 } else if ( $broken == 'yes' ) {
57 $r = ' class="new"';
58 } else {
59 $r = '';
62 $r .= " title=\"{$link}\"";
63 return $r;
66 /**
67 * @param $nt Title object.
68 * @param $text String: FIXME
69 * @param $broken Boolean: FIXME, default 'false'.
71 function getInternalLinkAttributesObj( &$nt, $text, $broken = false ) {
72 if( $broken == 'stub' ) {
73 $r = ' class="stub"';
74 } else if ( $broken == 'yes' ) {
75 $r = ' class="new"';
76 } else {
77 $r = '';
80 $r .= ' title="' . $nt->getEscapedText() . '"';
81 return $r;
84 /**
85 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
86 * it if you already have a title object handy. See makeLinkObj for further documentation.
88 * @param $title String: the text of the title
89 * @param $text String: link text
90 * @param $query String: optional query part
91 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
92 * be included in the link text. Other characters will be appended after
93 * the end of the link.
95 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
96 wfProfileIn( 'Linker::makeLink' );
97 $nt = Title::newFromText( $title );
98 if ($nt) {
99 $result = $this->makeLinkObj( Title::newFromText( $title ), $text, $query, $trail );
100 } else {
101 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
102 $result = $text == "" ? $title : $text;
105 wfProfileOut( 'Linker::makeLink' );
106 return $result;
110 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
111 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
113 * @param $title String: the text of the title
114 * @param $text String: link text
115 * @param $query String: optional query part
116 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
117 * be included in the link text. Other characters will be appended after
118 * the end of the link.
120 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
121 $nt = Title::newFromText( $title );
122 if ($nt) {
123 return $this->makeKnownLinkObj( Title::newFromText( $title ), $text, $query, $trail, $prefix , $aprops );
124 } else {
125 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
126 return $text == '' ? $title : $text;
131 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
132 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
134 * @param string $title The text of the title
135 * @param string $text Link text
136 * @param string $query Optional query part
137 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
138 * be included in the link text. Other characters will be appended after
139 * the end of the link.
141 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
142 $nt = Title::newFromText( $title );
143 if ($nt) {
144 return $this->makeBrokenLinkObj( Title::newFromText( $title ), $text, $query, $trail );
145 } else {
146 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
147 return $text == '' ? $title : $text;
152 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
153 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
155 * @param $title String: the text of the title
156 * @param $text String: link text
157 * @param $query String: optional query part
158 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
159 * be included in the link text. Other characters will be appended after
160 * the end of the link.
162 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
163 $nt = Title::newFromText( $title );
164 if ($nt) {
165 return $this->makeStubLinkObj( Title::newFromText( $title ), $text, $query, $trail );
166 } else {
167 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
168 return $text == '' ? $title : $text;
173 * Make a link for a title which may or may not be in the database. If you need to
174 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
175 * call to this will result in a DB query.
177 * @param $nt Title: the title object to make the link from, e.g. from
178 * Title::newFromText.
179 * @param $text String: link text
180 * @param $query String: optional query part
181 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
182 * be included in the link text. Other characters will be appended after
183 * the end of the link.
184 * @param $prefix String: optional prefix. As trail, only before instead of after.
186 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
187 global $wgUser;
188 $fname = 'Linker::makeLinkObj';
189 wfProfileIn( $fname );
191 # Fail gracefully
192 if ( ! is_object($nt) ) {
193 # throw new MWException();
194 wfProfileOut( $fname );
195 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
198 if ( $nt->isExternal() ) {
199 $u = $nt->getFullURL();
200 $link = $nt->getPrefixedURL();
201 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
202 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
204 $inside = '';
205 if ( '' != $trail ) {
206 $m = array();
207 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
208 $inside = $m[1];
209 $trail = $m[2];
212 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
214 wfProfileOut( $fname );
215 return $t;
216 } elseif ( $nt->isAlwaysKnown() ) {
217 # Image links, special page links and self-links with fragements are always known.
218 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
219 } else {
220 wfProfileIn( $fname.'-immediate' );
221 # Work out link colour immediately
222 $aid = $nt->getArticleID() ;
223 if ( 0 == $aid ) {
224 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
225 } else {
226 $stub = false;
227 if ( $nt->isContentPage() ) {
228 $threshold = $wgUser->getOption('stubthreshold');
229 if ( $threshold > 0 ) {
230 $dbr = wfGetDB( DB_SLAVE );
231 $s = $dbr->selectRow(
232 array( 'page' ),
233 array( 'page_len',
234 'page_is_redirect' ),
235 array( 'page_id' => $aid ), $fname ) ;
236 $stub = ( $s !== false && !$s->page_is_redirect &&
237 $s->page_len < $threshold );
240 if ( $stub ) {
241 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
242 } else {
243 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
246 wfProfileOut( $fname.'-immediate' );
248 wfProfileOut( $fname );
249 return $retVal;
253 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
254 * it doesn't have to do a database query. It's also valid for interwiki titles and special
255 * pages.
257 * @param $nt Title object of target page
258 * @param $text String: text to replace the title
259 * @param $query String: link target
260 * @param $trail String: text after link
261 * @param $prefix String: text before link text
262 * @param $aprops String: extra attributes to the a-element
263 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
264 * @return the a-element
266 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
268 $fname = 'Linker::makeKnownLinkObj';
269 wfProfileIn( $fname );
271 if ( !is_object( $nt ) ) {
272 wfProfileOut( $fname );
273 return $text;
276 $u = $nt->escapeLocalURL( $query );
277 if ( $nt->getFragment() != '' ) {
278 if( $nt->getPrefixedDbkey() == '' ) {
279 $u = '';
280 if ( '' == $text ) {
281 $text = htmlspecialchars( $nt->getFragment() );
284 $u .= $nt->getFragmentForURL();
286 if ( $text == '' ) {
287 $text = htmlspecialchars( $nt->getPrefixedText() );
289 if ( $style == '' ) {
290 $style = $this->getInternalLinkAttributesObj( $nt, $text );
293 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
295 list( $inside, $trail ) = Linker::splitTrail( $trail );
296 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
297 wfProfileOut( $fname );
298 return $r;
302 * Make a red link to the edit page of a given title.
304 * @param $title String: The text of the title
305 * @param $text String: Link text
306 * @param $query String: Optional query part
307 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
308 * be included in the link text. Other characters will be appended after
309 * the end of the link.
311 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
312 # Fail gracefully
313 if ( ! isset($nt) ) {
314 # throw new MWException();
315 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
318 $fname = 'Linker::makeBrokenLinkObj';
319 wfProfileIn( $fname );
321 if ( '' == $query ) {
322 $q = 'action=edit';
323 } else {
324 $q = 'action=edit&'.$query;
326 $u = $nt->escapeLocalURL( $q );
328 if ( '' == $text ) {
329 $text = htmlspecialchars( $nt->getPrefixedText() );
331 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
333 list( $inside, $trail ) = Linker::splitTrail( $trail );
334 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
336 wfProfileOut( $fname );
337 return $s;
341 * Make a brown link to a short article.
343 * @param $title String: the text of the title
344 * @param $text String: link text
345 * @param $query String: optional query part
346 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
347 * be included in the link text. Other characters will be appended after
348 * the end of the link.
350 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
351 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
352 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
356 * Generate either a normal exists-style link or a stub link, depending
357 * on the given page size.
359 * @param $size Integer
360 * @param $nt Title object.
361 * @param $text String
362 * @param $query String
363 * @param $trail String
364 * @param $prefix String
365 * @return string HTML of link
367 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
368 global $wgUser;
369 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
370 if( $size < $threshold ) {
371 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
372 } else {
373 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
377 /**
378 * Make appropriate markup for a link to the current article. This is currently rendered
379 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
380 * despite $query not being used.
382 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
383 if ( '' == $text ) {
384 $text = htmlspecialchars( $nt->getPrefixedText() );
386 list( $inside, $trail ) = Linker::splitTrail( $trail );
387 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
390 /** @todo document */
391 function fnamePart( $url ) {
392 $basename = strrchr( $url, '/' );
393 if ( false === $basename ) {
394 $basename = $url;
395 } else {
396 $basename = substr( $basename, 1 );
398 return htmlspecialchars( $basename );
401 /** Obsolete alias */
402 function makeImage( $url, $alt = '' ) {
403 return $this->makeExternalImage( $url, $alt );
406 /** @todo document */
407 function makeExternalImage( $url, $alt = '' ) {
408 if ( '' == $alt ) {
409 $alt = $this->fnamePart( $url );
411 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
412 return $s;
415 /** @todo document */
416 function makeImageLinkObj( $nt, $label, $alt, $align = '', $params = array(), $framed = false,
417 $thumb = false, $manual_thumb = '', $valign = '' )
419 global $wgContLang, $wgUser, $wgThumbLimits;
421 $img = new Image( $nt );
423 if ( !$img->allowInlineDisplay() && $img->exists() ) {
424 return $this->makeKnownLinkObj( $nt );
427 $error = $prefix = $postfix = '';
428 $page = isset( $params['page'] ) ? $params['page'] : false;
430 if ( 'center' == $align )
432 $prefix = '<div class="center">';
433 $postfix = '</div>';
434 $align = 'none';
437 if ( !isset( $params['width'] ) ) {
438 $params['width'] = $img->getWidth( $page );
439 if( $thumb || $framed ) {
440 $wopt = $wgUser->getOption( 'thumbsize' );
442 if( !isset( $wgThumbLimits[$wopt] ) ) {
443 $wopt = User::getDefaultOption( 'thumbsize' );
446 $params['width'] = min( $params['width'], $wgThumbLimits[$wopt] );
450 if ( $thumb || $framed ) {
452 # Create a thumbnail. Alignment depends on language
453 # writing direction, # right aligned for left-to-right-
454 # languages ("Western languages"), left-aligned
455 # for right-to-left-languages ("Semitic languages")
457 # If thumbnail width has not been provided, it is set
458 # to the default user option as specified in Language*.php
459 if ( $align == '' ) {
460 $align = $wgContLang->isRTL() ? 'left' : 'right';
462 return $prefix.$this->makeThumbLinkObj( $img, $label, $alt, $align, $params, $framed, $manual_thumb ).$postfix;
465 if ( $params['width'] && $img->exists() ) {
466 # Create a resized image, without the additional thumbnail features
467 $thumb = $img->transform( $params );
468 } else {
469 $thumb = false;
472 if ( $page ) {
473 $query = 'page=' . urlencode( $page );
474 } else {
475 $query = '';
477 $u = $nt->getLocalURL( $query );
478 $imgAttribs = array(
479 'alt' => $alt,
480 'longdesc' => $u
482 if ( $valign ) {
483 $imgAttribs['style'] = "vertical-align: $valign";
485 $linkAttribs = array(
486 'href' => $u,
487 'class' => 'image',
488 'title' => $alt
491 if ( !$thumb ) {
492 $s = $this->makeBrokenImageLinkObj( $img->getTitle() );
493 } else {
494 $s = $thumb->toHtml( $imgAttribs, $linkAttribs );
496 if ( '' != $align ) {
497 $s = "<div class=\"float{$align}\"><span>{$s}</span></div>";
499 return str_replace("\n", ' ',$prefix.$s.$postfix);
503 * Make HTML for a thumbnail including image, border and caption
504 * $img is an Image object
506 function makeThumbLinkObj( $img, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manual_thumb = "" ) {
507 global $wgStylePath, $wgContLang;
509 $page = isset( $params['page'] ) ? $params['page'] : false;
511 if ( empty( $params['width'] ) ) {
512 $params['width'] = 180;
514 $thumb = false;
515 if ( $manual_thumb != '' ) {
516 # Use manually specified thumbnail
517 $manual_title = Title::makeTitleSafe( NS_IMAGE, $manual_thumb );
518 if( $manual_title ) {
519 $manual_img = new Image( $manual_title );
520 $thumb = $manual_img->getUnscaledThumb();
522 } elseif ( $framed ) {
523 // Use image dimensions, don't scale
524 $thumb = $img->getUnscaledThumb( $page );
525 } else {
526 # Do not present an image bigger than the source, for bitmap-style images
527 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
528 $srcWidth = $img->getWidth( $page );
529 if ( $srcWidth && !$img->mustRender() && $params['width'] > $srcWidth ) {
530 $params['width'] = $srcWidth;
532 $thumb = $img->transform( $params );
535 if ( $thumb ) {
536 $outerWidth = $thumb->getWidth() + 2;
537 } else {
538 $outerWidth = $params['width'] + 2;
541 $query = $page ? 'page=' . urlencode( $page ) : '';
542 $u = $img->getTitle()->getLocalURL( $query );
544 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
545 $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
546 $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
548 $s = "<div class=\"thumb t{$align}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
549 if ( !$thumb ) {
550 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
551 $zoomicon = '';
552 } elseif( !$img->exists() ) {
553 $s .= $this->makeBrokenImageLinkObj( $img->getTitle() );
554 $zoomicon = '';
555 } else {
556 $imgAttribs = array(
557 'alt' => $alt,
558 'longdesc' => $u,
559 'class' => 'thumbimage'
561 $linkAttribs = array(
562 'href' => $u,
563 'class' => 'internal',
564 'title' => $alt
567 $s .= $thumb->toHtml( $imgAttribs, $linkAttribs );
568 if ( $framed ) {
569 $zoomicon="";
570 } else {
571 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
572 '<a href="'.$u.'" class="internal" title="'.$more.'">'.
573 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
574 'width="15" height="11" alt="" /></a></div>';
577 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$label."</div></div></div>";
578 return str_replace("\n", ' ', $s);
582 * Pass a title object, not a title string
584 function makeBrokenImageLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
585 # Fail gracefully
586 if ( ! isset($nt) ) {
587 # throw new MWException();
588 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
591 $fname = 'Linker::makeBrokenImageLinkObj';
592 wfProfileIn( $fname );
594 $q = 'wpDestFile=' . urlencode( $nt->getDBkey() );
595 if ( '' != $query ) {
596 $q .= "&$query";
598 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
599 $url = $uploadTitle->escapeLocalURL( $q );
601 if ( '' == $text ) {
602 $text = htmlspecialchars( $nt->getPrefixedText() );
604 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
605 list( $inside, $trail ) = Linker::splitTrail( $trail );
606 $s = "<a href=\"{$url}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
608 wfProfileOut( $fname );
609 return $s;
612 /** @todo document */
613 function makeMediaLink( $name, /* wtf?! */ $url, $alt = '' ) {
614 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
615 return $this->makeMediaLinkObj( $nt, $alt );
619 * Create a direct link to a given uploaded file.
621 * @param $title Title object.
622 * @param $text String: pre-sanitized HTML
623 * @return string HTML
625 * @public
626 * @todo Handle invalid or missing images better.
628 function makeMediaLinkObj( $title, $text = '' ) {
629 if( is_null( $title ) ) {
630 ### HOTFIX. Instead of breaking, return empty string.
631 return $text;
632 } else {
633 $img = new Image( $title );
634 if( $img->exists() ) {
635 $url = $img->getURL();
636 $class = 'internal';
637 } else {
638 $upload = SpecialPage::getTitleFor( 'Upload' );
639 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $img->getName() ) );
640 $class = 'new';
642 $alt = htmlspecialchars( $title->getText() );
643 if( $text == '' ) {
644 $text = $alt;
646 $u = htmlspecialchars( $url );
647 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
651 /** @todo document */
652 function specialLink( $name, $key = '' ) {
653 global $wgContLang;
655 if ( '' == $key ) { $key = strtolower( $name ); }
656 $pn = $wgContLang->ucfirst( $name );
657 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
658 wfMsg( $key ) );
661 /** @todo document */
662 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
663 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
664 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
665 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
666 $style .= ' rel="nofollow"';
668 $url = htmlspecialchars( $url );
669 if( $escape ) {
670 $text = htmlspecialchars( $text );
672 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
676 * Make user link (or user contributions for unregistered users)
677 * @param $userId Integer: user id in database.
678 * @param $userText String: user name in database
679 * @return string HTML fragment
680 * @private
682 function userLink( $userId, $userText ) {
683 $encName = htmlspecialchars( $userText );
684 if( $userId == 0 ) {
685 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
686 return $this->makeKnownLinkObj( $contribsPage,
687 $encName);
688 } else {
689 $userPage = Title::makeTitle( NS_USER, $userText );
690 return $this->makeLinkObj( $userPage, $encName );
695 * @param $userId Integer: user id in database.
696 * @param $userText String: user name in database.
697 * @param $redContribsWhenNoEdits Bool: return a red contribs link when the user had no edits and this is true.
698 * @return string HTML fragment with talk and/or block links
700 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false ) {
701 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
702 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
703 $blockable = ( $wgSysopUserBans || 0 == $userId );
705 $items = array();
706 if( $talkable ) {
707 $items[] = $this->userTalkLink( $userId, $userText );
709 if( $userId ) {
710 // check if the user has an edit
711 if( $redContribsWhenNoEdits && User::edits( $userId ) == 0 ) {
712 $style = "class='new'";
713 } else {
714 $style = '';
716 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
718 $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
720 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
721 $items[] = $this->blockLink( $userId, $userText );
724 if( $items ) {
725 return ' (' . implode( ' | ', $items ) . ')';
726 } else {
727 return '';
732 * Alias for userToolLinks( $userId, $userText, true );
734 public function userToolLinksRedContribs( $userId, $userText ) {
735 return $this->userToolLinks( $userId, $userText, true );
740 * @param $userId Integer: user id in database.
741 * @param $userText String: user name in database.
742 * @return string HTML fragment with user talk link
743 * @private
745 function userTalkLink( $userId, $userText ) {
746 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
747 $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
748 return $userTalkLink;
752 * @param $userId Integer: userid
753 * @param $userText String: user name in database.
754 * @return string HTML fragment with block link
755 * @private
757 function blockLink( $userId, $userText ) {
758 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
759 $blockLink = $this->makeKnownLinkObj( $blockPage,
760 wfMsgHtml( 'blocklink' ) );
761 return $blockLink;
765 * Generate a user link if the current user is allowed to view it
766 * @param $rev Revision object.
767 * @return string HTML
769 function revUserLink( $rev ) {
770 if( $rev->userCan( Revision::DELETED_USER ) ) {
771 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
772 } else {
773 $link = wfMsgHtml( 'rev-deleted-user' );
775 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
776 return '<span class="history-deleted">' . $link . '</span>';
778 return $link;
782 * Generate a user tool link cluster if the current user is allowed to view it
783 * @param $rev Revision object.
784 * @return string HTML
786 function revUserTools( $rev ) {
787 if( $rev->userCan( Revision::DELETED_USER ) ) {
788 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
789 ' ' .
790 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
791 } else {
792 $link = wfMsgHtml( 'rev-deleted-user' );
794 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
795 return '<span class="history-deleted">' . $link . '</span>';
797 return $link;
801 * This function is called by all recent changes variants, by the page history,
802 * and by the user contributions list. It is responsible for formatting edit
803 * comments. It escapes any HTML in the comment, but adds some CSS to format
804 * auto-generated comments (from section editing) and formats [[wikilinks]].
806 * @author Erik Moeller <moeller@scireview.de>
808 * Note: there's not always a title to pass to this function.
809 * Since you can't set a default parameter for a reference, I've turned it
810 * temporarily to a value pass. Should be adjusted further. --brion
812 * @param string $comment
813 * @param mixed $title Title object (to generate link to the section in autocomment) or null
814 * @param bool $local Whether section links should refer to local page
816 function formatComment($comment, $title = NULL, $local = false) {
817 wfProfileIn( __METHOD__ );
819 # Sanitize text a bit:
820 $comment = str_replace( "\n", " ", $comment );
821 $comment = htmlspecialchars( $comment );
823 # Render autocomments and make links:
824 $comment = $this->formatAutoComments( $comment, $title, $local );
825 $comment = $this->formatLinksInComment( $comment );
827 wfProfileOut( __METHOD__ );
828 return $comment;
832 * The pattern for autogen comments is / * foo * /, which makes for
833 * some nasty regex.
834 * We look for all comments, match any text before and after the comment,
835 * add a separator where needed and format the comment itself with CSS
836 * Called by Linker::formatComment.
838 * @param $comment Comment text
839 * @param $title An optional title object used to links to sections
841 * @todo Document the $local parameter.
843 private function formatAutocomments( $comment, $title = NULL, $local = false ) {
844 $match = array();
845 while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
846 $pre=$match[1];
847 $auto=$match[2];
848 $post=$match[3];
849 $link='';
850 if( $title ) {
851 $section = $auto;
853 # Generate a valid anchor name from the section title.
854 # Hackish, but should generally work - we strip wiki
855 # syntax, including the magic [[: that is used to
856 # "link rather than show" in case of images and
857 # interlanguage links.
858 $section = str_replace( '[[:', '', $section );
859 $section = str_replace( '[[', '', $section );
860 $section = str_replace( ']]', '', $section );
861 if ( $local ) {
862 $sectionTitle = Title::newFromText( '#' . $section);
863 } else {
864 $sectionTitle = wfClone( $title );
865 $sectionTitle->mFragment = $section;
867 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
869 $sep='-';
870 $auto=$link.$auto;
871 if($pre) { $auto = $sep.' '.$auto; }
872 if($post) { $auto .= ' '.$sep; }
873 $auto='<span class="autocomment">'.$auto.'</span>';
874 $comment=$pre.$auto.$post;
877 return $comment;
881 * Format regular and media links - all other wiki formatting is ignored
882 * Called by Linker::formatComment.
883 * @param $comment The comment text.
884 * @return Comment text with links using HTML.
886 private function formatLinksInComment( $comment ) {
887 global $wgContLang;
889 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
890 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
892 while(preg_match('/\[\[:?(.*?)(\|(.*?))*\]\](.*)$/',$comment,$match)) {
893 # Handle link renaming [[foo|text]] will show link as "text"
894 if( "" != $match[3] ) {
895 $text = $match[3];
896 } else {
897 $text = $match[1];
899 $submatch = array();
900 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
901 # Media link; trail not supported.
902 $linkRegexp = '/\[\[(.*?)\]\]/';
903 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
904 } else {
905 # Other kind of link
906 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
907 $trail = $submatch[1];
908 } else {
909 $trail = "";
911 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
912 if (isset($match[1][0]) && $match[1][0] == ':')
913 $match[1] = substr($match[1], 1);
914 $thelink = $this->makeLink( $match[1], $text, "", $trail );
916 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
919 return $comment;
923 * Wrap a comment in standard punctuation and formatting if
924 * it's non-empty, otherwise return empty string.
926 * @param string $comment
927 * @param mixed $title Title object (to generate link to section in autocomment) or null
928 * @param bool $local Whether section links should refer to local page
930 * @return string
932 function commentBlock( $comment, $title = NULL, $local = false ) {
933 // '*' used to be the comment inserted by the software way back
934 // in antiquity in case none was provided, here for backwards
935 // compatability, acc. to brion -ævar
936 if( $comment == '' || $comment == '*' ) {
937 return '';
938 } else {
939 $formatted = $this->formatComment( $comment, $title, $local );
940 return " <span class=\"comment\">($formatted)</span>";
945 * Wrap and format the given revision's comment block, if the current
946 * user is allowed to view it.
948 * @param Revision $rev
949 * @param bool $local Whether section links should refer to local page
950 * @return string HTML
952 function revComment( Revision $rev, $local = false ) {
953 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
954 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
955 } else {
956 $block = " <span class=\"comment\">" .
957 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
959 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
960 return " <span class=\"history-deleted\">$block</span>";
962 return $block;
965 /** @todo document */
966 function tocIndent() {
967 return "\n<ul>";
970 /** @todo document */
971 function tocUnindent($level) {
972 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
976 * parameter level defines if we are on an indentation level
978 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
979 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
980 $anchor . '"><span class="tocnumber">' .
981 $tocnumber . '</span> <span class="toctext">' .
982 $tocline . '</span></a>';
985 /** @todo document */
986 function tocLineEnd() {
987 return "</li>\n";
990 /** @todo document */
991 function tocList($toc) {
992 global $wgJsMimeType;
993 $title = wfMsgHtml('toc') ;
994 return
995 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
996 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
997 . $toc
998 # no trailing newline, script should not be wrapped in a
999 # paragraph
1000 . "</ul>\n</td></tr></table>"
1001 . '<script type="' . $wgJsMimeType . '">'
1002 . ' if (window.showTocToggle) {'
1003 . ' var tocShowText = "' . wfEscapeJsString( wfMsg('showtoc') ) . '";'
1004 . ' var tocHideText = "' . wfEscapeJsString( wfMsg('hidetoc') ) . '";'
1005 . ' showTocToggle();'
1006 . ' } '
1007 . "</script>\n";
1010 /** @todo document */
1011 public function editSectionLinkForOther( $title, $section ) {
1012 global $wgContLang;
1014 $title = Title::newFromText( $title );
1015 $editurl = '&section='.$section;
1016 $url = $this->makeKnownLinkObj( $title, wfMsg('editsection'), 'action=edit'.$editurl );
1018 return "<span class=\"editsection\">[".$url."]</span>";
1023 * @param $title Title object.
1024 * @param $section Integer: section number.
1025 * @param $hint Link String: title, or default if omitted or empty
1027 public function editSectionLink( $nt, $section, $hint='' ) {
1028 global $wgContLang;
1030 $editurl = '&section='.$section;
1031 $hint = ( $hint=='' ) ? '' : ' title="' . wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) ) . '"';
1032 $url = $this->makeKnownLinkObj( $nt, wfMsg('editsection'), 'action=edit'.$editurl, '', '', '', $hint );
1034 return "<span class=\"editsection\">[".$url."]</span>";
1038 * Create a headline for content
1040 * @param int $level The level of the headline (1-6)
1041 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1042 * This *must* be at least '>' for no attribs
1043 * @param string $anchor The anchor to give the headline (the bit after the #)
1044 * @param string $text The text of the header
1045 * @param string $link HTML to add for the section edit link
1047 * @return string HTML headline
1049 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1050 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1054 * Split a link trail, return the "inside" portion and the remainder of the trail
1055 * as a two-element array
1057 * @static
1059 static function splitTrail( $trail ) {
1060 static $regex = false;
1061 if ( $regex === false ) {
1062 global $wgContLang;
1063 $regex = $wgContLang->linkTrail();
1065 $inside = '';
1066 if ( '' != $trail ) {
1067 $m = array();
1068 if ( preg_match( $regex, $trail, $m ) ) {
1069 $inside = $m[1];
1070 $trail = $m[2];
1073 return array( $inside, $trail );
1077 * Generate a rollback link for a given revision. Currently it's the
1078 * caller's responsibility to ensure that the revision is the top one. If
1079 * it's not, of course, the user will get an error message.
1081 * If the calling page is called with the parameter &bot=1, all rollback
1082 * links also get that parameter. It causes the edit itself and the rollback
1083 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1084 * changes, so this allows sysops to combat a busy vandal without bothering
1085 * other users.
1087 * @param Revision $rev
1089 function generateRollback( $rev ) {
1090 global $wgUser, $wgRequest;
1091 $title = $rev->getTitle();
1093 $extraRollback = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
1094 $extraRollback .= '&token=' . urlencode(
1095 $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ) );
1096 return '<span class="mw-rollback-link">['. $this->makeKnownLinkObj( $title,
1097 wfMsg('rollbacklink'),
1098 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extraRollback ) .']</span>';
1102 * Returns HTML for the "templates used on this page" list.
1104 * @param array $templates Array of templates from Article::getUsedTemplate
1105 * or similar
1106 * @param bool $preview Whether this is for a preview
1107 * @param bool $section Whether this is for a section edit
1108 * @return string HTML output
1110 public function formatTemplates( $templates, $preview = false, $section = false) {
1111 global $wgUser;
1112 wfProfileIn( __METHOD__ );
1114 $sk = $wgUser->getSkin();
1116 $outText = '';
1117 if ( count( $templates ) > 0 ) {
1118 # Do a batch existence check
1119 $batch = new LinkBatch;
1120 foreach( $templates as $title ) {
1121 $batch->addObj( $title );
1123 $batch->execute();
1125 # Construct the HTML
1126 $outText = '<div class="mw-templatesUsedExplanation">';
1127 if ( $preview ) {
1128 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1129 } elseif ( $section ) {
1130 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1131 } else {
1132 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1134 $outText .= '</div><ul>';
1136 foreach ( $templates as $titleObj ) {
1137 $r = $titleObj->getRestrictions( 'edit' );
1138 if ( in_array( 'sysop', $r ) ) {
1139 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1140 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1141 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1142 } else {
1143 $protected = '';
1145 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1147 $outText .= '</ul>';
1149 wfProfileOut( __METHOD__ );
1150 return $outText;
1154 * Format a size in bytes for output, using an appropriate
1155 * unit (B, KB, MB or GB) according to the magnitude in question
1157 * @param $size Size to format
1158 * @return string
1160 public function formatSize( $size ) {
1161 global $wgLang;
1162 // For small sizes no decimal places necessary
1163 $round = 0;
1164 if( $size > 1024 ) {
1165 $size = $size / 1024;
1166 if( $size > 1024 ) {
1167 $size = $size / 1024;
1168 // For MB and bigger two decimal places are smarter
1169 $round = 2;
1170 if( $size > 1024 ) {
1171 $size = $size / 1024;
1172 $msg = 'size-gigabytes';
1173 } else {
1174 $msg = 'size-megabytes';
1176 } else {
1177 $msg = 'size-kilobytes';
1179 } else {
1180 $msg = 'size-bytes';
1182 $size = round( $size, $round );
1183 return wfMsgHtml( $msg, $wgLang->formatNum( $size ) );
1187 * Given the id of an interface element, constructs the appropriate title
1188 * and accesskey attributes from the system messages. (Note, this is usu-
1189 * ally the id but isn't always, because sometimes the accesskey needs to
1190 * go on a different element than the id, for reverse-compatibility, etc.)
1192 * @param string $name Id of the element, minus prefixes.
1193 * @return string title and accesskey attributes, ready to drop in an
1194 * element (e.g., ' title="This does something [x]" accesskey="x"').
1196 public function tooltipAndAccesskey($name) {
1197 $out = '';
1199 $tooltip = wfMsg('tooltip-'.$name);
1200 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1201 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1202 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1203 $out .= ' title="'.htmlspecialchars($tooltip);
1205 $accesskey = wfMsg('accesskey-'.$name);
1206 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1207 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1208 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1209 } elseif ($out) {
1210 $out .= '"';
1212 return $out;
1216 * Given the id of an interface element, constructs the appropriate title
1217 * attribute from the system messages. (Note, this is usually the id but
1218 * isn't always, because sometimes the accesskey needs to go on a different
1219 * element than the id, for reverse-compatibility, etc.)
1221 * @param string $name Id of the element, minus prefixes.
1222 * @return string title attribute, ready to drop in an element
1223 * (e.g., ' title="This does something"').
1225 public function tooltip($name) {
1226 $out = '';
1228 $tooltip = wfMsg('tooltip-'.$name);
1229 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1230 $out = ' title="'.htmlspecialchars($tooltip).'"';
1233 return $out;