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 ( !in_array( 'broken', $options ) && $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( $target->getPrefixedText() == '' ) {
295 # A link like [[#Foo]]. This used to mean an empty title
296 # attribute, but that's silly. Just don't output a title.
297 } elseif( in_array( 'known', $options ) ) {
298 $defaults['title'] = $target->getPrefixedText();
300 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
303 # Finally, merge the custom attribs with the default ones, and iterate
304 # over that, deleting all "false" attributes.
306 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
307 foreach( $merged as $key => $val ) {
308 # A false value suppresses the attribute, and we don't want the
309 # href attribute to be overridden.
310 if( $key != 'href' and $val !== false ) {
314 wfProfileOut( __METHOD__
);
318 private function linkText( $target ) {
319 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
320 if( !$target instanceof Title
) {
324 # If the target is just a fragment, with no title, we return the frag-
325 # ment text. Otherwise, we return the title text itself.
326 if( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
327 return htmlspecialchars( $target->getFragment() );
329 return htmlspecialchars( $target->getPrefixedText() );
333 * @deprecated Use link()
335 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
336 * it if you already have a title object handy. See makeLinkObj for further documentation.
338 * @param $title String: the text of the title
339 * @param $text String: link text
340 * @param $query String: optional query part
341 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
342 * be included in the link text. Other characters will be appended after
343 * the end of the link.
345 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
346 wfProfileIn( __METHOD__
);
347 $nt = Title
::newFromText( $title );
348 if ( $nt instanceof Title
) {
349 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
351 wfDebug( 'Invalid title passed to Linker::makeLink(): "'.$title."\"\n" );
352 $result = $text == "" ?
$title : $text;
355 wfProfileOut( __METHOD__
);
360 * @deprecated Use link()
362 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
363 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
365 * @param $title String: the text of the title
366 * @param $text String: link text
367 * @param $query String: optional query part
368 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
369 * be included in the link text. Other characters will be appended after
370 * the end of the link.
372 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '',$aprops = '') {
373 $nt = Title
::newFromText( $title );
374 if ( $nt instanceof Title
) {
375 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
377 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "'.$title."\"\n" );
378 return $text == '' ?
$title : $text;
383 * @deprecated Use link()
385 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
386 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
388 * @param string $title The text of the title
389 * @param string $text Link text
390 * @param string $query Optional query part
391 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
392 * be included in the link text. Other characters will be appended after
393 * the end of the link.
395 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
396 $nt = Title
::newFromText( $title );
397 if ( $nt instanceof Title
) {
398 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
400 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "'.$title."\"\n" );
401 return $text == '' ?
$title : $text;
406 * @deprecated Use link()
408 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
409 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
411 * @param $title String: the text of the title
412 * @param $text String: link text
413 * @param $query String: optional query part
414 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
415 * be included in the link text. Other characters will be appended after
416 * the end of the link.
418 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
419 wfDeprecated( __METHOD__
);
420 $nt = Title
::newFromText( $title );
421 if ( $nt instanceof Title
) {
422 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
424 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "'.$title."\"\n" );
425 return $text == '' ?
$title : $text;
430 * @deprecated Use link()
432 * Make a link for a title which may or may not be in the database. If you need to
433 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
434 * call to this will result in a DB query.
436 * @param $nt Title: the title object to make the link from, e.g. from
437 * Title::newFromText.
438 * @param $text String: link text
439 * @param $query String: optional query part
440 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
441 * be included in the link text. Other characters will be appended after
442 * the end of the link.
443 * @param $prefix String: optional prefix. As trail, only before instead of after.
445 function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
446 wfProfileIn( __METHOD__
);
448 $query = wfCgiToArray( $query );
449 list( $inside, $trail ) = Linker
::splitTrail( $trail );
451 $text = $this->linkText( $nt );
454 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
456 wfProfileOut( __METHOD__
);
461 * @deprecated Use link()
463 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
464 * it doesn't have to do a database query. It's also valid for interwiki titles and special
467 * @param $nt Title object of target page
468 * @param $text String: text to replace the title
469 * @param $query String: link target
470 * @param $trail String: text after link
471 * @param $prefix String: text before link text
472 * @param $aprops String: extra attributes to the a-element
473 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
474 * @return the a-element
476 function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
477 wfProfileIn( __METHOD__
);
480 $text = $this->linkText( $title );
482 $attribs = Sanitizer
::mergeAttributes(
483 Sanitizer
::decodeTagAttributes( $aprops ),
484 Sanitizer
::decodeTagAttributes( $style )
486 $query = wfCgiToArray( $query );
487 list( $inside, $trail ) = Linker
::splitTrail( $trail );
489 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
490 array( 'known', 'noclasses' ) ) . $trail;
492 wfProfileOut( __METHOD__
);
497 * @deprecated Use link()
499 * Make a red link to the edit page of a given title.
501 * @param $nt Title object of the target page
502 * @param $text String: Link text
503 * @param $query String: Optional query part
504 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
505 * be included in the link text. Other characters will be appended after
506 * the end of the link.
508 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
509 wfProfileIn( __METHOD__
);
511 list( $inside, $trail ) = Linker
::splitTrail( $trail );
513 $text = $this->linkText( $title );
515 $nt = $this->normaliseSpecialPage( $title );
517 $ret = $this->link( $title, "$prefix$text$inside", array(),
518 wfCgiToArray( $query ), 'broken' ) . $trail;
520 wfProfileOut( __METHOD__
);
525 * @deprecated Use link()
527 * Make a brown link to a short article.
529 * @param $nt Title object of the target page
530 * @param $text String: link text
531 * @param $query String: optional query part
532 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
533 * be included in the link text. Other characters will be appended after
534 * the end of the link.
536 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
537 wfDeprecated( __METHOD__
);
538 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
542 * @deprecated Use link()
544 * Make a coloured link.
546 * @param $nt Title object of the target page
547 * @param $colour Integer: colour of the link
548 * @param $text String: link text
549 * @param $query String: optional query part
550 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
551 * be included in the link text. Other characters will be appended after
552 * the end of the link.
554 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
556 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
558 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
562 * Generate either a normal exists-style link or a stub link, depending
563 * on the given page size.
565 * @param $size Integer
566 * @param $nt Title object.
567 * @param $text String
568 * @param $query String
569 * @param $trail String
570 * @param $prefix String
571 * @return string HTML of link
573 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
575 $threshold = intval( $wgUser->getOption( 'stubthreshold' ) );
576 $colour = ( $size < $threshold ) ?
'stub' : '';
577 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
581 * Make appropriate markup for a link to the current article. This is currently rendered
582 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
583 * despite $query not being used.
585 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
587 $text = htmlspecialchars( $nt->getPrefixedText() );
589 list( $inside, $trail ) = Linker
::splitTrail( $trail );
590 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
593 function normaliseSpecialPage( Title
$title ) {
594 if ( $title->getNamespace() == NS_SPECIAL
) {
595 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
596 if ( !$name ) return $title;
597 $ret = SpecialPage
::getTitleFor( $name, $subpage );
598 $ret->mFragment
= $title->getFragment();
605 /** @todo document */
606 function fnamePart( $url ) {
607 $basename = strrchr( $url, '/' );
608 if ( false === $basename ) {
611 $basename = substr( $basename, 1 );
616 /** Obsolete alias */
617 function makeImage( $url, $alt = '' ) {
618 wfDeprecated( __METHOD__
);
619 return $this->makeExternalImage( $url, $alt );
622 /** @todo document */
623 function makeExternalImage( $url, $alt = '' ) {
625 $alt = $this->fnamePart( $url );
628 $success = wfRunHooks('LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
630 wfDebug("Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true);
633 return Xml
::element( 'img',
640 * Creates the HTML source for images
641 * @deprecated use makeImageLink2
643 * @param object $title
644 * @param string $label label text
645 * @param string $alt alt text
646 * @param string $align horizontal alignment: none, left, center, right)
647 * @param array $handlerParams Parameters to be passed to the media handler
648 * @param boolean $framed shows image in original size in a frame
649 * @param boolean $thumb shows image as thumbnail in a frame
650 * @param string $manualthumb image name for the manual thumbnail
651 * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
652 * @param string $time, timestamp of the file, set as false for current
655 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
656 $thumb = false, $manualthumb = '', $valign = '', $time = false )
658 $frameParams = array( 'alt' => $alt, 'caption' => $label );
660 $frameParams['align'] = $align;
663 $frameParams['framed'] = true;
666 $frameParams['thumbnail'] = true;
668 if ( $manualthumb ) {
669 $frameParams['manualthumb'] = $manualthumb;
672 $frameParams['valign'] = $valign;
674 $file = wfFindFile( $title, $time );
675 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
679 * Given parameters derived from [[Image:Foo|options...]], generate the
680 * HTML that that syntax inserts in the page.
682 * @param Title $title Title object
683 * @param File $file File object, or false if it doesn't exist
685 * @param array $frameParams Associative array of parameters external to the media handler.
686 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
687 * will often be false.
688 * thumbnail If present, downscale and frame
689 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
690 * framed Shows image in original size in a frame
691 * frameless Downscale but don't frame
692 * upright If present, tweak default sizes for portrait orientation
693 * upright_factor Fudge factor for "upright" tweak (default 0.75)
694 * border If present, show a border around the image
695 * align Horizontal alignment (left, right, center, none)
696 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
697 * bottom, text-bottom)
698 * alt Alternate text for image (i.e. alt attribute). Plain text.
699 * caption HTML for image caption.
700 * link-url URL to link to
701 * link-title Title object to link to
702 * no-link Boolean, suppress description link
704 * @param array $handlerParams Associative array of media handler parameters, to be passed
705 * to transform(). Typical keys are "width" and "page".
706 * @param string $time, timestamp of the file, set as false for current
707 * @param string $query, query params for desc url
708 * @return string HTML for an image, with links, wrappers, etc.
710 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
712 if( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
713 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
717 global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
718 if ( $file && !$file->allowInlineDisplay() ) {
719 wfDebug( __METHOD__
.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
720 return $this->link( $title );
725 $hp =& $handlerParams;
727 // Clean up parameters
728 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
729 if ( !isset( $fp['align'] ) ) $fp['align'] = '';
730 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
731 # Backward compatibility, title used to always be equal to alt text
732 if ( !isset( $fp['title'] ) ) $fp['title'] = $fp['alt'];
734 $prefix = $postfix = '';
736 if ( 'center' == $fp['align'] ) {
737 $prefix = '<div class="center">';
739 $fp['align'] = 'none';
741 if ( $file && !isset( $hp['width'] ) ) {
742 $hp['width'] = $file->getWidth( $page );
744 if( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
745 $wopt = $wgUser->getOption( 'thumbsize' );
747 if( !isset( $wgThumbLimits[$wopt] ) ) {
748 $wopt = User
::getDefaultOption( 'thumbsize' );
751 // Reduce width for upright images when parameter 'upright' is used
752 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
753 $fp['upright'] = $wgThumbUpright;
755 // Use width which is smaller: real image width or user preference width
756 // 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
757 $prefWidth = isset( $fp['upright'] ) ?
758 round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
759 $wgThumbLimits[$wopt];
760 if ( $hp['width'] <= 0 ||
$prefWidth < $hp['width'] ) {
761 $hp['width'] = $prefWidth;
766 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
767 # Create a thumbnail. Alignment depends on language
768 # writing direction, # right aligned for left-to-right-
769 # languages ("Western languages"), left-aligned
770 # for right-to-left-languages ("Semitic languages")
772 # If thumbnail width has not been provided, it is set
773 # to the default user option as specified in Language*.php
774 if ( $fp['align'] == '' ) {
775 $fp['align'] = $wgContLang->isRTL() ?
'left' : 'right';
777 return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ).$postfix;
780 if ( $file && isset( $fp['frameless'] ) ) {
781 $srcWidth = $file->getWidth( $page );
782 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
783 # This is the same behaviour as the "thumb" option does it already.
784 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
785 $hp['width'] = $srcWidth;
789 if ( $file && $hp['width'] ) {
790 # Create a resized image, without the additional thumbnail features
791 $thumb = $file->transform( $hp );
797 $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
801 'title' => $fp['title'],
802 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
803 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
804 if ( !empty( $fp['link-url'] ) ) {
805 $params['custom-url-link'] = $fp['link-url'];
806 } elseif ( !empty( $fp['link-title'] ) ) {
807 $params['custom-title-link'] = $fp['link-title'];
808 } elseif ( !empty( $fp['no-link'] ) ) {
811 $params['desc-link'] = true;
812 $params['desc-query'] = $query;
815 $s = $thumb->toHtml( $params );
817 if ( '' != $fp['align'] ) {
818 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
820 return str_replace("\n", ' ',$prefix.$s.$postfix);
824 * Make HTML for a thumbnail including image, border and caption
825 * @param Title $title
826 * @param File $file File object or false if it doesn't exist
828 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
829 $frameParams = array(
834 if ( $framed ) $frameParams['framed'] = true;
835 if ( $manualthumb ) $frameParams['manualthumb'] = $manualthumb;
836 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
839 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
840 global $wgStylePath, $wgContLang;
841 $exists = $file && $file->exists();
845 $hp =& $handlerParams;
847 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
848 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
849 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
850 # Backward compatibility, title used to always be equal to alt text
851 if ( !isset( $fp['title'] ) ) $fp['title'] = $fp['alt'];
852 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
854 if ( empty( $hp['width'] ) ) {
855 // Reduce width for upright images when parameter 'upright' is used
856 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
861 $outerWidth = $hp['width'] +
2;
863 if ( isset( $fp['manualthumb'] ) ) {
864 # Use manually specified thumbnail
865 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
866 if( $manual_title ) {
867 $manual_img = wfFindFile( $manual_title );
869 $thumb = $manual_img->getUnscaledThumb();
874 } elseif ( isset( $fp['framed'] ) ) {
875 // Use image dimensions, don't scale
876 $thumb = $file->getUnscaledThumb( $page );
878 # Do not present an image bigger than the source, for bitmap-style images
879 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
880 $srcWidth = $file->getWidth( $page );
881 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
882 $hp['width'] = $srcWidth;
884 $thumb = $file->transform( $hp );
888 $outerWidth = $thumb->getWidth() +
2;
890 $outerWidth = $hp['width'] +
2;
894 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
895 # So we don't need to pass it here in $query. However, the URL for the
896 # zoom icon still needs it, so we make a unique query for it. See bug 14771
897 $url = $title->getLocalURL( $query );
899 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
902 $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
904 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
906 $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
908 } elseif ( !$thumb ) {
909 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
912 $s .= $thumb->toHtml( array(
914 'title' => $fp['title'],
915 'img-class' => 'thumbimage',
917 'desc-query' => $query ) );
918 if ( isset( $fp['framed'] ) ) {
921 $zoomicon = '<div class="magnify">'.
922 '<a href="'.$url.'" class="internal" title="'.$more.'">'.
923 '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
924 'width="15" height="11" alt="" /></a></div>';
927 $s .= ' <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
928 return str_replace("\n", ' ', $s);
932 * Make a "broken" link to an image
934 * @param Title $title Image title
935 * @param string $text Link label
936 * @param string $query Query string
937 * @param string $trail Link trail
938 * @param string $prefix Link prefix
939 * @param bool $time, a file of a certain timestamp was requested
942 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
943 global $wgEnableUploads;
944 if( $title instanceof Title
) {
945 wfProfileIn( __METHOD__
);
946 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
947 if( $wgEnableUploads && !$currentExists ) {
948 $upload = SpecialPage
::getTitleFor( 'Upload' );
950 $text = htmlspecialchars( $title->getPrefixedText() );
951 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
953 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
955 $q = 'wpDestFile=' . $title->getPartialUrl();
958 list( $inside, $trail ) = self
::splitTrail( $trail );
959 $style = $this->getInternalLinkAttributesObj( $title, $text, 'new' );
960 wfProfileOut( __METHOD__
);
961 return '<a href="' . $upload->escapeLocalUrl( $q ) . '"'
962 . $style . '>' . $prefix . $text . $inside . '</a>' . $trail;
964 wfProfileOut( __METHOD__
);
965 return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
968 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
972 /** @deprecated use Linker::makeMediaLinkObj() */
973 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
974 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
975 return $this->makeMediaLinkObj( $nt, $text, $time );
979 * Create a direct link to a given uploaded file.
981 * @param $title Title object.
982 * @param $text String: pre-sanitized HTML
983 * @param $time string: time image was created
984 * @return string HTML
987 * @todo Handle invalid or missing images better.
989 function makeMediaLinkObj( $title, $text = '', $time = false ) {
990 if( is_null( $title ) ) {
991 ### HOTFIX. Instead of breaking, return empty string.
994 $img = wfFindFile( $title, $time );
996 $url = $img->getURL();
999 $upload = SpecialPage
::getTitleFor( 'Upload' );
1000 $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
1003 $alt = htmlspecialchars( $title->getText() );
1007 $u = htmlspecialchars( $url );
1008 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
1012 /** @todo document */
1013 function specialLink( $name, $key = '' ) {
1016 if ( '' == $key ) { $key = strtolower( $name ); }
1017 $pn = $wgContLang->ucfirst( $name );
1018 return $this->makeKnownLink( $wgContLang->specialPage( $pn ),
1023 * Make an external link
1024 * @param String $url URL to link to
1025 * @param String $text text of link
1026 * @param boolean $escape Do we escape the link text?
1027 * @param String $linktype Type of external link. Gets added to the classes
1028 * @param array $attribs Array of extra attributes to <a>
1030 * @TODO! @FIXME! This is a really crappy implementation. $linktype and
1031 * 'external' are mashed into the class attrib for the link (which is made
1032 * into a string). Then, if we've got additional params in $attribs, we
1033 * add to it. People using this might want to change the classes (or other
1034 * default link attributes), but passing $attribsText is just messy. Would
1035 * make a lot more sense to make put the classes into $attribs, let the
1036 * hook play with them, *then* expand it all at once.
1038 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
1039 $attribsText = $this->getExternalLinkAttributes( $url, $text, 'external ' . $linktype );
1040 $url = htmlspecialchars( $url );
1042 $text = htmlspecialchars( $text );
1045 $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
1047 wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true);
1051 $attribsText .= Xml
::expandAttributes( $attribs );
1053 return '<a href="'.$url.'"'.$attribsText.'>'.$text.'</a>';
1057 * Make user link (or user contributions for unregistered users)
1058 * @param $userId Integer: user id in database.
1059 * @param $userText String: user name in database
1060 * @return string HTML fragment
1063 function userLink( $userId, $userText ) {
1064 if( $userId == 0 ) {
1065 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
1067 $page = Title
::makeTitle( NS_USER
, $userText );
1069 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
1073 * Generate standard user tool links (talk, contributions, block link, etc.)
1075 * @param int $userId User identifier
1076 * @param string $userText User name or IP address
1077 * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
1078 * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
1079 * @param int $edits, user edit count (optional, for performance)
1082 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
1083 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans, $wgLang;
1084 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1085 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
1089 $items[] = $this->userTalkLink( $userId, $userText );
1092 // check if the user has an edit
1094 if( $redContribsWhenNoEdits ) {
1095 $count = !is_null($edits) ?
$edits : User
::edits( $userId );
1097 $attribs['class'] = 'new';
1100 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1102 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1104 if( $blockable && $wgUser->isAllowed( 'block' ) ) {
1105 $items[] = $this->blockLink( $userId, $userText );
1109 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
1116 * Alias for userToolLinks( $userId, $userText, true );
1117 * @param int $userId User identifier
1118 * @param string $userText User name or IP address
1119 * @param int $edits, user edit count (optional, for performance)
1121 public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
1122 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
1127 * @param $userId Integer: user id in database.
1128 * @param $userText String: user name in database.
1129 * @return string HTML fragment with user talk link
1132 function userTalkLink( $userId, $userText ) {
1133 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1134 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1135 return $userTalkLink;
1139 * @param $userId Integer: userid
1140 * @param $userText String: user name in database.
1141 * @return string HTML fragment with block link
1144 function blockLink( $userId, $userText ) {
1145 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
1146 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
1151 * Generate a user link if the current user is allowed to view it
1152 * @param $rev Revision object.
1153 * @param $isPublic, bool, show only if all users can see it
1154 * @return string HTML
1156 function revUserLink( $rev, $isPublic = false ) {
1157 if( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1158 $link = wfMsgHtml( 'rev-deleted-user' );
1159 } else if( $rev->userCan( Revision
::DELETED_USER
) ) {
1160 $link = $this->userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1161 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1163 $link = wfMsgHtml( 'rev-deleted-user' );
1165 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1166 return '<span class="history-deleted">' . $link . '</span>';
1172 * Generate a user tool link cluster if the current user is allowed to view it
1173 * @param $rev Revision object.
1174 * @param $isPublic, bool, show only if all users can see it
1175 * @return string HTML
1177 function revUserTools( $rev, $isPublic = false ) {
1178 if( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1179 $link = wfMsgHtml( 'rev-deleted-user' );
1180 } else if( $rev->userCan( Revision
::DELETED_USER
) ) {
1181 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1182 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1183 $link = $this->userLink( $userId, $userText ) .
1184 ' ' . $this->userToolLinks( $userId, $userText );
1186 $link = wfMsgHtml( 'rev-deleted-user' );
1188 if( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1189 return ' <span class="history-deleted">' . $link . '</span>';
1195 * This function is called by all recent changes variants, by the page history,
1196 * and by the user contributions list. It is responsible for formatting edit
1197 * comments. It escapes any HTML in the comment, but adds some CSS to format
1198 * auto-generated comments (from section editing) and formats [[wikilinks]].
1200 * @author Erik Moeller <moeller@scireview.de>
1202 * Note: there's not always a title to pass to this function.
1203 * Since you can't set a default parameter for a reference, I've turned it
1204 * temporarily to a value pass. Should be adjusted further. --brion
1206 * @param string $comment
1207 * @param mixed $title Title object (to generate link to the section in autocomment) or null
1208 * @param bool $local Whether section links should refer to local page
1210 function formatComment($comment, $title = NULL, $local = false) {
1211 wfProfileIn( __METHOD__
);
1213 # Sanitize text a bit:
1214 $comment = str_replace( "\n", " ", $comment );
1215 # Allow HTML entities (for bug 13815)
1216 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1218 # Render autocomments and make links:
1219 $comment = $this->formatAutoComments( $comment, $title, $local );
1220 $comment = $this->formatLinksInComment( $comment );
1222 wfProfileOut( __METHOD__
);
1227 * The pattern for autogen comments is / * foo * /, which makes for
1229 * We look for all comments, match any text before and after the comment,
1230 * add a separator where needed and format the comment itself with CSS
1231 * Called by Linker::formatComment.
1233 * @param string $comment Comment text
1234 * @param object $title An optional title object used to links to sections
1235 * @return string $comment formatted comment
1237 * @todo Document the $local parameter.
1239 private function formatAutocomments( $comment, $title = null, $local = false ) {
1241 $this->autocommentTitle
= $title;
1242 $this->autocommentLocal
= $local;
1243 $comment = preg_replace_callback(
1244 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1245 array( $this, 'formatAutocommentsCallback' ),
1247 unset( $this->autocommentTitle
);
1248 unset( $this->autocommentLocal
);
1252 private function formatAutocommentsCallback( $match ) {
1253 $title = $this->autocommentTitle
;
1254 $local = $this->autocommentLocal
;
1263 # Generate a valid anchor name from the section title.
1264 # Hackish, but should generally work - we strip wiki
1265 # syntax, including the magic [[: that is used to
1266 # "link rather than show" in case of images and
1267 # interlanguage links.
1268 $section = str_replace( '[[:', '', $section );
1269 $section = str_replace( '[[', '', $section );
1270 $section = str_replace( ']]', '', $section );
1272 $sectionTitle = Title
::newFromText( '#' . $section );
1274 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1275 $title->getDBkey(), $section );
1277 if ( $sectionTitle ) {
1278 $link = $this->link( $sectionTitle,
1279 wfMsgForContent( 'sectionlink' ), array(), array(),
1285 $auto = "$link$auto";
1287 # written summary $presep autocomment (summary /* section */)
1288 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1291 # autocomment $postsep written summary (/* section */ summary)
1292 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1294 $auto = '<span class="autocomment">' . $auto . '</span>';
1295 $comment = $pre . $auto . $post;
1300 * Formats wiki links and media links in text; all other wiki formatting
1303 * @fixme doesn't handle sub-links as in image thumb texts like the main parser
1304 * @param string $comment Text to format links in
1307 public function formatLinksInComment( $comment ) {
1308 return preg_replace_callback(
1309 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1310 array( $this, 'formatLinksInCommentCallback' ),
1314 protected function formatLinksInCommentCallback( $match ) {
1317 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1318 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1320 $comment = $match[0];
1322 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1323 if( strpos( $match[1], '%' ) !== false ) {
1324 $match[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($match[1]) );
1327 # Handle link renaming [[foo|text]] will show link as "text"
1328 if( "" != $match[3] ) {
1333 $submatch = array();
1334 if( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1335 # Media link; trail not supported.
1336 $linkRegexp = '/\[\[(.*?)\]\]/';
1337 $thelink = $this->makeMediaLink( $submatch[1], "", $text );
1339 # Other kind of link
1340 if( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1341 $trail = $submatch[1];
1345 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1346 if (isset($match[1][0]) && $match[1][0] == ':')
1347 $match[1] = substr($match[1], 1);
1348 $thelink = $this->makeLink( $match[1], $text, "", $trail );
1350 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1356 * Wrap a comment in standard punctuation and formatting if
1357 * it's non-empty, otherwise return empty string.
1359 * @param string $comment
1360 * @param mixed $title Title object (to generate link to section in autocomment) or null
1361 * @param bool $local Whether section links should refer to local page
1365 function commentBlock( $comment, $title = NULL, $local = false ) {
1366 // '*' used to be the comment inserted by the software way back
1367 // in antiquity in case none was provided, here for backwards
1368 // compatability, acc. to brion -ævar
1369 if( $comment == '' ||
$comment == '*' ) {
1372 $formatted = $this->formatComment( $comment, $title, $local );
1373 return " <span class=\"comment\">($formatted)</span>";
1378 * Wrap and format the given revision's comment block, if the current
1379 * user is allowed to view it.
1381 * @param Revision $rev
1382 * @param bool $local Whether section links should refer to local page
1383 * @param $isPublic, show only if all users can see it
1384 * @return string HTML
1386 function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1387 if( $rev->getComment() == "" ) return "";
1388 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1389 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1390 } else if( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1391 $block = $this->commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1392 $rev->getTitle(), $local );
1394 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1396 if( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1397 return " <span class=\"history-deleted\">$block</span>";
1402 public function formatRevisionSize( $size ) {
1404 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1407 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1410 $stxt = htmlspecialchars( $stxt );
1411 return "<span class=\"history-size\">$stxt</span>";
1414 /** @todo document */
1415 function tocIndent() {
1419 /** @todo document */
1420 function tocUnindent($level) {
1421 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level>0 ?
$level : 0 );
1425 * parameter level defines if we are on an indentation level
1427 function tocLine( $anchor, $tocline, $tocnumber, $level ) {
1428 return "\n<li class=\"toclevel-$level\"><a href=\"#" .
1429 $anchor . '"><span class="tocnumber">' .
1430 $tocnumber . '</span> <span class="toctext">' .
1431 $tocline . '</span></a>';
1434 /** @todo document */
1435 function tocLineEnd() {
1439 /** @todo document */
1440 function tocList($toc) {
1441 global $wgJsMimeType;
1442 $title = wfMsgHtml('toc') ;
1444 '<table id="toc" class="toc" summary="' . $title .'"><tr><td>'
1445 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1447 # no trailing newline, script should not be wrapped in a
1449 . "</ul>\n</td></tr></table>"
1450 . '<script type="' . $wgJsMimeType . '">'
1451 . ' if (window.showTocToggle) {'
1452 . ' var tocShowText = "' . Xml
::escapeJsString( wfMsg('showtoc') ) . '";'
1453 . ' var tocHideText = "' . Xml
::escapeJsString( wfMsg('hidetoc') ) . '";'
1454 . ' showTocToggle();'
1460 * Used to generate section edit links that point to "other" pages
1461 * (sections that are really part of included pages).
1463 * @param $title Title string.
1464 * @param $section Integer: section number.
1466 public function editSectionLinkForOther( $title, $section ) {
1467 wfDeprecated( __METHOD__
);
1468 $title = Title
::newFromText( $title );
1469 return $this->doEditSectionLink( $title, $section );
1473 * @param $nt Title object.
1474 * @param $section Integer: section number.
1475 * @param $hint Link String: title, or default if omitted or empty
1477 public function editSectionLink( Title
$nt, $section, $hint = '' ) {
1478 wfDeprecated( __METHOD__
);
1479 if( $hint === '' ) {
1480 # No way to pass an actual empty $hint here! The new interface al-
1481 # lows this, so we have to do this for compatibility.
1484 return $this->doEditSectionLink( $nt, $section, $hint );
1488 * Create a section edit link. This supersedes editSectionLink() and
1489 * editSectionLinkForOther().
1491 * @param $nt Title The title being linked to (may not be the same as
1492 * $wgTitle, if the section is included from a template)
1493 * @param $section string The designation of the section being pointed to,
1494 * to be included in the link, like "§ion=$section"
1495 * @param $tooltip string The tooltip to use for the link: will be escaped
1496 * and wrapped in the 'editsectionhint' message
1497 * @return string HTML to use for edit link
1499 public function doEditSectionLink( Title
$nt, $section, $tooltip = null ) {
1501 if( !is_null( $tooltip ) ) {
1502 $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
1504 $link = $this->link( $nt, wfMsg('editsection'),
1506 array( 'action' => 'edit', 'section' => $section ),
1507 array( 'noclasses', 'known' )
1510 # Run the old hook. This takes up half of the function . . . hopefully
1511 # we can rid of it someday.
1514 $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
1515 $attribs = " title=\"$attribs\"";
1518 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result ) );
1519 if( !is_null( $result ) ) {
1520 # For reverse compatibility, add the brackets *after* the hook is
1521 # run, and even add them to hook-provided text. (This is the main
1522 # reason that the EditSectionLink hook is deprecated in favor of
1523 # DoEditSectionLink: it can't change the brackets or the span.)
1524 $result = wfMsgHtml( 'editsection-brackets', $result );
1525 return "<span class=\"editsection\">$result</span>";
1528 # Add the brackets and the span, and *then* run the nice new hook, with
1529 # clean and non-redundant arguments.
1530 $result = wfMsgHtml( 'editsection-brackets', $link );
1531 $result = "<span class=\"editsection\">$result</span>";
1533 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
1538 * Create a headline for content
1540 * @param int $level The level of the headline (1-6)
1541 * @param string $attribs Any attributes for the headline, starting with a space and ending with '>'
1542 * This *must* be at least '>' for no attribs
1543 * @param string $anchor The anchor to give the headline (the bit after the #)
1544 * @param string $text The text of the header
1545 * @param string $link HTML to add for the section edit link
1546 * @param mixed $legacyAnchor A second, optional anchor to give for
1547 * backward compatibility (false to omit)
1549 * @return string HTML headline
1551 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1552 $ret = "<a name=\"$anchor\" id=\"$anchor\"></a>"
1553 . "<h$level$attribs"
1555 . " <span class=\"mw-headline\">$text</span>"
1557 if ( $legacyAnchor !== false ) {
1558 $ret = "<a name=\"$legacyAnchor\" id=\"$legacyAnchor\"></a>$ret";
1564 * Split a link trail, return the "inside" portion and the remainder of the trail
1565 * as a two-element array
1569 static function splitTrail( $trail ) {
1570 static $regex = false;
1571 if ( $regex === false ) {
1573 $regex = $wgContLang->linkTrail();
1576 if ( '' != $trail ) {
1578 if ( preg_match( $regex, $trail, $m ) ) {
1583 return array( $inside, $trail );
1587 * Generate a rollback link for a given revision. Currently it's the
1588 * caller's responsibility to ensure that the revision is the top one. If
1589 * it's not, of course, the user will get an error message.
1591 * If the calling page is called with the parameter &bot=1, all rollback
1592 * links also get that parameter. It causes the edit itself and the rollback
1593 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1594 * changes, so this allows sysops to combat a busy vandal without bothering
1597 * @param Revision $rev
1599 function generateRollback( $rev ) {
1600 return '<span class="mw-rollback-link">['
1601 . $this->buildRollbackLink( $rev )
1606 * Build a raw rollback link, useful for collections of "tool" links
1608 * @param Revision $rev
1611 public function buildRollbackLink( $rev ) {
1612 global $wgRequest, $wgUser;
1613 $title = $rev->getTitle();
1615 'action' => 'rollback',
1616 'from' => $rev->getUserText()
1618 if( $wgRequest->getBool( 'bot' ) ) {
1619 $query['bot'] = '1';
1620 $query['hidediff'] = '1'; // bug 15999
1622 $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
1623 $rev->getUserText() ) );
1625 $dbr = wfGetDB( DB_MASTER
);
1627 // Latest edits by this user, up to 10; if too expensive, use only on smaller wikis
1628 $res = $dbr->select( 'revision',
1630 array( 'rev_page' => $rev->getPage(),
1631 'rev_user_text' => $rev->getUserText()
1633 array( 'USE INDEX' => 'page_timestamp',
1634 'ORDER BY' => 'rev_timestamp DESC',
1638 // Swiped from Article::commitRollback()
1639 $user = intval( $rev->getUser() );
1640 $user_text = $dbr->addQuotes( $rev->getUserText() );
1642 // Get the last edit not by this guy
1643 $s = $dbr->selectRow( 'revision',
1644 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
1645 array( 'rev_page' => $rev->getPage(),
1646 "rev_user != {$user} OR rev_user_text != {$user_text}"
1648 array( 'USE INDEX' => 'page_timestamp',
1649 'ORDER BY' => 'rev_timestamp DESC' )
1652 if( $s === false ) {
1653 // No one else ever edited this page
1656 elseif( $s->rev_deleted
& REVISION
::DELETED_TEXT ||
$s->rev_deleted
& REVISION
::DELETED_USER
) {
1657 // Only admins can see this text
1662 while( $row = $dbr->fetchObject( $res ) ) {
1664 if( $s->rev_id
> $row->rev_id
) {
1669 // We only bother to count up to 10
1670 if( $editCount == 10 )
1673 return $this->link( $title, wfMsgHtml( 'rollbacklink', $editCount ),
1674 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1675 $query, array( 'known', 'noclasses' ) );
1679 * Returns HTML for the "templates used on this page" list.
1681 * @param array $templates Array of templates from Article::getUsedTemplate
1683 * @param bool $preview Whether this is for a preview
1684 * @param bool $section Whether this is for a section edit
1685 * @return string HTML output
1687 public function formatTemplates( $templates, $preview = false, $section = false ) {
1688 wfProfileIn( __METHOD__
);
1691 if ( count( $templates ) > 0 ) {
1692 # Do a batch existence check
1693 $batch = new LinkBatch
;
1694 foreach( $templates as $title ) {
1695 $batch->addObj( $title );
1699 # Construct the HTML
1700 $outText = '<div class="mw-templatesUsedExplanation">';
1702 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ) );
1703 } elseif ( $section ) {
1704 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ) );
1706 $outText .= wfMsgExt( 'templatesused', array( 'parse' ) );
1708 $outText .= "</div><ul>\n";
1710 usort( $templates, array( 'Title', 'compare' ) );
1711 foreach ( $templates as $titleObj ) {
1712 $r = $titleObj->getRestrictions( 'edit' );
1713 if ( in_array( 'sysop', $r ) ) {
1714 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1715 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1716 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1720 if( $titleObj->quickUserCan( 'edit' ) ) {
1721 $editLink = $this->makeLinkObj( $titleObj, wfMsg('editlink'), 'action=edit' );
1723 $editLink = $this->makeLinkObj( $titleObj, wfMsg('viewsourcelink'), 'action=edit' );
1725 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1727 $outText .= '</ul>';
1729 wfProfileOut( __METHOD__
);
1734 * Returns HTML for the "hidden categories on this page" list.
1736 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1738 * @return string HTML output
1740 public function formatHiddenCategories( $hiddencats ) {
1742 wfProfileIn( __METHOD__
);
1745 if ( count( $hiddencats ) > 0 ) {
1746 # Construct the HTML
1747 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1748 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1749 $outText .= "</div><ul>\n";
1751 foreach ( $hiddencats as $titleObj ) {
1752 $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
1754 $outText .= '</ul>';
1756 wfProfileOut( __METHOD__
);
1761 * Format a size in bytes for output, using an appropriate
1762 * unit (B, KB, MB or GB) according to the magnitude in question
1764 * @param $size Size to format
1767 public function formatSize( $size ) {
1769 return htmlspecialchars( $wgLang->formatSize( $size ) );
1773 * @deprecated Returns raw bits of HTML, use titleAttrib() and accesskey()
1775 public function tooltipAndAccesskey( $name ) {
1776 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1777 # no attribute" instead of "output '' as value for attribute", this
1778 # would be three lines.
1780 'title' => $this->titleAttrib( $name, 'withaccess' ),
1781 'accesskey' => $this->accesskey( $name )
1783 if ( $attribs['title'] === false ) {
1784 unset( $attribs['title'] );
1786 if ( $attribs['accesskey'] === false ) {
1787 unset( $attribs['accesskey'] );
1789 return Xml
::expandAttributes( $attribs );
1792 /** @deprecated Returns raw bits of HTML, use titleAttrib() */
1793 public function tooltip( $name, $options = null ) {
1794 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1795 # no attribute" instead of "output '' as value for attribute", this
1796 # would be two lines.
1797 $tooltip = $this->titleAttrib( $name, $options );
1798 if ( $tooltip === false ) {
1801 return Xml
::expandAttributes( array(
1802 'title' => $this->titleAttrib( $name, $options )
1807 * Given the id of an interface element, constructs the appropriate title
1808 * attribute from the system messages. (Note, this is usually the id but
1809 * isn't always, because sometimes the accesskey needs to go on a different
1810 * element than the id, for reverse-compatibility, etc.)
1812 * @param string $name Id of the element, minus prefixes.
1813 * @param mixed $options null or the string 'withaccess' to add an access-
1815 * @return string Contents of the title attribute (which you must HTML-
1816 * escape), or false for no title attribute
1818 public function titleAttrib( $name, $options = null ) {
1819 wfProfileIn( __METHOD__
);
1821 $tooltip = wfMsg( "tooltip-$name" );
1822 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1823 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1825 # Message equal to '-' means suppress it.
1826 if ( wfEmptyMsg( "tooltip-$name", $tooltip ) ||
$tooltip == '-' ) {
1830 if ( $options == 'withaccess' ) {
1831 $accesskey = $this->accesskey( $name );
1832 if( $accesskey !== false ) {
1833 if ( $tooltip === false ||
$tooltip === '' ) {
1834 $tooltip = "[$accesskey]";
1836 $tooltip .= " [$accesskey]";
1841 wfProfileOut( __METHOD__
);
1846 * Given the id of an interface element, constructs the appropriate
1847 * accesskey attribute from the system messages. (Note, this is usually
1848 * the id but isn't always, because sometimes the accesskey needs to go on
1849 * a different element than the id, for reverse-compatibility, etc.)
1851 * @param string $name Id of the element, minus prefixes.
1852 * @return string Contents of the accesskey attribute (which you must HTML-
1853 * escape), or false for no accesskey attribute
1855 public function accesskey( $name ) {
1856 wfProfileIn( __METHOD__
);
1858 $accesskey = wfMsg( "accesskey-$name" );
1860 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1861 # attribute, but this is broken for accesskey: that might be a useful
1863 if( $accesskey != '' && $accesskey != '-' && !wfEmptyMsg( "accesskey-$name", $accesskey ) ) {
1864 wfProfileOut( __METHOD__
);
1868 wfProfileOut( __METHOD__
);
1873 * Creates a (show/hide) link for deleting revisions/log entries
1875 * @param array $query Query parameters to be passed to link()
1876 * @param bool $restricted Set to true to use a <strong> instead of a <span>
1878 * @return string HTML <a> link to Special:Revisiondelete, wrapped in a
1879 * span to allow for customization of appearance with CSS
1881 public function revDeleteLink( $query = array(), $restricted = false ) {
1882 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1883 $text = wfMsgHtml( 'rev-delundel' );
1884 $tag = $restricted ?
'strong' : 'span';
1885 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1886 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );