Ajax show editors message moved to the extension repository (r19556)
[mediawiki.git] / includes / Linker.php
blob42ef97ea81129427b641136ca58e4bf2b086387d
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 */
9 /**
10 * For the moment, Skin is a descendent class of Linker.
11 * In the future, it should probably be further split
12 * so that ever other bit of the wiki doesn't have to
13 * go loading up Skin to get at it.
16 class Linker {
17 function __construct() {}
19 /**
20 * @deprecated
22 function postParseLinkColour( $s = NULL ) {
23 return NULL;
26 /** @todo document */
27 function getExternalLinkAttributes( $link, $text, $class='' ) {
28 $link = htmlspecialchars( $link );
30 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
32 $r .= " title=\"{$link}\"";
33 return $r;
36 function getInterwikiLinkAttributes( $link, $text, $class='' ) {
37 global $wgContLang;
39 $link = urldecode( $link );
40 $link = $wgContLang->checkTitleEncoding( $link );
41 $link = preg_replace( '/[\\x00-\\x1f]/', ' ', $link );
42 $link = htmlspecialchars( $link );
44 $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
46 $r .= " title=\"{$link}\"";
47 return $r;
50 /** @todo document */
51 function getInternalLinkAttributes( $link, $text, $broken = false ) {
52 $link = urldecode( $link );
53 $link = str_replace( '_', ' ', $link );
54 $link = htmlspecialchars( $link );
56 if( $broken == 'stub' ) {
57 $r = ' class="stub"';
58 } else if ( $broken == 'yes' ) {
59 $r = ' class="new"';
60 } else {
61 $r = '';
64 $r .= " title=\"{$link}\"";
65 return $r;
68 /**
69 * @param $nt Title object.
70 * @param $text String: FIXME
71 * @param $broken Boolean: FIXME, default 'false'.
73 function getInternalLinkAttributesObj( &$nt, $text, $broken = false ) {
74 if( $broken == 'stub' ) {
75 $r = ' class="stub"';
76 } else if ( $broken == 'yes' ) {
77 $r = ' class="new"';
78 } else {
79 $r = '';
82 $r .= ' title="' . $nt->getEscapedText() . '"';
83 return $r;
86 /**
87 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
88 * it if you already have a title object handy. See makeLinkObj for further documentation.
90 * @param $title String: the text of the title
91 * @param $text String: link text
92 * @param $query String: optional query part
93 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
94 * be included in the link text. Other characters will be appended after
95 * the end of the link.
97 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
98 wfProfileIn( 'Linker::makeLink' );
99 $nt = Title::newFromText( $title );
100 if ($nt) {
101 $result = $this->makeLinkObj( Title::newFromText( $title ), $text, $query, $trail );
102 } else {
103 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
104 $result = $text == "" ? $title : $text;
107 wfProfileOut( 'Linker::makeLink' );
108 return $result;
112 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
113 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
115 * @param $title String: the text of the title
116 * @param $text String: link text
117 * @param $query String: optional query part
118 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
119 * be included in the link text. Other characters will be appended after
120 * the end of the link.
122 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
123 $nt = Title::newFromText( $title );
124 if ($nt) {
125 return $this->makeKnownLinkObj( Title::newFromText( $title ), $text, $query, $trail, $prefix , $aprops );
126 } else {
127 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
128 return $text == '' ? $title : $text;
133 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
134 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
136 * @param string $title The text of the title
137 * @param string $text Link text
138 * @param string $query Optional query part
139 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
140 * be included in the link text. Other characters will be appended after
141 * the end of the link.
143 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
144 $nt = Title::newFromText( $title );
145 if ($nt) {
146 return $this->makeBrokenLinkObj( Title::newFromText( $title ), $text, $query, $trail );
147 } else {
148 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
149 return $text == '' ? $title : $text;
154 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
155 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
157 * @param $title String: the text of the title
158 * @param $text String: link text
159 * @param $query String: optional query part
160 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
161 * be included in the link text. Other characters will be appended after
162 * the end of the link.
164 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
165 $nt = Title::newFromText( $title );
166 if ($nt) {
167 return $this->makeStubLinkObj( Title::newFromText( $title ), $text, $query, $trail );
168 } else {
169 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
170 return $text == '' ? $title : $text;
175 * Make a link for a title which may or may not be in the database. If you need to
176 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
177 * call to this will result in a DB query.
179 * @param $nt Title: the title object to make the link from, e.g. from
180 * Title::newFromText.
181 * @param $text String: link text
182 * @param $query String: optional query part
183 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
184 * be included in the link text. Other characters will be appended after
185 * the end of the link.
186 * @param $prefix String: optional prefix. As trail, only before instead of after.
188 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
189 global $wgUser;
190 $fname = 'Linker::makeLinkObj';
191 wfProfileIn( $fname );
193 # Fail gracefully
194 if ( ! is_object($nt) ) {
195 # throw new MWException();
196 wfProfileOut( $fname );
197 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
200 if ( $nt->isExternal() ) {
201 $u = $nt->getFullURL();
202 $link = $nt->getPrefixedURL();
203 if ( '' == $text ) { $text = $nt->getPrefixedText(); }
204 $style = $this->getInterwikiLinkAttributes( $link, $text, 'extiw' );
206 $inside = '';
207 if ( '' != $trail ) {
208 $m = array();
209 if ( preg_match( '/^([a-z]+)(.*)$$/sD', $trail, $m ) ) {
210 $inside = $m[1];
211 $trail = $m[2];
214 $t = "<a href=\"{$u}\"{$style}>{$text}{$inside}</a>";
216 wfProfileOut( $fname );
217 return $t;
218 } elseif ( $nt->isAlwaysKnown() ) {
219 # Image links, special page links and self-links with fragements are always known.
220 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
221 } else {
222 wfProfileIn( $fname.'-immediate' );
223 # Work out link colour immediately
224 $aid = $nt->getArticleID() ;
225 if ( 0 == $aid ) {
226 $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
227 } else {
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_namespace',
235 'page_is_redirect' ),
236 array( 'page_id' => $aid ), $fname ) ;
237 if ( $s !== false ) {
238 $size = $s->page_len;
239 if ( $s->page_is_redirect OR $s->page_namespace != NS_MAIN ) {
240 $size = $threshold*2 ; # Really big
242 } else {
243 $size = $threshold*2 ; # Really big
245 } else {
246 $size = 1 ;
248 if ( $size < $threshold ) {
249 $retVal = $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
250 } else {
251 $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
254 wfProfileOut( $fname.'-immediate' );
256 wfProfileOut( $fname );
257 return $retVal;
261 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
262 * it doesn't have to do a database query. It's also valid for interwiki titles and special
263 * pages.
265 * @param $nt Title object of target page
266 * @param $text String: text to replace the title
267 * @param $query String: link target
268 * @param $trail String: text after link
269 * @param $prefix String: text before link text
270 * @param $aprops String: extra attributes to the a-element
271 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
272 * @return the a-element
274 function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
276 $fname = 'Linker::makeKnownLinkObj';
277 wfProfileIn( $fname );
279 if ( !is_object( $nt ) ) {
280 wfProfileOut( $fname );
281 return $text;
284 $u = $nt->escapeLocalURL( $query );
285 if ( $nt->getFragment() != '' ) {
286 if( $nt->getPrefixedDbkey() == '' ) {
287 $u = '';
288 if ( '' == $text ) {
289 $text = htmlspecialchars( $nt->getFragment() );
292 $u .= $nt->getFragmentForURL();
294 if ( $text == '' ) {
295 $text = htmlspecialchars( $nt->getPrefixedText() );
297 if ( $style == '' ) {
298 $style = $this->getInternalLinkAttributesObj( $nt, $text );
301 if ( $aprops !== '' ) $aprops = ' ' . $aprops;
303 list( $inside, $trail ) = Linker::splitTrail( $trail );
304 $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
305 wfProfileOut( $fname );
306 return $r;
310 * Make a red link to the edit page of a given title.
312 * @param $title String: The text of the title
313 * @param $text String: Link text
314 * @param $query String: Optional query part
315 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
316 * be included in the link text. Other characters will be appended after
317 * the end of the link.
319 function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
320 # Fail gracefully
321 if ( ! isset($nt) ) {
322 # throw new MWException();
323 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
326 $fname = 'Linker::makeBrokenLinkObj';
327 wfProfileIn( $fname );
329 if ( '' == $query ) {
330 $q = 'action=edit';
331 } else {
332 $q = 'action=edit&'.$query;
334 $u = $nt->escapeLocalURL( $q );
336 if ( '' == $text ) {
337 $text = htmlspecialchars( $nt->getPrefixedText() );
339 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
341 list( $inside, $trail ) = Linker::splitTrail( $trail );
342 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
344 wfProfileOut( $fname );
345 return $s;
349 * Make a brown link to a short article.
351 * @param $title String: the text of the title
352 * @param $text String: link text
353 * @param $query String: optional query part
354 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
355 * be included in the link text. Other characters will be appended after
356 * the end of the link.
358 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
359 $u = $nt->escapeLocalURL( $query );
361 if ( '' == $text ) {
362 $text = htmlspecialchars( $nt->getPrefixedText() );
364 $style = $this->getInternalLinkAttributesObj( $nt, $text, 'stub' );
366 list( $inside, $trail ) = Linker::splitTrail( $trail );
367 $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
368 return $s;
372 * Generate either a normal exists-style link or a stub link, depending
373 * on the given page size.
375 * @param $size Integer
376 * @param $nt Title object.
377 * @param $text String
378 * @param $query String
379 * @param $trail String
380 * @param $prefix String
381 * @return string HTML of link
383 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
384 global $wgUser;
385 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
386 if( $size < $threshold ) {
387 return $this->makeStubLinkObj( $nt, $text, $query, $trail, $prefix );
388 } else {
389 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
393 /**
394 * Make appropriate markup for a link to the current article. This is currently rendered
395 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
396 * despite $query not being used.
398 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
399 if ( '' == $text ) {
400 $text = htmlspecialchars( $nt->getPrefixedText() );
402 list( $inside, $trail ) = Linker::splitTrail( $trail );
403 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
406 /** @todo document */
407 function fnamePart( $url ) {
408 $basename = strrchr( $url, '/' );
409 if ( false === $basename ) {
410 $basename = $url;
411 } else {
412 $basename = substr( $basename, 1 );
414 return htmlspecialchars( $basename );
417 /** Obsolete alias */
418 function makeImage( $url, $alt = '' ) {
419 return $this->makeExternalImage( $url, $alt );
422 /** @todo document */
423 function makeExternalImage( $url, $alt = '' ) {
424 if ( '' == $alt ) {
425 $alt = $this->fnamePart( $url );
427 $s = '<img src="'.$url.'" alt="'.$alt.'" />';
428 return $s;
431 /** @todo document */
432 function makeImageLinkObj( $nt, $label, $alt, $align = '', $width = false, $height = false, $framed = false,
433 $thumb = false, $manual_thumb = '', $page = null )
435 global $wgContLang, $wgUser, $wgThumbLimits, $wgGenerateThumbnailOnParse;
437 $img = new Image( $nt );
439 if ( ! is_null( $page ) ) {
440 $img->selectPage( $page );
443 if ( !$img->allowInlineDisplay() && $img->exists() ) {
444 return $this->makeKnownLinkObj( $nt );
447 $url = $img->getViewURL();
448 $error = $prefix = $postfix = '';
450 wfDebug( "makeImageLinkObj: '$width'x'$height', \"$label\"\n" );
452 if ( 'center' == $align )
454 $prefix = '<div class="center">';
455 $postfix = '</div>';
456 $align = 'none';
459 if ( $thumb || $framed ) {
461 # Create a thumbnail. Alignment depends on language
462 # writing direction, # right aligned for left-to-right-
463 # languages ("Western languages"), left-aligned
464 # for right-to-left-languages ("Semitic languages")
466 # If thumbnail width has not been provided, it is set
467 # to the default user option as specified in Language*.php
468 if ( $align == '' ) {
469 $align = $wgContLang->isRTL() ? 'left' : 'right';
473 if ( $width === false ) {
474 $wopt = $wgUser->getOption( 'thumbsize' );
476 if( !isset( $wgThumbLimits[$wopt] ) ) {
477 $wopt = User::getDefaultOption( 'thumbsize' );
480 $width = min( $img->getWidth(), $wgThumbLimits[$wopt] );
483 return $prefix.$this->makeThumbLinkObj( $img, $label, $alt, $align, $width, $height, $framed, $manual_thumb ).$postfix;
486 if ( $width && $img->exists() ) {
488 # Create a resized image, without the additional thumbnail
489 # features
491 if ( $height == false )
492 $height = -1;
493 if ( $manual_thumb == '') {
494 $thumb = $img->getThumbnail( $width, $height, $wgGenerateThumbnailOnParse );
495 if ( $thumb ) {
496 // In most cases, $width = $thumb->width or $height = $thumb->height.
497 // If not, we're scaling the image larger than it can be scaled,
498 // so we send to the browser a smaller thumbnail, and let the client do the scaling.
500 if ($height != -1 && $width > $thumb->width * $height / $thumb->height) {
501 // $height is the limiting factor, not $width
502 // set $width to the largest it can be, such that the resulting
503 // scaled height is at most $height
504 $width = floor($thumb->width * $height / $thumb->height);
506 $height = round($thumb->height * $width / $thumb->width);
508 wfDebug( "makeImageLinkObj: client-size set to '$width x $height'\n" );
509 $url = $thumb->getUrl();
510 } else {
511 $error = htmlspecialchars( $img->getLastError() );
512 // Do client-side scaling...
513 $height = intval( $img->getHeight() * $width / $img->getWidth() );
516 } else {
517 $width = $img->width;
518 $height = $img->height;
521 wfDebug( "makeImageLinkObj2: '$width'x'$height'\n" );
522 $u = $nt->escapeLocalURL();
523 if ( $error ) {
524 $s = $error;
525 } elseif ( $url == '' ) {
526 $s = $this->makeBrokenImageLinkObj( $img->getTitle() );
527 //$s .= "<br />{$alt}<br />{$url}<br />\n";
528 } else {
529 $s = '<a href="'.$u.'" class="image" title="'.$alt.'">' .
530 '<img src="'.$url.'" alt="'.$alt.'" ' .
531 ( $width
532 ? ( 'width="'.$width.'" height="'.$height.'" ' )
533 : '' ) .
534 'longdesc="'.$u.'" /></a>';
536 if ( '' != $align ) {
537 $s = "<div class=\"float{$align}\"><span>{$s}</span></div>";
539 return str_replace("\n", ' ',$prefix.$s.$postfix);
543 * Make HTML for a thumbnail including image, border and caption
544 * $img is an Image object
546 function makeThumbLinkObj( $img, $label = '', $alt, $align = 'right', $boxwidth = 180, $boxheight=false, $framed=false , $manual_thumb = "" ) {
547 global $wgStylePath, $wgContLang, $wgGenerateThumbnailOnParse;
548 $thumbUrl = '';
549 $error = '';
551 $width = $height = 0;
552 if ( $img->exists() ) {
553 $width = $img->getWidth();
554 $height = $img->getHeight();
556 if ( 0 == $width || 0 == $height ) {
557 $width = $height = 180;
559 if ( $boxwidth == 0 ) {
560 $boxwidth = 180;
562 if ( $framed ) {
563 // Use image dimensions, don't scale
564 $boxwidth = $width;
565 $boxheight = $height;
566 $thumbUrl = $img->getViewURL();
567 } else {
568 if ( $boxheight === false )
569 $boxheight = -1;
570 if ( '' == $manual_thumb ) {
571 $thumb = $img->getThumbnail( $boxwidth, $boxheight, $wgGenerateThumbnailOnParse );
572 if ( $thumb ) {
573 $thumbUrl = $thumb->getUrl();
574 $boxwidth = $thumb->width;
575 $boxheight = $thumb->height;
576 } else {
577 $error = $img->getLastError();
581 $oboxwidth = $boxwidth + 2;
583 if ( $manual_thumb != '' ) # Use manually specified thumbnail
585 $manual_title = Title::makeTitleSafe( NS_IMAGE, $manual_thumb ); #new Title ( $manual_thumb ) ;
586 if( $manual_title ) {
587 $manual_img = new Image( $manual_title );
588 $thumbUrl = $manual_img->getViewURL();
589 if ( $manual_img->exists() )
591 $width = $manual_img->getWidth();
592 $height = $manual_img->getHeight();
593 $boxwidth = $width ;
594 $boxheight = $height ;
595 $oboxwidth = $boxwidth + 2 ;
600 $u = $img->getEscapeLocalURL();
602 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
603 $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
604 $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
606 $s = "<div class=\"thumb t{$align}\"><div class=\"thumbinner\" style=\"width:{$oboxwidth}px;\">";
607 if( $thumbUrl == '' ) {
608 // Couldn't generate thumbnail? Scale the image client-side.
609 $thumbUrl = $img->getViewURL();
610 if( $boxheight == -1 ) {
611 // Approximate...
612 $boxheight = intval( $height * $boxwidth / $width );
615 if ( $error ) {
616 $s .= htmlspecialchars( $error );
617 $zoomicon = '';
618 } elseif( !$img->exists() ) {
619 $s .= $this->makeBrokenImageLinkObj( $img->getTitle() );
620 $zoomicon = '';
621 } else {
622 $s .= '<a href="'.$u.'" class="internal" title="'.$alt.'">'.
623 '<img src="'.$thumbUrl.'" alt="'.$alt.'" ' .
624 'width="'.$boxwidth.'" height="'.$boxheight.'" ' .
625 'longdesc="'.$u.'" class="thumbimage" /></a>';
626 if ( $framed ) {
627 $zoomicon="";
628 } else {
629 $zoomicon = '<div class="magnify" style="float:'.$magnifyalign.'">'.
630 '<a href="'.$u.'" class="internal" title="'.$more.'">'.
631 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
632 'width="15" height="11" alt="" /></a></div>';
635 $s .= ' <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$label."</div></div></div>";
636 return str_replace("\n", ' ', $s);
640 * Pass a title object, not a title string
642 function makeBrokenImageLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
643 # Fail gracefully
644 if ( ! isset($nt) ) {
645 # throw new MWException();
646 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
649 $fname = 'Linker::makeBrokenImageLinkObj';
650 wfProfileIn( $fname );
652 $q = 'wpDestFile=' . urlencode( $nt->getDBkey() );
653 if ( '' != $query ) {
654 $q .= "&$query";
656 $uploadTitle = SpecialPage::getTitleFor( 'Upload' );
657 $url = $uploadTitle->escapeLocalURL( $q );
659 if ( '' == $text ) {
660 $text = htmlspecialchars( $nt->getPrefixedText() );
662 $style = $this->getInternalLinkAttributesObj( $nt, $text, "yes" );
663 list( $inside, $trail ) = Linker::splitTrail( $trail );
664 $s = "<a href=\"{$url}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
666 wfProfileOut( $fname );
667 return $s;
670 /** @todo document */
671 function makeMediaLink( $name, /* wtf?! */ $url, $alt = '' ) {
672 $nt = Title::makeTitleSafe( NS_IMAGE, $name );
673 return $this->makeMediaLinkObj( $nt, $alt );
677 * Create a direct link to a given uploaded file.
679 * @param $title Title object.
680 * @param $text String: pre-sanitized HTML
681 * @param $nourl Boolean: Mask absolute URLs, so the parser doesn't
682 * linkify them (it is currently not context-aware)
683 * @return string HTML
685 * @public
686 * @todo Handle invalid or missing images better.
688 function makeMediaLinkObj( $title, $text = '' ) {
689 if( is_null( $title ) ) {
690 ### HOTFIX. Instead of breaking, return empty string.
691 return $text;
692 } else {
693 $img = new Image( $title );
694 if( $img->exists() ) {
695 $url = $img->getURL();
696 $class = 'internal';
697 } else {
698 $upload = SpecialPage::getTitleFor( 'Upload' );
699 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $img->getName() ) );
700 $class = 'new';
702 $alt = htmlspecialchars( $title->getText() );
703 if( $text == '' ) {
704 $text = $alt;
706 $u = htmlspecialchars( $url );
707 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
711 /** @todo document */
712 function specialLink( $name, $key = '' ) {
713 global $wgContLang;
715 if ( '' == $key ) { $key = strtolower( $name ); }
716 $pn = $wgContLang->ucfirst( $name );
717 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
718 wfMsg( $key ) );
721 /** @todo document */
722 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $ns = null ) {
723 $style = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
724 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
725 if( $wgNoFollowLinks && !(isset($ns) && in_array($ns, $wgNoFollowNsExceptions)) ) {
726 $style .= ' rel="nofollow"';
728 $url = htmlspecialchars( $url );
729 if( $escape ) {
730 $text = htmlspecialchars( $text );
732 return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
736 * Make user link (or user contributions for unregistered users)
737 * @param $userId Integer: user id in database.
738 * @param $userText String: user name in database
739 * @return string HTML fragment
740 * @private
742 function userLink( $userId, $userText ) {
743 $encName = htmlspecialchars( $userText );
744 if( $userId == 0 ) {
745 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
746 return $this->makeKnownLinkObj( $contribsPage,
747 $encName);
748 } else {
749 $userPage = Title::makeTitle( NS_USER, $userText );
750 return $this->makeLinkObj( $userPage, $encName );
755 * @param $userId Integer: user id in database.
756 * @param $userText String: user name in database.
757 * @return string HTML fragment with talk and/or block links
758 * @private
760 function userToolLinks( $userId, $userText ) {
761 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
762 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
763 $blockable = ( $wgSysopUserBans || 0 == $userId );
765 $items = array();
766 if( $talkable ) {
767 $items[] = $this->userTalkLink( $userId, $userText );
769 if( $userId ) {
770 // check if the user has an edit
771 if( User::edits( $userId ) == 0 ) {
772 $style = "class='new'";
773 } else {
774 $style = '';
776 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
777 $items[] = $this->makeKnownLinkObj( $contribsPage ,
778 wfMsgHtml( 'contribslink' ),
779 '', '', '', '', $style
782 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
783 $items[] = $this->blockLink( $userId, $userText );
786 if( $items ) {
787 return ' (' . implode( ' | ', $items ) . ')';
788 } else {
789 return '';
794 * @param $userId Integer: user id in database.
795 * @param $userText String: user name in database.
796 * @return string HTML fragment with user talk link
797 * @private
799 function userTalkLink( $userId, $userText ) {
800 global $wgLang;
801 $talkname = $wgLang->getNsText( NS_TALK ); # use the shorter name
803 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
804 $userTalkLink = $this->makeLinkObj( $userTalkPage, $talkname );
805 return $userTalkLink;
809 * @param $userId Integer: userid
810 * @param $userText String: user name in database.
811 * @return string HTML fragment with block link
812 * @private
814 function blockLink( $userId, $userText ) {
815 $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
816 $blockLink = $this->makeKnownLinkObj( $blockPage,
817 wfMsgHtml( 'blocklink' ) );
818 return $blockLink;
822 * Generate a user link if the current user is allowed to view it
823 * @param $rev Revision object.
824 * @return string HTML
826 function revUserLink( $rev ) {
827 if( $rev->userCan( Revision::DELETED_USER ) ) {
828 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
829 } else {
830 $link = wfMsgHtml( 'rev-deleted-user' );
832 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
833 return '<span class="history-deleted">' . $link . '</span>';
835 return $link;
839 * Generate a user tool link cluster if the current user is allowed to view it
840 * @param $rev Revision object.
841 * @return string HTML
843 function revUserTools( $rev ) {
844 if( $rev->userCan( Revision::DELETED_USER ) ) {
845 $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
846 ' ' .
847 $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
848 } else {
849 $link = wfMsgHtml( 'rev-deleted-user' );
851 if( $rev->isDeleted( Revision::DELETED_USER ) ) {
852 return '<span class="history-deleted">' . $link . '</span>';
854 return $link;
858 * This function is called by all recent changes variants, by the page history,
859 * and by the user contributions list. It is responsible for formatting edit
860 * comments. It escapes any HTML in the comment, but adds some CSS to format
861 * auto-generated comments (from section editing) and formats [[wikilinks]].
863 * @author Erik Moeller <moeller@scireview.de>
865 * Note: there's not always a title to pass to this function.
866 * Since you can't set a default parameter for a reference, I've turned it
867 * temporarily to a value pass. Should be adjusted further. --brion
869 * $param string $comment
870 * @param mixed $title Title object (to generate link to the section in autocomment) or null
871 * @param bool $local Whether section links should refer to local page
873 function formatComment($comment, $title = NULL, $local = false) {
874 wfProfileIn( __METHOD__ );
876 global $wgContLang;
877 $comment = str_replace( "\n", " ", $comment );
878 $comment = htmlspecialchars( $comment );
880 # The pattern for autogen comments is / * foo * /, which makes for
881 # some nasty regex.
882 # We look for all comments, match any text before and after the comment,
883 # add a separator where needed and format the comment itself with CSS
884 $match = array();
885 while (preg_match('/(.*)\/\*\s*(.*?)\s*\*\/(.*)/', $comment,$match)) {
886 $pre=$match[1];
887 $auto=$match[2];
888 $post=$match[3];
889 $link='';
890 if( $title ) {
891 $section = $auto;
893 # Generate a valid anchor name from the section title.
894 # Hackish, but should generally work - we strip wiki
895 # syntax, including the magic [[: that is used to
896 # "link rather than show" in case of images and
897 # interlanguage links.
898 $section = str_replace( '[[:', '', $section );
899 $section = str_replace( '[[', '', $section );
900 $section = str_replace( ']]', '', $section );
901 if ( $local ) {
902 $sectionTitle = Title::newFromText( '#' . $section);
903 } else {
904 $sectionTitle = wfClone( $title );
905 $sectionTitle->mFragment = $section;
907 $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
909 $sep='-';
910 $auto=$link.$auto;
911 if($pre) { $auto = $sep.' '.$auto; }
912 if($post) { $auto .= ' '.$sep; }
913 $auto='<span class="autocomment">'.$auto.'</span>';
914 $comment=$pre.$auto.$post;
917 # format regular and media links - all other wiki formatting
918 # is ignored
919 $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
920 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
921 while(preg_match('/\[\[:?(.*?)(\|(.*?))*\]\](.*)$/',$comment,$match)) {
922 # Handle link renaming [[foo|text]] will show link as "text"
923 if( "" != $match[3] ) {
924 $text = $match[3];
925 } else {
926 $text = $match[1];
928 $submatch = array();
929 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
930 # Media link; trail not supported.
931 $linkRegexp = '/\[\[(.*?)\]\]/';
932 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
933 } else {
934 # Other kind of link
935 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
936 $trail = $submatch[1];
937 } else {
938 $trail = "";
940 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
941 if (isset($match[1][0]) && $match[1][0] == ':')
942 $match[1] = substr($match[1], 1);
943 $thelink = $this->makeLink( $match[1], $text, "", $trail );
945 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
947 wfProfileOut( __METHOD__ );
948 return $comment;
952 * Wrap a comment in standard punctuation and formatting if
953 * it's non-empty, otherwise return empty string.
955 * @param string $comment
956 * @param mixed $title Title object (to generate link to section in autocomment) or null
957 * @param bool $local Whether section links should refer to local page
959 * @return string
961 function commentBlock( $comment, $title = NULL, $local = false ) {
962 // '*' used to be the comment inserted by the software way back
963 // in antiquity in case none was provided, here for backwards
964 // compatability, acc. to brion -ævar
965 if( $comment == '' || $comment == '*' ) {
966 return '';
967 } else {
968 $formatted = $this->formatComment( $comment, $title, $local );
969 return " <span class=\"comment\">($formatted)</span>";
974 * Wrap and format the given revision's comment block, if the current
975 * user is allowed to view it.
977 * @param Revision $rev
978 * @param bool $local Whether section links should refer to local page
979 * @return string HTML
981 function revComment( Revision $rev, $local = false ) {
982 if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
983 $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
984 } else {
985 $block = " <span class=\"comment\">" .
986 wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
988 if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
989 return " <span class=\"history-deleted\">$block</span>";
991 return $block;
994 /** @todo document */
995 function tocIndent() {
996 return "\n<ul>";
999 /** @todo document */
1000 function tocUnindent($level) {
1001 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ? $level : 0 );
1005 * parameter level defines if we are on an indentation level
1007 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1008 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1009 $anchor . '"><span class="tocnumber">' .
1010 $tocnumber . '</span> <span class="toctext">' .
1011 $tocline . '</span></a>';
1014 /** @todo document */
1015 function tocLineEnd() {
1016 return "</li>\n";
1019 /** @todo document */
1020 function tocList($toc) {
1021 global $wgJsMimeType;
1022 $title = wfMsgForContent('toc') ;
1023 return
1024 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1025 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1026 . $toc
1027 # no trailing newline, script should not be wrapped in a
1028 # paragraph
1029 . "</ul>\n</td></tr></table>"
1030 . '<script type="' . $wgJsMimeType . '">'
1031 . ' if (window.showTocToggle) {'
1032 . ' var tocShowText = "' . wfEscapeJsString( wfMsgForContent('showtoc') ) . '";'
1033 . ' var tocHideText = "' . wfEscapeJsString( wfMsgForContent('hidetoc') ) . '";'
1034 . ' showTocToggle();'
1035 . ' } '
1036 . "</script>\n";
1039 /** @todo document */
1040 public function editSectionLinkForOther( $title, $section ) {
1041 global $wgContLang;
1043 $title = Title::newFromText( $title );
1044 $editurl = '&section='.$section;
1045 $url = $this->makeKnownLinkObj( $title, wfMsg('editsection'), 'action=edit'.$editurl );
1047 return "<span class=\"editsection\">[".$url."]</span>";
1052 * @param $title Title object.
1053 * @param $section Integer: section number.
1054 * @param $hint Link String: title, or default if omitted or empty
1056 public function editSectionLink( $nt, $section, $hint='' ) {
1057 global $wgContLang;
1059 $editurl = '&section='.$section;
1060 $hint = ( $hint=='' ) ? '' : ' title="' . wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) ) . '"';
1061 $url = $this->makeKnownLinkObj( $nt, wfMsg('editsection'), 'action=edit'.$editurl, '', '', '', $hint );
1063 return "<span class=\"editsection\">[".$url."]</span>";
1067 * Create a headline for content
1069 * @param int $level The level of the headline (1-6)
1070 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1071 * This *must* be at least '>' for no attribs
1072 * @param string $anchor The anchor to give the headline (the bit after the #)
1073 * @param string $text The text of the header
1074 * @param string $link HTML to add for the section edit link
1076 * @return string HTML headline
1078 public function makeHeadline( $level, $attribs, $anchor, $text, $link ) {
1079 return "<a name=\"$anchor\"></a><h$level$attribs$link <span class=\"mw-headline\">$text</span></h$level>";
1083 * Split a link trail, return the "inside" portion and the remainder of the trail
1084 * as a two-element array
1086 * @static
1088 static function splitTrail( $trail ) {
1089 static $regex = false;
1090 if ( $regex === false ) {
1091 global $wgContLang;
1092 $regex = $wgContLang->linkTrail();
1094 $inside = '';
1095 if ( '' != $trail ) {
1096 $m = array();
1097 if ( preg_match( $regex, $trail, $m ) ) {
1098 $inside = $m[1];
1099 $trail = $m[2];
1102 return array( $inside, $trail );
1106 * Generate a rollback link for a given revision. Currently it's the
1107 * caller's responsibility to ensure that the revision is the top one. If
1108 * it's not, of course, the user will get an error message.
1110 * If the calling page is called with the parameter &bot=1, all rollback
1111 * links also get that parameter. It causes the edit itself and the rollback
1112 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1113 * changes, so this allows sysops to combat a busy vandal without bothering
1114 * other users.
1116 * @param Revision $rev
1118 function generateRollback( $rev ) {
1119 global $wgUser, $wgRequest;
1120 $title = $rev->getTitle();
1122 $extraRollback = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
1123 $extraRollback .= '&token=' . urlencode(
1124 $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ) );
1125 return '<span class="mw-rollback-link">['. $this->makeKnownLinkObj( $title,
1126 wfMsg('rollbacklink'),
1127 'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extraRollback ) .']</span>';
1131 * Returns HTML for the "templates used on this page" list.
1133 * @param array $templates Array of templates from Article::getUsedTemplate
1134 * or similar
1135 * @param bool $preview Whether this is for a preview
1136 * @param bool $section Whether this is for a section edit
1137 * @return string HTML output
1139 public function formatTemplates( $templates, $preview = false, $section = false) {
1140 global $wgUser;
1141 wfProfileIn( __METHOD__ );
1143 $sk =& $wgUser->getSkin();
1145 $outText = '';
1146 if ( count( $templates ) > 0 ) {
1147 # Do a batch existence check
1148 $batch = new LinkBatch;
1149 foreach( $templates as $title ) {
1150 $batch->addObj( $title );
1152 $batch->execute();
1154 # Construct the HTML
1155 $outText = '<div class="mw-templatesUsedExplanation">';
1156 if ( $preview ) {
1157 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1158 } elseif ( $section ) {
1159 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1160 } else {
1161 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1163 $outText .= '</div><ul>';
1165 foreach ( $templates as $titleObj ) {
1166 $r = $titleObj->getRestrictions( 'edit' );
1167 if ( in_array( 'sysop', $r ) ) {
1168 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1169 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1170 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1171 } else {
1172 $protected = '';
1174 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
1176 $outText .= '</ul>';
1178 wfProfileOut( __METHOD__ );
1179 return $outText;
1183 * Format a size in bytes for output, using an appropriate
1184 * unit (B, KB, MB or GB) according to the magnitude in question
1186 * @param $size Size to format
1187 * @return string
1189 public function formatSize( $size ) {
1190 global $wgLang;
1191 if( $size > 1024 ) {
1192 $size = $size / 1024;
1193 if( $size > 1024 ) {
1194 $size = $size / 1024;
1195 if( $size > 1024 ) {
1196 $size = $size / 1024;
1197 $msg = 'size-gigabytes';
1198 } else {
1199 $msg = 'size-megabytes';
1201 } else {
1202 $msg = 'size-kilobytes';
1204 } else {
1205 $msg = 'size-bytes';
1207 $size = round( $size, 0 );
1208 return wfMsgHtml( $msg, $wgLang->formatNum( $size ) );
1212 * Given the id of an interface element, constructs the appropriate title
1213 * and accesskey attributes from the system messages. (Note, this is usu-
1214 * ally the id but isn't always, because sometimes the accesskey needs to
1215 * go on a different element than the id, for reverse-compatibility, etc.)
1217 * @param string $name Id of the element, minus prefixes.
1218 * @return string title and accesskey attributes, ready to drop in an
1219 * element (e.g., ' title="This does something [x]" accesskey="x"').
1221 public function tooltipAndAccesskey($name) {
1222 $out = '';
1224 $tooltip = wfMsg('tooltip-'.$name);
1225 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1226 // Compatibility: formerly some tooltips had [alt-.] hardcoded
1227 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1228 $out .= ' title="'.htmlspecialchars($tooltip);
1230 $accesskey = wfMsg('accesskey-'.$name);
1231 if ($accesskey && $accesskey != '-' && !wfEmptyMsg('accesskey-'.$name, $accesskey)) {
1232 if ($out) $out .= " [$accesskey]\" accesskey=\"$accesskey\"";
1233 else $out .= " title=\"[$accesskey]\" accesskey=\"$accesskey\"";
1234 } elseif ($out) {
1235 $out .= '"';
1237 return $out;
1241 * Given the id of an interface element, constructs the appropriate title
1242 * attribute from the system messages. (Note, this is usually the id but
1243 * isn't always, because sometimes the accesskey needs to go on a different
1244 * element than the id, for reverse-compatibility, etc.)
1246 * @param string $name Id of the element, minus prefixes.
1247 * @return string title attribute, ready to drop in an element
1248 * (e.g., ' title="This does something"').
1250 public function tooltip($name) {
1251 $out = '';
1253 $tooltip = wfMsg('tooltip-'.$name);
1254 if (!wfEmptyMsg('tooltip-'.$name, $tooltip) && $tooltip != '-') {
1255 $out = ' title="'.htmlspecialchars($tooltip).'"';
1258 return $out;