3 * Split off some of the internal bits from Skin.php. These functions are used
4 * for primarily page content: links, embedded images, table of contents. Links
5 * are also used in the skin. For the moment, Skin is a descendent class of
6 * Linker. In the future, it should probably be further split so that every
7 * other bit of the wiki doesn't have to go loading up Skin to get at it.
14 * Flags for userToolLinks()
16 const TOOL_LINKS_NOBLOCK
= 1;
18 function __construct() {}
23 function postParseLinkColour( $s = null ) {
24 wfDeprecated( __METHOD__
);
29 * Get the appropriate HTML attributes to add to the "a" element of an ex-
30 * ternal link, as created by [wikisyntax].
32 * @param string $title The (unescaped) title text for the link
33 * @param string $unused Unused
34 * @param string $class The contents of the class attribute; if an empty
35 * string is passed, which is the default value, defaults to 'external'.
37 function getExternalLinkAttributes( $title, $unused = null, $class='' ) {
38 return $this->getLinkAttributesInternal( $title, $class, 'external' );
42 * Get the appropriate HTML attributes to add to the "a" element of an in-
45 * @param string $title The title text for the link, URL-encoded (???) but
47 * @param string $unused Unused
48 * @param string $class The contents of the class attribute; if an empty
49 * string is passed, which is the default value, defaults to 'external'.
51 function getInterwikiLinkAttributes( $title, $unused = null, $class='' ) {
54 # FIXME: We have a whole bunch of handling here that doesn't happen in
55 # getExternalLinkAttributes, why?
56 $title = urldecode( $title );
57 $title = $wgContLang->checkTitleEncoding( $title );
58 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
60 return $this->getLinkAttributesInternal( $title, $class, 'external' );
64 * Get the appropriate HTML attributes to add to the "a" element of an in-
67 * @param string $title The title text for the link, URL-encoded (???) but
69 * @param string $unused Unused
70 * @param string $class The contents of the class attribute, default none
72 function getInternalLinkAttributes( $title, $unused = null, $class='' ) {
73 $title = urldecode( $title );
74 $title = str_replace( '_', ' ', $title );
75 return $this->getLinkAttributesInternal( $title, $class );
79 * Get the appropriate HTML attributes to add to the "a" element of an in-
80 * ternal link, given the Title object for the page we want to link to.
82 * @param Title $nt The Title object
83 * @param string $unused Unused
84 * @param string $class The contents of the class attribute, default none
85 * @param mixed $title Optional (unescaped) string to use in the title
86 * attribute; if false, default to the name of the page we're linking to
88 function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
89 if( $title === false ) {
90 $title = $nt->getPrefixedText();
92 return $this->getLinkAttributesInternal( $title, $class );
96 * Common code for getLinkAttributesX functions
98 private function getLinkAttributesInternal( $title, $class, $classDefault = false ) {
99 $title = htmlspecialchars( $title );
100 if( $class === '' and $classDefault !== false ) {
101 # FIXME: Parameter defaults the hard way! We should just have
102 # $class = 'external' or whatever as the default in the externally-
103 # exposed functions, not $class = ''.
104 $class = $classDefault;
106 $class = htmlspecialchars( $class );
108 if( $class !== '' ) {
109 $r .= " class=\"$class\"";
111 $r .= " title=\"$title\"";
116 * Return the CSS colour of a known link
119 * @param integer $threshold user defined threshold
120 * @return string CSS class
122 function getLinkColour( $t, $threshold ) {
124 if ( $t->isRedirect() ) {
126 $colour = 'mw-redirect';
127 } elseif ( $threshold > 0 &&
128 $t->exists() && $t->getLength() < $threshold &&
129 MWNamespace
::isContent( $t->getNamespace() ) ) {
137 * This function returns an HTML link to the given target. It serves a few
139 * 1) If $target is a Title, the correct URL to link to will be figured
141 * 2) It automatically adds the usual classes for various types of link
142 * targets: "new" for red links, "stub" for short articles, etc.
143 * 3) It escapes all attribute values safely so there's no risk of XSS.
144 * 4) It provides a default tooltip if the target is a Title (the page
145 * name of the target).
146 * link() replaces the old functions in the makeLink() family.
148 * @param $target Title Can currently only be a Title, but this may
149 * change to support Images, literal URLs, etc.
150 * @param $text string The HTML contents of the <a> element, i.e.,
151 * the link text. This is raw HTML and will not be escaped. If null,
152 * defaults to the prefixed text of the Title; or if the Title is just a
153 * fragment, the contents of the fragment.
154 * @param $customAttribs array A key => value array of extra HTML attri-
155 * butes, such as title and class. (href is ignored.) Classes will be
156 * merged with the default classes, while other attributes will replace
157 * default attributes. All passed attribute values will be HTML-escaped.
158 * A false attribute value means to suppress that attribute.
159 * @param $query array The query string to append to the URL
160 * you're linking to, in key => value array form. Query keys and values
161 * will be URL-encoded.
162 * @param $options mixed String or array of strings:
163 * 'known': Page is known to exist, so don't check if it does.
164 * 'broken': Page is known not to exist, so don't check if it does.
165 * 'noclasses': Don't add any classes automatically (includes "new",
166 * "stub", "mw-redirect", "extiw"). Only use the class attribute
167 * provided, if any, so you get a simple blue link with no funny i-
169 * 'forcearticlepath': Use the article path always, even with a querystring.
170 * Has compatibility issues on some setups, so avoid wherever possible.
171 * @return string HTML <a> attribute
173 public function link( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
174 wfProfileIn( __METHOD__
);
175 if( !$target instanceof Title
) {
176 return "<!-- ERROR -->$text";
178 $options = (array)$options;
181 if( !wfRunHooks( 'LinkBegin', array( $this, $target, &$text,
182 &$customAttribs, &$query, &$options, &$ret ) ) ) {
183 wfProfileOut( __METHOD__
);
187 # Normalize the Title if it's a special page
188 $target = $this->normaliseSpecialPage( $target );
190 # If we don't know whether the page exists, let's find out.
191 wfProfileIn( __METHOD__
. '-checkPageExistence' );
192 if( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
193 if( $target->isKnown() ) {
194 $options []= 'known';
196 $options []= 'broken';
199 wfProfileOut( __METHOD__
. '-checkPageExistence' );
202 if( in_array( "forcearticlepath", $options ) && $query ){
207 # Note: we want the href attribute first, for prettiness.
208 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
209 if( in_array( 'forcearticlepath', $options ) && $oldquery ){
210 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
213 $attribs = array_merge(
215 $this->linkAttribs( $target, $customAttribs, $options )
217 if( is_null( $text ) ) {
218 $text = $this->linkText( $target );
222 if( wfRunHooks( 'LinkEnd', array( $this, $target, $options, &$text, &$attribs, &$ret ) ) ) {
223 $ret = Xml
::openElement( 'a', $attribs ) . $text . Xml
::closeElement( 'a' );
226 wfProfileOut( __METHOD__
);
231 * Identical to link(), except $options defaults to 'known'.
233 public function linkKnown( $target, $text = null, $customAttribs = array(), $query = array(), $options = 'known' ) {
234 return $this->link( $target, $text, $customAttribs, $query, $options );
237 private function linkUrl( $target, $query, $options ) {
238 wfProfileIn( __METHOD__
);
239 # We don't want to include fragments for broken links, because they
240 # generally make no sense.
241 if( in_array( 'broken', $options ) and $target->mFragment
!== '' ) {
242 $target = clone $target;
243 $target->mFragment
= '';
246 # If it's a broken link, add the appropriate query pieces, unless
247 # there's already an action specified, or unless 'edit' makes no sense
248 # (i.e., for a nonexistent special page).
249 if( in_array( 'broken', $options ) and empty( $query['action'] )
250 and $target->getNamespace() != NS_SPECIAL
) {
251 $query['action'] = 'edit';
252 $query['redlink'] = '1';
254 $ret = $target->getLinkUrl( $query );
255 wfProfileOut( __METHOD__
);
259 private function linkAttribs( $target, $attribs, $options ) {
260 wfProfileIn( __METHOD__
);
264 if( !in_array( 'noclasses', $options ) ) {
265 wfProfileIn( __METHOD__
. '-getClasses' );
266 # Now build the classes.
269 if( in_array( 'broken', $options ) ) {
273 if( $target->isExternal() ) {
274 $classes[] = 'extiw';
277 # Note that redirects never count as stubs here.
278 if ( $target->isRedirect() ) {
279 $classes[] = 'mw-redirect';
280 } elseif( $target->isContentPage() ) {
282 $threshold = $wgUser->getOption( 'stubthreshold' );
283 if( $threshold > 0 and $target->exists() and $target->getLength() < $threshold ) {
287 if( $classes != array() ) {
288 $defaults['class'] = implode( ' ', $classes );
290 wfProfileOut( __METHOD__
. '-getClasses' );
293 # Get a default title attribute.
294 if( in_array( 'known', $options ) ) {
295 $defaults['title'] = $target->getPrefixedText();
297 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
300 # Finally, merge the custom attribs with the default ones, and iterate
301 # over that, deleting all "false" attributes.
303 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
304 foreach( $merged as $key => $val ) {
305 # A false value suppresses the attribute, and we don't want the
306 # href attribute to be overridden.
307 if( $key != 'href' and $val !== false ) {
311 wfProfileOut( __METHOD__
);
315 private function linkText( $target ) {
316 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
317 if( !$target instanceof Title
) {
321 # If the target is just a fragment, with no title, we return the frag-
322 # ment text. Otherwise, we return the title text itself.
323 if( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
324 return htmlspecialchars( $target->getFragment() );
326 return htmlspecialchars( $target->getPrefixedText() );
330 * @deprecated Use link()
332 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
333 * it if you already have a title object handy. See makeLinkObj for further documentation.
335 * @param $title String: the text of the title
336 * @param $text String: link text
337 * @param $query String: optional query part
338 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
339 * be included in the link text. Other characters will be appended after
340 * the end of the link.
342 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
343 wfProfileIn( __METHOD__
);
344 $nt = Title
::newFromText( $title );
345 if ( $nt instanceof Title
) {
346 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
348 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
349 $result = $text == "" ?
$title : $text;
352 wfProfileOut( __METHOD__
);
357 * @deprecated Use link()
359 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
360 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
362 * @param $title String: the text of the title
363 * @param $text String: link text
364 * @param $query String: optional query part
365 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
366 * be included in the link text. Other characters will be appended after
367 * the end of the link.
369 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
370 $nt = Title
::newFromText( $title );
371 if ( $nt instanceof Title
) {
372 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
374 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
375 return $text == '' ?
$title : $text;
380 * @deprecated Use link()
382 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
383 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
385 * @param string $title The text of the title
386 * @param string $text Link text
387 * @param string $query Optional query part
388 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
389 * be included in the link text. Other characters will be appended after
390 * the end of the link.
392 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
393 $nt = Title
::newFromText( $title );
394 if ( $nt instanceof Title
) {
395 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
397 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
398 return $text == '' ?
$title : $text;
403 * @deprecated Use link()
405 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
406 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
408 * @param $title String: the text of the title
409 * @param $text String: link text
410 * @param $query String: optional query part
411 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
412 * be included in the link text. Other characters will be appended after
413 * the end of the link.
415 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
416 wfDeprecated( __METHOD__
);
417 $nt = Title
::newFromText( $title );
418 if ( $nt instanceof Title
) {
419 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
421 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
422 return $text == '' ?
$title : $text;
427 * @deprecated Use link()
429 * Make a link for a title which may or may not be in the database. If you need to
430 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
431 * call to this will result in a DB query.
433 * @param $nt Title: the title object to make the link from, e.g. from
434 * Title::newFromText.
435 * @param $text String: link text
436 * @param $query String: optional query part
437 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
438 * be included in the link text. Other characters will be appended after
439 * the end of the link.
440 * @param $prefix String: optional prefix. As trail, only before instead of after.
442 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
444 wfProfileIn( __METHOD__
);
446 $query = wfCgiToArray( $query );
447 list( $inside, $trail ) = Linker
::splitTrail( $trail );
449 $text = $this->linkText( $nt );
452 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
454 wfProfileOut( __METHOD__
);
459 * @deprecated Use link()
461 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
462 * it doesn't have to do a database query. It's also valid for interwiki titles and special
465 * @param $nt Title object of target page
466 * @param $text String: text to replace the title
467 * @param $query String: link target
468 * @param $trail String: text after link
469 * @param $prefix String: text before link text
470 * @param $aprops String: extra attributes to the a-element
471 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
472 * @return the a-element
474 function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
475 wfProfileIn( __METHOD__
);
478 $text = $this->linkText( $title );
480 $attribs = Sanitizer
::mergeAttributes(
481 Sanitizer
::decodeTagAttributes( $aprops ),
482 Sanitizer
::decodeTagAttributes( $style )
484 $query = wfCgiToArray( $query );
485 list( $inside, $trail ) = Linker
::splitTrail( $trail );
487 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
488 array( 'known', 'noclasses' ) ) . $trail;
490 wfProfileOut( __METHOD__
);
495 * @deprecated Use link()
497 * Make a red link to the edit page of a given title.
499 * @param $nt Title object of the target page
500 * @param $text String: Link text
501 * @param $query String: Optional query part
502 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
503 * be included in the link text. Other characters will be appended after
504 * the end of the link.
506 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
507 wfProfileIn( __METHOD__
);
509 list( $inside, $trail ) = Linker
::splitTrail( $trail );
511 $text = $this->linkText( $title );
513 $nt = $this->normaliseSpecialPage( $title );
515 $ret = $this->link( $title, "$prefix$text$inside", array(),
516 wfCgiToArray( $query ), 'broken' ) . $trail;
518 wfProfileOut( __METHOD__
);
523 * @deprecated Use link()
525 * Make a brown link to a short article.
527 * @param $nt Title object of the target page
528 * @param $text String: link text
529 * @param $query String: optional query part
530 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
531 * be included in the link text. Other characters will be appended after
532 * the end of the link.
534 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
535 wfDeprecated( __METHOD__
);
536 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
540 * @deprecated Use link()
542 * Make a coloured link.
544 * @param $nt Title object of the target page
545 * @param $colour Integer: colour of the link
546 * @param $text String: link text
547 * @param $query String: optional query part
548 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
549 * be included in the link text. Other characters will be appended after
550 * the end of the link.
552 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
554 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
556 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
560 * Generate either a normal exists-style link or a stub link, depending
561 * on the given page size.
563 * @param $size Integer
564 * @param $nt Title object.
565 * @param $text String
566 * @param $query String
567 * @param $trail String
568 * @param $prefix String
569 * @return string HTML of link
571 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
573 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
574 $colour = ( $size < $threshold ) ?
'stub' : '';
575 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
579 * Make appropriate markup for a link to the current article. This is currently rendered
580 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
581 * despite $query not being used.
583 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
585 $text = htmlspecialchars( $nt->getPrefixedText() );
587 list( $inside, $trail ) = Linker
::splitTrail( $trail );
588 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
591 function normaliseSpecialPage( Title
$title ) {
592 if ( $title->getNamespace() == NS_SPECIAL
) {
593 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
594 if ( !$name ) return $title;
595 $ret = SpecialPage
::getTitleFor( $name, $subpage );
596 $ret->mFragment
= $title->getFragment();
603 /** @todo document */
604 function fnamePart( $url ) {
605 $basename = strrchr( $url, '/' );
606 if ( false === $basename ) {
609 $basename = substr( $basename, 1 );
614 /** Obsolete alias */
615 function makeImage( $url, $alt = '' ) {
616 wfDeprecated( __METHOD__
);
617 return $this->makeExternalImage( $url, $alt );
620 /** @todo document */
621 function makeExternalImage( $url, $alt = '' ) {
623 $alt = $this->fnamePart( $url );
626 $success = wfRunHooks('LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
628 wfDebug("Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true);
631 return Xml
::element( 'img',
638 * Creates the HTML source for images
639 * @deprecated use makeImageLink2
641 * @param object $title
642 * @param string $label label text
643 * @param string $alt alt text
644 * @param string $align horizontal alignment: none, left, center, right)
645 * @param array $handlerParams Parameters to be passed to the media handler
646 * @param boolean $framed shows image in original size in a frame
647 * @param boolean $thumb shows image as thumbnail in a frame
648 * @param string $manualthumb image name for the manual thumbnail
649 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
650 * @param string $time, timestamp of the file, set as false for current
653 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
654 $thumb = false, $manualthumb = '', $valign = '', $time = false )
656 $frameParams = array( 'alt' => $alt, 'caption' => $label );
658 $frameParams['align'] = $align;
661 $frameParams['framed'] = true;
664 $frameParams['thumbnail'] = true;
666 if ( $manualthumb ) {
667 $frameParams['manualthumb'] = $manualthumb;
670 $frameParams['valign'] = $valign;
672 $file = wfFindFile( $title, $time );
673 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
677 * Given parameters derived from [[Image:Foo|options...]], generate the
678 * HTML that that syntax inserts in the page.
680 * @param Title $title Title object
681 * @param File $file File object, or false if it doesn't exist
683 * @param array $frameParams Associative array of parameters external to the media handler.
684 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
685 * will often be false.
686 * thumbnail If present, downscale and frame
687 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
688 * framed Shows image in original size in a frame
689 * frameless Downscale but don't frame
690 * upright If present, tweak default sizes for portrait orientation
691 * upright_factor Fudge factor for "upright" tweak (default 0.75)
692 * border If present, show a border around the image
693 * align Horizontal alignment (left, right, center, none)
694 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
695 * bottom, text-bottom)
696 * alt Alternate text for image (i.e. alt attribute). Plain text.
697 * caption HTML for image caption.
698 * link-url URL to link to
699 * link-title Title object to link to
700 * no-link Boolean, suppress description link
702 * @param array $handlerParams Associative array of media handler parameters, to be passed
703 * to transform(). Typical keys are "width" and "page".
704 * @param string $time, timestamp of the file, set as false for current
705 * @param string $query, query params for desc url
706 * @return string HTML for an image, with links, wrappers, etc.
708 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
710 if( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
711 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
715 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
716 if ( $file && !$file->allowInlineDisplay() ) {
717 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
718 return $this->link( $title );
723 $hp =& $handlerParams;
725 // Clean up parameters
726 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
727 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
728 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
729 # Backward compatibility, title used to always be equal to alt text
730 if ( !isset( $fp['title'] ) ) $fp['title'] = $fp['alt'];
732 $prefix = $postfix = '';
734 if ( 'center' == $fp['align'] ) {
735 $prefix = '<div class="center">';
737 $fp['align'] = 'none';
739 if ( $file && !isset( $hp['width'] ) ) {
740 $hp['width'] = $file->getWidth( $page );
742 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
743 $wopt = $wgUser->getOption( 'thumbsize' );
745 if( !isset( $wgThumbLimits[$wopt] ) ) {
746 $wopt = User
::getDefaultOption( 'thumbsize' );
749 // Reduce width for upright images when parameter 'upright' is used
750 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
751 $fp['upright'] = $wgThumbUpright;
753 // Use width which is smaller: real image width or user preference width
754 // 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
755 $prefWidth = isset( $fp['upright'] ) ?
756 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
757 $wgThumbLimits[$wopt];
758 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
759 $hp['width'] = $prefWidth;
764 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
765 # Create a thumbnail. Alignment depends on language
766 # writing direction, # right aligned for left-to-right-
767 # languages ("Western languages"), left-aligned
768 # for right-to-left-languages ("Semitic languages")
770 # If thumbnail width has not been provided, it is set
771 # to the default user option as specified in Language*.php
772 if ( $fp['align'] == '' ) {
773 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
775 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ).$postfix;
778 if ( $file && isset( $fp['frameless'] ) ) {
779 $srcWidth = $file->getWidth( $page );
780 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
781 # This is the same behaviour as the "thumb" option does it already.
782 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
783 $hp['width'] = $srcWidth;
787 if ( $file && $hp['width'] ) {
788 # Create a resized image, without the additional thumbnail features
789 $thumb = $file->transform( $hp );
795 $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
799 'title' => $fp['title'],
800 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
801 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
802 if ( !empty( $fp['link-url'] ) ) {
803 $params['custom-url-link'] = $fp['link-url'];
804 } elseif ( !empty( $fp['link-title'] ) ) {
805 $params['custom-title-link'] = $fp['link-title'];
806 } elseif ( !empty( $fp['no-link'] ) ) {
809 $params['desc-link'] = true;
810 $params['desc-query'] = $query;
813 $s = $thumb->toHtml( $params );
815 if ( '' != $fp['align'] ) {
816 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
818 return str_replace("\n", ' ',$prefix.$s.$postfix);
822 * Make HTML for a thumbnail including image, border and caption
823 * @param Title $title
824 * @param File $file File object or false if it doesn't exist
826 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
827 $frameParams = array(
832 if ( $framed ) $frameParams['framed'] = true;
833 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
834 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
837 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
838 global $wgStylePath, $wgContLang;
839 $exists = $file && $file->exists();
843 $hp =& $handlerParams;
845 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
846 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
847 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
848 # Backward compatibility, title used to always be equal to alt text
849 if ( !isset( $fp['title'] ) ) $fp['title'] = $fp['alt'];
850 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
852 if ( empty( $hp['width'] ) ) {
853 // Reduce width for upright images when parameter 'upright' is used
854 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
859 $outerWidth = $hp['width'] +
2;
861 if ( isset( $fp['manualthumb'] ) ) {
862 # Use manually specified thumbnail
863 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
864 if( $manual_title ) {
865 $manual_img = wfFindFile( $manual_title );
867 $thumb = $manual_img->getUnscaledThumb();
872 } elseif ( isset( $fp['framed'] ) ) {
873 // Use image dimensions, don't scale
874 $thumb = $file->getUnscaledThumb( $page );
876 # Do not present an image bigger than the source, for bitmap-style images
877 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
878 $srcWidth = $file->getWidth( $page );
879 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
880 $hp['width'] = $srcWidth;
882 $thumb = $file->transform( $hp );
886 $outerWidth = $thumb->getWidth() +
2;
888 $outerWidth = $hp['width'] +
2;
892 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
893 # So we don't need to pass it here in $query. However, the URL for the
894 # zoom icon still needs it, so we make a unique query for it. See bug 14771
895 $url = $title->getLocalURL( $query );
897 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
900 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
902 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
904 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
906 } elseif ( !$thumb ) {
907 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
910 $s .= $thumb->toHtml( array(
912 'title' => $fp['title'],
913 'img-class' => 'thumbimage',
915 'desc-query' => $query ) );
916 if ( isset( $fp['framed'] ) ) {
919 $zoomicon = '<div class="magnify">'.
920 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
921 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
922 'width="15" height="11" alt="" /></a></div>';
925 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
926 return str_replace("\n", ' ', $s);
930 * Make a "broken" link to an image
932 * @param Title $title Image title
933 * @param string $text Link label
934 * @param string $query Query string
935 * @param string $trail Link trail
936 * @param string $prefix Link prefix
937 * @param bool $time, a file of a certain timestamp was requested
940 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
941 global $wgEnableUploads;
942 if( $title instanceof Title
) {
943 wfProfileIn( __METHOD__
);
944 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
945 if( $wgEnableUploads && !$currentExists ) {
946 $upload = SpecialPage
::getTitleFor( 'Upload' );
948 $text = htmlspecialchars( $title->getPrefixedText() );
949 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
951 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
953 $q = 'wpDestFile=' . $title->getPartialUrl();
956 list( $inside, $trail ) = self
::splitTrail( $trail );
957 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
958 wfProfileOut( __METHOD__
);
959 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
960 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
962 wfProfileOut( __METHOD__
);
963 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
966 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
970 /** @deprecated use Linker::makeMediaLinkObj() */
971 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
972 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
973 return $this->makeMediaLinkObj( $nt, $text, $time );
977 * Create a direct link to a given uploaded file.
979 * @param $title Title object.
980 * @param $text String: pre-sanitized HTML
981 * @param $time string: time image was created
982 * @return string HTML
985 * @todo Handle invalid or missing images better.
987 function makeMediaLinkObj( $title, $text = '', $time = false ) {
988 if( is_null( $title ) ) {
989 ### HOTFIX. Instead of breaking, return empty string.
992 $img = wfFindFile( $title, $time );
994 $url = $img->getURL();
997 $upload = SpecialPage
::getTitleFor( 'Upload' );
998 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
1001 $alt = htmlspecialchars( $title->getText() );
1005 $u = htmlspecialchars( $url );
1006 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
1010 /** @todo document */
1011 function specialLink( $name, $key = '' ) {
1014 if ( '' == $key ) { $key = strtolower( $name ); }
1015 $pn = $wgContLang->ucfirst( $name );
1016 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
1021 * Make an external link
1022 * @param String $url URL to link to
1023 * @param String $text text of link
1024 * @param boolean $escape Do we escape the link text?
1025 * @param String $linktype Type of external link. Gets added to the classes
1026 * @param array $attribs Array of extra attributes to <a>
1028 * @TODO! @FIXME! This is a really crappy implementation. $linktype and
1029 * 'external' are mashed into the class attrib for the link (which is made
1030 * into a string). Then, if we've got additional params in $attribs, we
1031 * add to it. People using this might want to change the classes (or other
1032 * default link attributes), but passing $attribsText is just messy. Would
1033 * make a lot more sense to make put the classes into $attribs, let the
1034 * hook play with them, *then* expand it all at once.
1036 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
1037 $attribsText = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
1038 $url = htmlspecialchars( $url );
1040 $text = htmlspecialchars( $text );
1043 $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
1045 wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true);
1049 $attribsText .= Xml
::expandAttributes( $attribs );
1051 return '<a href="'.$url.'"'.$attribsText.'>'.$text.'</a>';
1055 * Make user link (or user contributions for unregistered users)
1056 * @param $userId Integer: user id in database.
1057 * @param $userText String: user name in database
1058 * @return string HTML fragment
1061 function userLink( $userId, $userText ) {
1062 if( $userId == 0 ) {
1063 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
1065 $page = Title
::makeTitle( NS_USER
, $userText );
1067 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
1071 * Generate standard user tool links (talk, contributions, block link, etc.)
1073 * @param int $userId User identifier
1074 * @param string $userText User name or IP address
1075 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
1076 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
1077 * @param int $edits, user edit count (optional, for performance)
1080 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
1081 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans, $wgLang;
1082 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1083 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
1087 $items[] = $this->userTalkLink( $userId, $userText );
1090 // check if the user has an edit
1092 if( $redContribsWhenNoEdits ) {
1093 $count = !is_null($edits) ?
$edits : User
::edits( $userId );
1095 $attribs['class'] = 'new';
1098 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1100 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1102 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
1103 $items[] = $this->blockLink( $userId, $userText );
1107 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
1114 * Alias for userToolLinks( $userId, $userText, true );
1115 * @param int $userId User identifier
1116 * @param string $userText User name or IP address
1117 * @param int $edits, user edit count (optional, for performance)
1119 public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
1120 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
1125 * @param $userId Integer: user id in database.
1126 * @param $userText String: user name in database.
1127 * @return string HTML fragment with user talk link
1130 function userTalkLink( $userId, $userText ) {
1131 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1132 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1133 return $userTalkLink;
1137 * @param $userId Integer: userid
1138 * @param $userText String: user name in database.
1139 * @return string HTML fragment with block link
1142 function blockLink( $userId, $userText ) {
1143 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
1144 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
1149 * Generate a user link if the current user is allowed to view it
1150 * @param $rev Revision object.
1151 * @param $isPublic, bool, show only if all users can see it
1152 * @return string HTML
1154 function revUserLink( $rev, $isPublic = false ) {
1155 if( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1156 $link = wfMsgHtml( 'rev-deleted-user' );
1157 } else if( $rev->userCan( Revision
::DELETED_USER
) ) {
1158 $link = $this->userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1159 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1161 $link = wfMsgHtml( 'rev-deleted-user' );
1163 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1164 return '<span class="history-deleted">' . $link . '</span>';
1170 * Generate a user tool link cluster if the current user is allowed to view it
1171 * @param $rev Revision object.
1172 * @param $isPublic, bool, show only if all users can see it
1173 * @return string HTML
1175 function revUserTools( $rev, $isPublic = false ) {
1176 if( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1177 $link = wfMsgHtml( 'rev-deleted-user' );
1178 } else if( $rev->userCan( Revision
::DELETED_USER
) ) {
1179 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1180 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1181 $link = $this->userLink( $userId, $userText ) .
1182 ' ' . $this->userToolLinks( $userId, $userText );
1184 $link = wfMsgHtml( 'rev-deleted-user' );
1186 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1187 return ' <span class="history-deleted">' . $link . '</span>';
1193 * This function is called by all recent changes variants, by the page history,
1194 * and by the user contributions list. It is responsible for formatting edit
1195 * comments. It escapes any HTML in the comment, but adds some CSS to format
1196 * auto-generated comments (from section editing) and formats [[wikilinks]].
1198 * @author Erik Moeller <moeller@scireview.de>
1200 * Note: there's not always a title to pass to this function.
1201 * Since you can't set a default parameter for a reference, I've turned it
1202 * temporarily to a value pass. Should be adjusted further. --brion
1204 * @param string $comment
1205 * @param mixed $title Title object (to generate link to the section in autocomment) or null
1206 * @param bool $local Whether section links should refer to local page
1208 function formatComment($comment, $title = NULL, $local = false) {
1209 wfProfileIn( __METHOD__
);
1211 # Sanitize text a bit:
1212 $comment = str_replace( "\n", " ", $comment );
1213 # Allow HTML entities (for bug 13815)
1214 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1216 # Render autocomments and make links:
1217 $comment = $this->formatAutoComments( $comment, $title, $local );
1218 $comment = $this->formatLinksInComment( $comment );
1220 wfProfileOut( __METHOD__
);
1225 * The pattern for autogen comments is / * foo * /, which makes for
1227 * We look for all comments, match any text before and after the comment,
1228 * add a separator where needed and format the comment itself with CSS
1229 * Called by Linker::formatComment.
1231 * @param string $comment Comment text
1232 * @param object $title An optional title object used to links to sections
1233 * @return string $comment formatted comment
1235 * @todo Document the $local parameter.
1237 private function formatAutocomments( $comment, $title = null, $local = false ) {
1239 $this->autocommentTitle
= $title;
1240 $this->autocommentLocal
= $local;
1241 $comment = preg_replace_callback(
1242 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1243 array( $this, 'formatAutocommentsCallback' ),
1245 unset( $this->autocommentTitle
);
1246 unset( $this->autocommentLocal
);
1250 private function formatAutocommentsCallback( $match ) {
1251 $title = $this->autocommentTitle
;
1252 $local = $this->autocommentLocal
;
1261 # Generate a valid anchor name from the section title.
1262 # Hackish, but should generally work - we strip wiki
1263 # syntax, including the magic [[: that is used to
1264 # "link rather than show" in case of images and
1265 # interlanguage links.
1266 $section = str_replace( '[[:', '', $section );
1267 $section = str_replace( '[[', '', $section );
1268 $section = str_replace( ']]', '', $section );
1270 $sectionTitle = Title
::newFromText( '#' . $section );
1272 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1273 $title->getDBkey(), $section );
1275 if ( $sectionTitle ) {
1276 $link = $this->link( $sectionTitle,
1277 wfMsgForContent( 'sectionlink' ), array(), array(),
1283 $auto = "$link$auto";
1285 # written summary $presep autocomment (summary /* section */)
1286 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1289 # autocomment $postsep written summary (/* section */ summary)
1290 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1292 $auto = '<span class="autocomment">' . $auto . '</span>';
1293 $comment = $pre . $auto . $post;
1298 * Formats wiki links and media links in text; all other wiki formatting
1301 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1302 * @param string $comment Text to format links in
1305 public function formatLinksInComment( $comment ) {
1306 return preg_replace_callback(
1307 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1308 array( $this, 'formatLinksInCommentCallback' ),
1312 protected function formatLinksInCommentCallback( $match ) {
1315 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1316 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1318 $comment = $match[0];
1320 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1321 if( strpos( $match[1], '%' ) !== false ) {
1322 $match[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($match[1]) );
1325 # Handle link renaming [[foo|text]] will show link as "text"
1326 if( "" != $match[3] ) {
1331 $submatch = array();
1332 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1333 # Media link; trail not supported.
1334 $linkRegexp = '/\[\[(.*?)\]\]/';
1335 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1337 # Other kind of link
1338 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1339 $trail = $submatch[1];
1343 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1344 if (isset($match[1][0]) && $match[1][0] == ':')
1345 $match[1] = substr($match[1], 1);
1346 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1348 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1354 * Wrap a comment in standard punctuation and formatting if
1355 * it's non-empty, otherwise return empty string.
1357 * @param string $comment
1358 * @param mixed $title Title object (to generate link to section in autocomment) or null
1359 * @param bool $local Whether section links should refer to local page
1363 function commentBlock( $comment, $title = NULL, $local = false ) {
1364 // '*' used to be the comment inserted by the software way back
1365 // in antiquity in case none was provided, here for backwards
1366 // compatability, acc. to brion -ævar
1367 if( $comment == '' ||
$comment == '*' ) {
1370 $formatted = $this->formatComment( $comment, $title, $local );
1371 return " <span class=\"comment\">($formatted)</span>";
1376 * Wrap and format the given revision's comment block, if the current
1377 * user is allowed to view it.
1379 * @param Revision $rev
1380 * @param bool $local Whether section links should refer to local page
1381 * @param $isPublic, show only if all users can see it
1382 * @return string HTML
1384 function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1385 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1386 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1387 } else if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1388 $block = $this->commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1389 $rev->getTitle(), $local );
1391 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1393 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1394 return " <span class=\"history-deleted\">$block</span>";
1399 public function formatRevisionSize( $size ) {
1401 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1404 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1407 $stxt = htmlspecialchars( $stxt );
1408 return "<span class=\"history-size\">$stxt</span>";
1411 /** @todo document */
1412 function tocIndent() {
1416 /** @todo document */
1417 function tocUnindent($level) {
1418 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1422 * parameter level defines if we are on an indentation level
1424 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1425 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1426 $anchor . '"><span class="tocnumber">' .
1427 $tocnumber . '</span> <span class="toctext">' .
1428 $tocline . '</span></a>';
1431 /** @todo document */
1432 function tocLineEnd() {
1436 /** @todo document */
1437 function tocList($toc) {
1438 global $wgJsMimeType;
1439 $title = wfMsgHtml('toc') ;
1441 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1442 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1444 # no trailing newline, script should not be wrapped in a
1446 . "</ul>\n</td></tr></table>"
1447 . '<script type="' . $wgJsMimeType . '">'
1448 . ' if (window.showTocToggle) {'
1449 . ' var tocShowText = "' . Xml
::escapeJsString( wfMsg('showtoc') ) . '";'
1450 . ' var tocHideText = "' . Xml
::escapeJsString( wfMsg('hidetoc') ) . '";'
1451 . ' showTocToggle();'
1457 * Used to generate section edit links that point to "other" pages
1458 * (sections that are really part of included pages).
1460 * @param $title Title string.
1461 * @param $section Integer: section number.
1463 public function editSectionLinkForOther( $title, $section ) {
1464 wfDeprecated( __METHOD__
);
1465 $title = Title
::newFromText( $title );
1466 return $this->doEditSectionLink( $title, $section );
1470 * @param $nt Title object.
1471 * @param $section Integer: section number.
1472 * @param $hint Link String: title, or default if omitted or empty
1474 public function editSectionLink( Title
$nt, $section, $hint = '' ) {
1475 wfDeprecated( __METHOD__
);
1476 if( $hint === '' ) {
1477 # No way to pass an actual empty $hint here! The new interface al-
1478 # lows this, so we have to do this for compatibility.
1481 return $this->doEditSectionLink( $nt, $section, $hint );
1485 * Create a section edit link. This supersedes editSectionLink() and
1486 * editSectionLinkForOther().
1488 * @param $nt Title The title being linked to (may not be the same as
1489 * $wgTitle, if the section is included from a template)
1490 * @param $section string The designation of the section being pointed to,
1491 * to be included in the link, like "§ion=$section"
1492 * @param $tooltip string The tooltip to use for the link: will be escaped
1493 * and wrapped in the 'editsectionhint' message
1494 * @return string HTML to use for edit link
1496 public function doEditSectionLink( Title
$nt, $section, $tooltip = null ) {
1498 if( !is_null( $tooltip ) ) {
1499 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1501 $link = $this->link( $nt, wfMsg('editsection'),
1503 array( 'action' => 'edit', 'section' => $section ),
1504 array( 'noclasses', 'known' )
1507 # Run the old hook. This takes up half of the function . . . hopefully
1508 # we can rid of it someday.
1511 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1512 $attribs = " title=\"$attribs\"";
1515 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result ) );
1516 if( !is_null( $result ) ) {
1517 # For reverse compatibility, add the brackets *after* the hook is
1518 # run, and even add them to hook-provided text. (This is the main
1519 # reason that the EditSectionLink hook is deprecated in favor of
1520 # DoEditSectionLink: it can't change the brackets or the span.)
1521 $result = wfMsgHtml( 'editsection-brackets', $result );
1522 return "<span class=\"editsection\">$result</span>";
1525 # Add the brackets and the span, and *then* run the nice new hook, with
1526 # clean and non-redundant arguments.
1527 $result = wfMsgHtml( 'editsection-brackets', $link );
1528 $result = "<span class=\"editsection\">$result</span>";
1530 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1535 * Create a headline for content
1537 * @param int $level The level of the headline (1-6)
1538 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1539 * This *must* be at least '>' for no attribs
1540 * @param string $anchor The anchor to give the headline (the bit after the #)
1541 * @param string $text The text of the header
1542 * @param string $link HTML to add for the section edit link
1543 * @param mixed $legacyAnchor A second, optional anchor to give for
1544 * backward compatibility (false to omit)
1546 * @return string HTML headline
1548 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1549 $ret = "<a name=\"$anchor\" id=\"$anchor\"></a>"
1550 . "<h$level$attribs"
1552 . " <span class=\"mw-headline\">$text</span>"
1554 if ( $legacyAnchor !== false ) {
1555 $ret = "<a name=\"$legacyAnchor\" id=\"$legacyAnchor\"></a>$ret";
1561 * Split a link trail, return the "inside" portion and the remainder of the trail
1562 * as a two-element array
1566 static function splitTrail( $trail ) {
1567 static $regex = false;
1568 if ( $regex === false ) {
1570 $regex = $wgContLang->linkTrail();
1573 if ( '' != $trail ) {
1575 if ( preg_match( $regex, $trail, $m ) ) {
1580 return array( $inside, $trail );
1584 * Generate a rollback link for a given revision. Currently it's the
1585 * caller's responsibility to ensure that the revision is the top one. If
1586 * it's not, of course, the user will get an error message.
1588 * If the calling page is called with the parameter &bot=1, all rollback
1589 * links also get that parameter. It causes the edit itself and the rollback
1590 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1591 * changes, so this allows sysops to combat a busy vandal without bothering
1594 * @param Revision $rev
1596 function generateRollback( $rev ) {
1597 return '<span class="mw-rollback-link">['
1598 . $this->buildRollbackLink( $rev )
1603 * Build a raw rollback link, useful for collections of "tool" links
1605 * @param Revision $rev
1608 public function buildRollbackLink( $rev ) {
1609 global $wgRequest, $wgUser;
1610 $title = $rev->getTitle();
1612 'action' => 'rollback',
1613 'from' => $rev->getUserText()
1615 if( $wgRequest->getBool( 'bot' ) ) {
1616 $query['bot'] = '1';
1617 $query['hidediff'] = '1'; // bug 15999
1619 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1620 $rev->getUserText() ) );
1621 return $this->link( $title, wfMsgHtml( 'rollbacklink' ),
1622 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1623 $query, array( 'known', 'noclasses' ) );
1627 * Returns HTML for the "templates used on this page" list.
1629 * @param array $templates Array of templates from Article::getUsedTemplate
1631 * @param bool $preview Whether this is for a preview
1632 * @param bool $section Whether this is for a section edit
1633 * @return string HTML output
1635 public function formatTemplates( $templates, $preview = false, $section = false ) {
1636 wfProfileIn( __METHOD__
);
1639 if ( count( $templates ) > 0 ) {
1640 # Do a batch existence check
1641 $batch = new LinkBatch
;
1642 foreach( $templates as $title ) {
1643 $batch->addObj( $title );
1647 # Construct the HTML
1648 $outText = '<div class="mw-templatesUsedExplanation">';
1650 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1651 } elseif ( $section ) {
1652 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1654 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1656 $outText .= "</div><ul>\n";
1658 usort( $templates, array( 'Title', 'compare' ) );
1659 foreach ( $templates as $titleObj ) {
1660 $r = $titleObj->getRestrictions( 'edit' );
1661 if ( in_array( 'sysop', $r ) ) {
1662 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1663 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1664 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1668 if( $titleObj->quickUserCan( 'edit' ) ) {
1669 $editLink = $this->makeLinkObj( $titleObj, wfMsg('editlink'), 'action=edit' );
1671 $editLink = $this->makeLinkObj( $titleObj, wfMsg('viewsourcelink'), 'action=edit' );
1673 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1675 $outText .= '</ul>';
1677 wfProfileOut( __METHOD__
);
1682 * Returns HTML for the "hidden categories on this page" list.
1684 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1686 * @return string HTML output
1688 public function formatHiddenCategories( $hiddencats ) {
1690 wfProfileIn( __METHOD__
);
1693 if ( count( $hiddencats ) > 0 ) {
1694 # Construct the HTML
1695 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1696 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1697 $outText .= "</div><ul>\n";
1699 foreach ( $hiddencats as $titleObj ) {
1700 $outText .= '<li>' . $this->link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1702 $outText .= '</ul>';
1704 wfProfileOut( __METHOD__
);
1709 * Format a size in bytes for output, using an appropriate
1710 * unit (B, KB, MB or GB) according to the magnitude in question
1712 * @param $size Size to format
1715 public function formatSize( $size ) {
1717 return htmlspecialchars( $wgLang->formatSize( $size ) );
1721 * @deprecated Returns raw bits of HTML, use titleAttrib() and accesskey()
1723 public function tooltipAndAccesskey( $name ) {
1724 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1725 # no attribute" instead of "output '' as value for attribute", this
1726 # would be three lines.
1728 'title' => $this->titleAttrib( $name, 'withaccess' ),
1729 'accesskey' => $this->accesskey( $name )
1731 if ( $attribs['title'] === false ) {
1732 unset( $attribs['title'] );
1734 if ( $attribs['accesskey'] === false ) {
1735 unset( $attribs['accesskey'] );
1737 return Xml
::expandAttributes( $attribs );
1740 /** @deprecated Returns raw bits of HTML, use titleAttrib() */
1741 public function tooltip( $name, $options = null ) {
1742 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1743 # no attribute" instead of "output '' as value for attribute", this
1744 # would be two lines.
1745 $tooltip = $this->titleAttrib( $name, $options );
1746 if ( $tooltip === false ) {
1749 return Xml
::expandAttributes( array(
1750 'title' => $this->titleAttrib( $name, $options )
1755 * Given the id of an interface element, constructs the appropriate title
1756 * attribute from the system messages. (Note, this is usually the id but
1757 * isn't always, because sometimes the accesskey needs to go on a different
1758 * element than the id, for reverse-compatibility, etc.)
1760 * @param string $name Id of the element, minus prefixes.
1761 * @param mixed $options null or the string 'withaccess' to add an access-
1763 * @return string Contents of the title attribute (which you must HTML-
1764 * escape), or false for no title attribute
1766 public function titleAttrib( $name, $options = null ) {
1767 wfProfileIn( __METHOD__
);
1769 $tooltip = wfMsg( "tooltip-$name" );
1770 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1771 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1773 # Message equal to '-' means suppress it.
1774 if ( wfEmptyMsg( "tooltip-$name", $tooltip ) ||
$tooltip == '-' ) {
1778 if ( $options == 'withaccess' ) {
1779 $accesskey = $this->accesskey( $name );
1780 if( $accesskey !== false ) {
1781 if ( $tooltip === false ||
$tooltip === '' ) {
1782 $tooltip = "[$accesskey]";
1784 $tooltip .= " [$accesskey]";
1789 wfProfileOut( __METHOD__
);
1794 * Given the id of an interface element, constructs the appropriate
1795 * accesskey attribute from the system messages. (Note, this is usually
1796 * the id but isn't always, because sometimes the accesskey needs to go on
1797 * a different element than the id, for reverse-compatibility, etc.)
1799 * @param string $name Id of the element, minus prefixes.
1800 * @return string Contents of the accesskey attribute (which you must HTML-
1801 * escape), or false for no accesskey attribute
1803 public function accesskey( $name ) {
1804 wfProfileIn( __METHOD__
);
1806 $accesskey = wfMsg( "accesskey-$name" );
1808 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1809 # attribute, but this is broken for accesskey: that might be a useful
1811 if( $accesskey != '' && $accesskey != '-' && !wfEmptyMsg( "accesskey-$name", $accesskey ) ) {
1812 wfProfileOut( __METHOD__
);
1816 wfProfileOut( __METHOD__
);
1821 * Creates a (show/hide) link for deleting revisions/log entries
1823 * @param array $query Query parameters to be passed to link()
1824 * @param bool $restricted Set to true to use a <strong> instead of a <span>
1826 * @return string HTML <a> link to Special:Revisiondelete, wrapped in a
1827 * span to allow for customization of appearance with CSS
1829 public function revDeleteLink( $query = array(), $restricted = false ) {
1830 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1831 $text = wfMsgHtml( 'rev-delundel' );
1832 $tag = $restricted ?
'strong' : 'span';
1833 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1834 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );