Display permissions specific to the API (such as writeapi and apihighlimits) on actio...
[lhc/web/wiklou.git] / includes / Linker.php
index 2c94461..b913ebf 100644 (file)
@@ -1,15 +1,12 @@
 <?php
 /**
- * Split off some of the internal bits from Skin.php.
- * These functions are used for primarily page content:
- * links, embedded images, table of contents. Links are
- * also used in the skin.
- * For the moment, Skin is a descendent class of Linker.
- * In the future, it should probably be further split
- * so that ever other bit of the wiki doesn't have to
- * go loading up Skin to get at it.
+ * Split off some of the internal bits from Skin.php. These functions are used
+ * for primarily page content: links, embedded images, table of contents. Links
+ * are also used in the skin. For the moment, Skin is a descendent class of
+ * Linker.  In the future, it should probably be further split so that every
+ * other bit of the wiki doesn't have to go loading up Skin to get at it.
  *
- * @addtogroup Skins
+ * @ingroup Skins
  */
 class Linker {
 
@@ -23,75 +20,279 @@ class Linker {
        /**
         * @deprecated
         */
-       function postParseLinkColour( $s = NULL ) {
-               return NULL;
+       function postParseLinkColour( $s = null ) {
+               wfDeprecated( __METHOD__ );
+               return null;
        }
 
-       /** @todo document */
-       function getExternalLinkAttributes( $link, $text, $class='' ) {
-               $link = htmlspecialchars( $link );
-
-               $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
-
-               $r .= " title=\"{$link}\"";
-               return $r;
+       /**
+        * Get the appropriate HTML attributes to add to the "a" element of an ex-
+        * ternal link, as created by [wikisyntax].
+        *
+        * @param string $title  The (unescaped) title text for the link
+        * @param string $unused Unused
+        * @param string $class  The contents of the class attribute; if an empty
+        *   string is passed, which is the default value, defaults to 'external'.
+        */
+       function getExternalLinkAttributes( $title, $unused = null, $class='' ) {
+               return $this->getLinkAttributesInternal( $title, $class, 'external' );
        }
 
-       function getInterwikiLinkAttributes( $link, $text, $class='' ) {
+       /**
+        * Get the appropriate HTML attributes to add to the "a" element of an in-
+        * terwiki link.
+        *
+        * @param string $title  The title text for the link, URL-encoded (???) but
+        *   not HTML-escaped
+        * @param string $unused Unused
+        * @param string $class  The contents of the class attribute; if an empty
+        *   string is passed, which is the default value, defaults to 'external'.
+        */
+       function getInterwikiLinkAttributes( $title, $unused = null, $class='' ) {
                global $wgContLang;
 
-               $link = urldecode( $link );
-               $link = $wgContLang->checkTitleEncoding( $link );
-               $link = preg_replace( '/[\\x00-\\x1f]/', ' ', $link );
-               $link = htmlspecialchars( $link );
+               # FIXME: We have a whole bunch of handling here that doesn't happen in
+               # getExternalLinkAttributes, why?
+               $title = urldecode( $title );
+               $title = $wgContLang->checkTitleEncoding( $title );
+               $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
 
-               $r = ($class != '') ? " class=\"$class\"" : " class=\"external\"";
+               return $this->getLinkAttributesInternal( $title, $class, 'external' );
+       }
 
-               $r .= " title=\"{$link}\"";
-               return $r;
+       /**
+        * Get the appropriate HTML attributes to add to the "a" element of an in-
+        * ternal link.
+        *
+        * @param string $title  The title text for the link, URL-encoded (???) but
+        *   not HTML-escaped
+        * @param string $unused Unused
+        * @param string $class  The contents of the class attribute, default none
+        */
+       function getInternalLinkAttributes( $title, $unused = null, $class='' ) {
+               $title = urldecode( $title );
+               $title = str_replace( '_', ' ', $title );
+               return $this->getLinkAttributesInternal( $title, $class );
        }
 
-       /** @todo document */
-       function getInternalLinkAttributes( $link, $text, $class='' ) {
-               $link = urldecode( $link );
-               $link = str_replace( '_', ' ', $link );
-               $link = htmlspecialchars( $link );
-               $r = ($class != '') ? ' class="' . htmlspecialchars( $class ) . '"' : '';
-               $r .= " title=\"{$link}\"";
-               return $r;
+       /**
+        * Get the appropriate HTML attributes to add to the "a" element of an in-
+        * ternal link, given the Title object for the page we want to link to.
+        *
+        * @param Title  $nt     The Title object
+        * @param string $unused Unused
+        * @param string $class  The contents of the class attribute, default none
+        * @param mixed  $title  Optional (unescaped) string to use in the title
+        *   attribute; if false, default to the name of the page we're linking to
+        */
+       function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
+               if( $title === false ) {
+                       $title = $nt->getPrefixedText();
+               }
+               return $this->getLinkAttributesInternal( $title, $class );
        }
 
        /**
-        * @param $nt Title object.
-        * @param $text String: FIXME
-        * @param $class String: CSS class of the link, default ''.
+        * Common code for getLinkAttributesX functions
         */
-       function getInternalLinkAttributesObj( &$nt, $text, $class='' ) {
-               $r = ($class != '') ? ' class="' . htmlspecialchars( $class ) . '"' : '';
-               $r .= ' title="' . $nt->getEscapedText() . '"';
+       private function getLinkAttributesInternal( $title, $class, $classDefault = false ) {
+               $title = htmlspecialchars( $title );
+               if( $class === '' and $classDefault !== false ) {
+                       # FIXME: Parameter defaults the hard way!  We should just have
+                       # $class = 'external' or whatever as the default in the externally-
+                       # exposed functions, not $class = ''.
+                       $class = $classDefault;
+               }
+               $class = htmlspecialchars( $class );
+               $r = '';
+               if( $class !== '' ) {
+                       $r .= " class=\"$class\"";
+               }
+               $r .= " title=\"$title\"";
                return $r;
        }
 
        /**
         * Return the CSS colour of a known link
         *
-        * @param mixed $s
-        * @param integer $id 
-        * @param integer $threshold
+        * @param Title $t
+        * @param integer $threshold user defined threshold
+        * @return string CSS class
         */
-       function getLinkColour( $s, $threshold ) {
-               if( $threshold > 0 && $s!=false ) {
-                       $colour = (     $s->page_len >= $threshold || 
-                                       $s->page_is_redirect ||
-                                       !Namespace::isContent( $s->page_namespace ) 
-                           ? '' : 'stub' );
-               }
-               else {
-                       $colour = '';
+       function getLinkColour( $t, $threshold ) {
+               $colour = '';
+               if ( $t->isRedirect() ) {
+                       # Page is a redirect
+                       $colour = 'mw-redirect';
+               } elseif ( $threshold > 0 && $t->getLength() < $threshold && MWNamespace::isContent( $t->getNamespace() ) ) {
+                       # Page is a stub
+                       $colour = 'stub';
                }
                return $colour;
        }
 
+       /**
+        * This function returns an HTML link to the given target.  It serves a few
+        * purposes:
+        *   1) If $target is a Title, the correct URL to link to will be figured
+        *      out automatically.
+        *   2) It automatically adds the usual classes for various types of link
+        *      targets: "new" for red links, "stub" for short articles, etc.
+        *   3) It escapes all attribute values safely so there's no risk of XSS.
+        *   4) It provides a default tooltip if the target is a Title (the page
+        *      name of the target).
+        * link() replaces the old functions in the makeLink() family.
+        *
+        * @param $target        Title  Can currently only be a Title, but this may
+        *   change to support Images, literal URLs, etc.
+        * @param $text          string The HTML contents of the <a> element, i.e.,
+        *   the link text.  This is raw HTML and will not be escaped.  If null,
+        *   defaults to the prefixed text of the Title; or if the Title is just a
+        *   fragment, the contents of the fragment.
+        * @param $query         array  The query string to append to the URL
+        *   you're linking to, in key => value array form.  Query keys and values
+        *   will be URL-encoded.
+        * @param $customAttribs array  A key => value array of extra HTML attri-
+        *   butes, such as title and class.  (href is ignored.)  Classes will be
+        *   merged with the default classes, while other attributes will replace
+        *   default attributes.  All passed attribute values will be HTML-escaped.
+        *   A false attribute value means to suppress that attribute.
+        * @param $options       mixed  String or array of strings:
+        *     'known': Page is known to exist, so don't check if it does.
+        *     'broken': Page is known not to exist, so don't check if it does.
+        *     'noclasses': Don't add any classes automatically (includes "new",
+        *       "stub", "mw-redirect", "extiw").  Only use the class attribute
+        *       provided, if any, so you get a simple blue link with no funny i-
+        *       cons.
+        * @return string HTML <a> attribute
+        */
+       public function link( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
+               wfProfileIn( __METHOD__ );
+               if( !$target instanceof Title ) {
+                       throw new MWException( 'Linker::link passed invalid target' );
+               }
+               $options = (array)$options;
+
+               # Normalize the Title if it's a special page
+               $target = $this->normaliseSpecialPage( $target );
+
+               # If we don't know whether the page exists, let's find out.
+               wfProfileIn( __METHOD__ . '-checkPageExistence' );
+               if( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
+                       if( $target->getNamespace() == NS_SPECIAL ) {
+                               if( SpecialPage::exists( $target->getDbKey() ) ) {
+                                       $options []= 'known';
+                               } else {
+                                       $options []= 'broken';
+                               }
+                       } elseif( $target->isAlwaysKnown() or
+                       ($target->getPrefixedText() == '' and $target->getFragment() != '')
+                       or $target->exists() ) {
+                               $options []= 'known';
+                       } else {
+                               $options []= 'broken';
+                       }
+               }
+               wfProfileOut( __METHOD__ . '-checkPageExistence' );
+
+               # Note: we want the href attribute first, for prettiness.
+               $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
+               $attribs = array_merge(
+                       $attribs,
+                       $this->linkAttribs( $target, $customAttribs, $options )
+               );
+               if( is_null( $text ) ) {
+                       $text = $this->linkText( $target );
+               }
+
+               $ret = Xml::openElement( 'a', $attribs )
+                       . $text
+                       . Xml::closeElement( 'a' );
+
+               wfProfileOut( __METHOD__ );
+               return $ret;
+       }
+
+       private function linkUrl( $target, $query, $options ) {
+               wfProfileIn( __METHOD__ );
+               # If it's a broken link, add the appropriate query pieces, unless
+               # there's already an action specified, or unless 'edit' makes no sense
+               # (i.e., for a nonexistent special page).
+               if( in_array( 'broken', $options ) and empty( $query['action'] )
+               and $target->getNamespace() != NS_SPECIAL ) {
+                       $query['action'] = 'edit';
+                       $query['redlink'] = '1';
+               }
+               $ret = $target->getLinkUrl( $query );
+               wfProfileOut( __METHOD__ );
+               return $ret;
+       }
+
+       private function linkAttribs( $target, $attribs, $options ) {
+               wfProfileIn( __METHOD__ );
+               global $wgUser;
+               $defaults = array();
+
+               if( !in_array( 'noclasses', $options ) ) {
+                       wfProfileIn( __METHOD__ . '-getClasses' );
+                       # Build the classes.
+                       $classes = array();
+
+                       if( in_array( 'broken', $options ) ) {
+                               $classes[] = 'new';
+                       }
+
+                       if( $target->isExternal() ) {
+                               $classes[] = 'extiw';
+                       }
+
+                       # Note that redirects never count as stubs here.
+                       if ( $target->isRedirect() ) {
+                               $classes[] = 'mw-redirect';
+                       } elseif( $target->isContentPage() ) {
+                               # Check for stub.
+                               $threshold = $wgUser->getOption( 'stubthreshold' );
+                               if( $threshold > 0 and $target->getLength() < $threshold ) {
+                                       $classes[] = 'stub';
+                               }
+                       }
+                       if( $classes != array() ) {
+                               $defaults['class'] = implode( ' ', $classes );
+                       }
+                       wfProfileOut( __METHOD__ . '-getClasses' );
+               }
+
+               # Get a default title attribute.
+               if( in_array( 'known', $options ) ) {
+                       $defaults['title'] = $target->getPrefixedText();
+               } else {
+                       $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
+               }
+
+               # Finally, merge the custom attribs with the default ones, and iterate
+               # over that, deleting all "false" attributes.
+               $ret = array();
+               $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
+               foreach( $merged as $key => $val ) {
+                       # A false value suppresses the attribute, and we don't want the
+                       # href attribute to be overridden.
+                       if( $key != 'href' and $val !== false ) {
+                               $ret[$key] = $val;
+                       }
+               }
+               wfProfileOut( __METHOD__ );
+               return $ret;
+       }
+
+       private function linkText( $target ) {
+               # If the target is just a fragment, with no title, we return the frag-
+               # ment text.  Otherwise, we return the title text itself.
+               if( $target->getPrefixedText() === '' and $target->getFragment() !== '' ) {
+                       return htmlspecialchars( $target->getFragment() );
+               }
+               return htmlspecialchars( $target->getPrefixedText() );
+       }
+
        /**
         * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
         * it if you already have a title object handy. See makeLinkObj for further documentation.
@@ -120,7 +321,7 @@ class Linker {
        /**
         * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
         * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
-        * 
+        *
         * @param $title String: the text of the title
         * @param $text  String: link text
         * @param $query String: optional query part
@@ -141,7 +342,7 @@ class Linker {
        /**
         * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
         * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
-        * 
+        *
         * @param string $title The text of the title
         * @param string $text Link text
         * @param string $query Optional query part
@@ -161,10 +362,10 @@ class Linker {
 
        /**
         * @deprecated use makeColouredLinkObj
-        * 
+        *
         * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
         * it if you already have a title object handy. See makeStubLinkObj for further documentation.
-        * 
+        *
         * @param $title String: the text of the title
         * @param $text  String: link text
         * @param $query String: optional query part
@@ -186,7 +387,7 @@ class Linker {
         * Make a link for a title which may or may not be in the database. If you need to
         * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
         * call to this will result in a DB query.
-        * 
+        *
         * @param $nt     Title: the title object to make the link from, e.g. from
         *                      Title::newFromText.
         * @param $text  String: link text
@@ -196,16 +397,10 @@ class Linker {
         *                      the end of the link.
         * @param $prefix String: optional prefix. As trail, only before instead of after.
         */
-       function makeLinkObj( $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
+       function makeLinkObj( Title $nt, $text= '', $query = '', $trail = '', $prefix = '' ) {
                global $wgUser;
                wfProfileIn( __METHOD__ );
 
-               if ( !$nt instanceof Title ) {
-                       # Fail gracefully
-                       wfProfileOut( __METHOD__ );
-                       return "<!-- ERROR -->{$prefix}{$text}{$trail}";
-               }
-
                if ( $nt->isExternal() ) {
                        $u = $nt->getFullURL();
                        $link = $nt->getPrefixedURL();
@@ -225,14 +420,14 @@ class Linker {
                        wfProfileOut( __METHOD__ );
                        return $t;
                } elseif ( $nt->isAlwaysKnown() ) {
-                       # Image links, special page links and self-links with fragements are always known.
+                       # Image links, special page links and self-links with fragments are always known.
                        $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
                } else {
                        wfProfileIn( __METHOD__.'-immediate' );
 
-                       # Handles links to special pages wich do not exist in the database:
+                       # Handles links to special pages which do not exist in the database:
                        if( $nt->getNamespace() == NS_SPECIAL ) {
-                               if( SpecialPage::exists( $nt->getDbKey() ) ) {
+                               if( SpecialPage::exists( $nt->getDBkey() ) ) {
                                        $retVal = $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix );
                                } else {
                                        $retVal = $this->makeBrokenLinkObj( $nt, $text, $query, $trail, $prefix );
@@ -250,14 +445,7 @@ class Linker {
                                $colour = '';
                                if ( $nt->isContentPage() ) {
                                        $threshold = $wgUser->getOption('stubthreshold');
-                                       if ( $threshold > 0 ) {
-                                               $dbr = wfGetDB( DB_SLAVE );
-                                               $s = $dbr->selectRow(
-                                                       array( 'page' ),
-                                                       array( 'page_len', 'page_is_redirect', 'page_namespace' ),
-                                                       array( 'page_id' => $aid ), __METHOD__ ) ;
-                                               $colour = $this->getLinkColour( $s, $threshold );
-                                       }
+                                       $colour = $this->getLinkColour( $nt, $threshold );
                                }
                                $retVal = $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
                        }
@@ -281,14 +469,10 @@ class Linker {
         * @param $style  String: style to apply - if empty, use getInternalLinkAttributesObj instead
         * @return the a-element
         */
-       function makeKnownLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
+       function makeKnownLinkObj( Title $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
                wfProfileIn( __METHOD__ );
 
-               if ( !$nt instanceof Title ) {
-                       # Fail gracefully
-                       wfProfileOut( __METHOD__ );
-                       return "<!-- ERROR -->{$prefix}{$text}{$trail}";
-               }
+               $nt = $this->normaliseSpecialPage( $title );
 
                $u = $nt->escapeLocalURL( $query );
                if ( $nt->getFragment() != '' ) {
@@ -307,7 +491,7 @@ class Linker {
                        $style = $this->getInternalLinkAttributesObj( $nt, $text );
                }
 
-               if ( $aprops !== '' ) $aprops = ' ' . $aprops;
+               if ( $aprops !== '' ) $aprops = " $aprops";
 
                list( $inside, $trail ) = Linker::splitTrail( $trail );
                $r = "<a href=\"{$u}\"{$style}{$aprops}>{$prefix}{$text}{$inside}</a>{$trail}";
@@ -317,7 +501,7 @@ class Linker {
 
        /**
         * Make a red link to the edit page of a given title.
-        * 
+        *
         * @param $nt Title object of the target page
         * @param $text  String: Link text
         * @param $query String: Optional query part
@@ -325,30 +509,29 @@ class Linker {
         *                      be included in the link text. Other characters will be appended after
         *                      the end of the link.
         */
-       function makeBrokenLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
+       function makeBrokenLinkObj( Title $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
                wfProfileIn( __METHOD__ );
 
-               if ( !$nt instanceof Title ) {
-                       # Fail gracefully
-                       wfProfileOut( __METHOD__ );
-                       return "<!-- ERROR -->{$prefix}{$text}{$trail}";
-               }
+               $nt = $this->normaliseSpecialPage( $title );
 
                if( $nt->getNamespace() == NS_SPECIAL ) {
                        $q = $query;
                } else if ( '' == $query ) {
-                       $q = 'action=edit';
+                       $q = 'action=edit&redlink=1';
                } else {
-                       $q = 'action=edit&'.$query;
+                       $q = 'action=edit&redlink=1&'.$query;
                }
                $u = $nt->escapeLocalURL( $q );
 
+               $titleText = $nt->getPrefixedText();
                if ( '' == $text ) {
-                       $text = htmlspecialchars( $nt->getPrefixedText() );
+                       $text = htmlspecialchars( $titleText );
                }
-               $style = $this->getInternalLinkAttributesObj( $nt, $text, 'new' );
-
+               $titleAttr = wfMsg( 'red-link-title', $titleText );
+               $style = $this->getInternalLinkAttributesObj( $nt, $text, 'new', $titleAttr );
                list( $inside, $trail ) = Linker::splitTrail( $trail );
+
+               wfRunHooks( 'BrokenLink', array( &$this, $nt, $query, &$u, &$style, &$prefix, &$text, &$inside, &$trail ) );
                $s = "<a href=\"{$u}\"{$style}>{$prefix}{$text}{$inside}</a>{$trail}";
 
                wfProfileOut( __METHOD__ );
@@ -357,9 +540,9 @@ class Linker {
 
        /**
         * @deprecated use makeColouredLinkObj
-        * 
+        *
         * Make a brown link to a short article.
-        * 
+        *
         * @param $nt Title object of the target page
         * @param $text  String: link text
         * @param $query String: optional query part
@@ -368,12 +551,13 @@ class Linker {
         *                      the end of the link.
         */
        function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
+               wfDeprecated( __METHOD__ );
                return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
        }
 
        /**
         * Make a coloured link.
-        * 
+        *
         * @param $nt Title object of the target page
         * @param $colour Integer: colour of the link
         * @param $text   String:  link text
@@ -383,7 +567,6 @@ class Linker {
         *                      the end of the link.
         */
        function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
-
                if($colour != ''){
                        $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
                } else $style = '';
@@ -409,7 +592,7 @@ class Linker {
                return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
        }
 
-       /** 
+       /**
         * Make appropriate markup for a link to the current article. This is currently rendered
         * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
         * despite $query not being used.
@@ -422,6 +605,18 @@ class Linker {
                return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
        }
 
+       function normaliseSpecialPage( Title $title ) {
+               if ( $title->getNamespace() == NS_SPECIAL ) {
+                       list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $title->getDBkey() );
+                       if ( !$name ) return $title;
+                       $ret = SpecialPage::getTitleFor( $name, $subpage );
+                       $ret->mFragment = $title->getFragment();
+                       return $ret;
+               } else {
+                       return $title;
+               }
+       }
+
        /** @todo document */
        function fnamePart( $url ) {
                $basename = strrchr( $url, '/' );
@@ -430,11 +625,12 @@ class Linker {
                } else {
                        $basename = substr( $basename, 1 );
                }
-               return htmlspecialchars( $basename );
+               return $basename;
        }
 
        /** Obsolete alias */
        function makeImage( $url, $alt = '' ) {
+               wfDeprecated( __METHOD__ );
                return $this->makeExternalImage( $url, $alt );
        }
 
@@ -443,11 +639,19 @@ class Linker {
                if ( '' == $alt ) {
                        $alt = $this->fnamePart( $url );
                }
-               $s = '<img src="'.$url.'" alt="'.$alt.'" />';
-               return $s;
+               $img = '';
+               $success = wfRunHooks('LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
+               if(!$success) {
+                       wfDebug("Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}", true);
+                       return $img;
+               }
+               return Xml::element( 'img',
+                       array(
+                               'src' => $url,
+                               'alt' => $alt ) );
        }
 
-       /** 
+       /**
         * Creates the HTML source for images
         * @deprecated use makeImageLink2
         *
@@ -460,6 +664,7 @@ class Linker {
         * @param boolean $thumb shows image as thumbnail in a frame
         * @param string $manualthumb image name for the manual thumbnail
         * @param string $valign vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
+        * @param string $time, timestamp of the file, set as false for current
         * @return string
         */
        function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
@@ -482,16 +687,18 @@ class Linker {
                        $frameParams['valign'] = $valign;
                }
                $file = wfFindFile( $title, $time );
-               return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams );
+               return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
        }
 
        /**
-        * Make an image link
+        * Given parameters derived from [[Image:Foo|options...]], generate the
+        * HTML that that syntax inserts in the page.
+        *
         * @param Title $title Title object
         * @param File $file File object, or false if it doesn't exist
         *
         * @param array $frameParams Associative array of parameters external to the media handler.
-        *     Boolean parameters are indicated by presence or absence, the value is arbitrary and 
+        *     Boolean parameters are indicated by presence or absence, the value is arbitrary and
         *     will often be false.
         *          thumbnail       If present, downscale and frame
         *          manualthumb     Image name to use as a thumbnail, instead of automatic scaling
@@ -501,19 +708,28 @@ class Linker {
         *          upright_factor  Fudge factor for "upright" tweak (default 0.75)
         *          border          If present, show a border around the image
         *          align           Horizontal alignment (left, right, center, none)
-        *          valign          Vertical alignment (baseline, sub, super, top, text-top, middle, 
+        *          valign          Vertical alignment (baseline, sub, super, top, text-top, middle,
         *                          bottom, text-bottom)
         *          alt             Alternate text for image (i.e. alt attribute). Plain text.
         *          caption         HTML for image caption.
         *
-        * @param array $handlerParams Associative array of media handler parameters, to be passed 
-        *       to transform(). Typical keys are "width" and "page". 
+        * @param array $handlerParams Associative array of media handler parameters, to be passed
+        *       to transform(). Typical keys are "width" and "page".
+        * @param string $time, timestamp of the file, set as false for current
+        * @param string $query, query params for desc url
+        * @return string HTML for an image, with links, wrappers, etc.
         */
-       function makeImageLink2( Title $title, $file, $frameParams = array(), $handlerParams = array() ) {
+       function makeImageLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
+               $res = null;
+               if( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
+               &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
+                       return $res;
+               }
+
                global $wgContLang, $wgUser, $wgThumbLimits, $wgThumbUpright;
                if ( $file && !$file->allowInlineDisplay() ) {
                        wfDebug( __METHOD__.': '.$title->getPrefixedDBkey()." does not allow inline display\n" );
-                       return $this->makeKnownLinkObj( $title );
+                       return $this->link( $title );
                }
 
                // Shortcuts
@@ -549,8 +765,8 @@ class Linker {
                                }
                                // Use width which is smaller: real image width or user preference width
                                // 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
-                               $prefWidth = isset( $fp['upright'] ) ? 
-                                       round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) : 
+                               $prefWidth = isset( $fp['upright'] ) ?
+                                       round( $wgThumbLimits[$wopt] * $fp['upright'], -1 ) :
                                        $wgThumbLimits[$wopt];
                                if ( $hp['width'] <= 0 || $prefWidth < $hp['width'] ) {
                                        $hp['width'] = $prefWidth;
@@ -570,7 +786,7 @@ class Linker {
                        if ( $fp['align'] == '' ) {
                                $fp['align'] = $wgContLang->isRTL() ? 'left' : 'right';
                        }
-                       return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp ).$postfix;
+                       return $prefix.$this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ).$postfix;
                }
 
                if ( $file && isset( $fp['frameless'] ) ) {
@@ -590,10 +806,11 @@ class Linker {
                }
 
                if ( !$thumb ) {
-                       $s = $this->makeBrokenImageLinkObj( $title );
+                       $s = $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
                } else {
                        $s = $thumb->toHtml( array(
                                'desc-link' => true,
+                               'desc-query' => $query,
                                'alt' => $fp['alt'],
                                'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false ,
                                'img-class' => isset( $fp['border'] ) ? 'thumbborder' : false ) );
@@ -606,11 +823,11 @@ class Linker {
 
        /**
         * Make HTML for a thumbnail including image, border and caption
-        * @param Title $title 
+        * @param Title $title
         * @param File $file File object or false if it doesn't exist
         */
        function makeThumbLinkObj( Title $title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed=false , $manualthumb = "" ) {
-               $frameParams = array( 
+               $frameParams = array(
                        'alt' => $alt,
                        'caption' => $label,
                        'align' => $align
@@ -620,7 +837,7 @@ class Linker {
                return $this->makeThumbLink2( $title, $file, $frameParams, $params );
        }
 
-       function makeThumbLink2( Title $title, $file, $frameParams = array(), $handlerParams = array() ) {
+       function makeThumbLink2( Title $title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
                global $wgStylePath, $wgContLang;
                $exists = $file && $file->exists();
 
@@ -634,7 +851,7 @@ class Linker {
                if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
 
                if ( empty( $hp['width'] ) ) {
-                       // Reduce width for upright images when parameter 'upright' is used 
+                       // Reduce width for upright images when parameter 'upright' is used
                        $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
                }
                $thumb = false;
@@ -673,16 +890,16 @@ class Linker {
                        }
                }
 
-               $query = $page ? 'page=' . urlencode( $page ) : '';
+               if( $page ) {
+                       $query = $query ? '&page=' . urlencode( $page ) : 'page=' . urlencode( $page );
+               }
                $url = $title->getLocalURL( $query );
 
                $more = htmlspecialchars( wfMsg( 'thumbnail-more' ) );
-               $magnifyalign = $wgContLang->isRTL() ? 'left' : 'right';
-               $textalign = $wgContLang->isRTL() ? ' style="text-align:right"' : '';
 
                $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
                if( !$exists ) {
-                       $s .= $this->makeBrokenImageLinkObj( $title );
+                       $s .= $this->makeBrokenImageLinkObj( $title, '', '', '', '', $time==true );
                        $zoomicon = '';
                } elseif ( !$thumb ) {
                        $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
@@ -691,17 +908,18 @@ class Linker {
                        $s .= $thumb->toHtml( array(
                                'alt' => $fp['alt'],
                                'img-class' => 'thumbimage',
-                               'desc-link' => true ) );
+                               'desc-link' => true,
+                               'desc-query' => $query ) );
                        if ( isset( $fp['framed'] ) ) {
                                $zoomicon="";
                        } else {
-                               $zoomicon =  '<div class="magnify" style="float:'.$magnifyalign.'">'.
+                               $zoomicon =  '<div class="magnify">'.
                                        '<a href="'.$url.'" class="internal" title="'.$more.'">'.
                                        '<img src="'.$wgStylePath.'/common/images/magnify-clip.png" ' .
                                        'width="15" height="11" alt="" /></a></div>';
                        }
                }
-               $s .= '  <div class="thumbcaption"'.$textalign.'>'.$zoomicon.$fp['caption']."</div></div></div>";
+               $s .= '  <div class="thumbcaption">'.$zoomicon.$fp['caption']."</div></div></div>";
                return str_replace("\n", ' ', $s);
        }
 
@@ -713,16 +931,22 @@ class Linker {
         * @param string $query Query string
         * @param string $trail Link trail
         * @param string $prefix Link prefix
+        * @param bool $time, a file of a certain timestamp was requested
         * @return string
         */
-       public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
+       public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
                global $wgEnableUploads;
                if( $title instanceof Title ) {
                        wfProfileIn( __METHOD__ );
-                       if( $wgEnableUploads ) {
+                       $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
+                       if( $wgEnableUploads && !$currentExists ) {
                                $upload = SpecialPage::getTitleFor( 'Upload' );
                                if( $text == '' )
                                        $text = htmlspecialchars( $title->getPrefixedText() );
+                               $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
+                               if( $redir ) {
+                                       return $this->makeKnownLinkObj( $title, $text, $query, $trail, $prefix );
+                               }
                                $q = 'wpDestFile=' . $title->getPartialUrl();
                                if( $query != '' )
                                        $q .= '&' . $query;
@@ -741,33 +965,34 @@ class Linker {
        }
 
        /** @deprecated use Linker::makeMediaLinkObj() */
-       function makeMediaLink( $name, $unused = '', $text = '' ) {
+       function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
                $nt = Title::makeTitleSafe( NS_IMAGE, $name );
-               return $this->makeMediaLinkObj( $nt, $text );
+               return $this->makeMediaLinkObj( $nt, $text, $time );
        }
 
        /**
         * Create a direct link to a given uploaded file.
         *
         * @param $title Title object.
-        * @param $text  String: pre-sanitized HTML
+        * @param $text String: pre-sanitized HTML
+        * @param $time string: time image was created
         * @return string HTML
         *
         * @public
         * @todo Handle invalid or missing images better.
         */
-       function makeMediaLinkObj( $title, $text = '' ) {
+       function makeMediaLinkObj( $title, $text = '', $time = false ) {
                if( is_null( $title ) ) {
                        ### HOTFIX. Instead of breaking, return empty string.
                        return $text;
                } else {
-                       $img  = wfFindFile( $title );
+                       $img  = wfFindFile( $title, $time );
                        if( $img ) {
                                $url  = $img->getURL();
                                $class = 'internal';
                        } else {
                                $upload = SpecialPage::getTitleFor( 'Upload' );
-                               $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDbKey() ) );
+                               $url = $upload->getLocalUrl( 'wpDestFile=' . urlencode( $title->getDBkey() ) );
                                $class = 'new';
                        }
                        $alt = htmlspecialchars( $title->getText() );
@@ -800,6 +1025,12 @@ class Linker {
                if( $escape ) {
                        $text = htmlspecialchars( $text );
                }
+               $link = '';
+               $success = wfRunHooks('LinkerMakeExternalLink', array( &$url, &$text, &$link ) );
+               if(!$success) {
+                       wfDebug("Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}", true);
+                       return $link;
+               }
                return '<a href="'.$url.'"'.$style.'>'.$text.'</a>';
        }
 
@@ -811,15 +1042,12 @@ class Linker {
         * @private
         */
        function userLink( $userId, $userText ) {
-               $encName = htmlspecialchars( $userText );
                if( $userId == 0 ) {
-                       $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
-                       return $this->makeKnownLinkObj( $contribsPage,
-                               $encName);
+                       $page = SpecialPage::getTitleFor( 'Contributions', $userText );
                } else {
-                       $userPage = Title::makeTitle( NS_USER, $userText );
-                       return $this->makeLinkObj( $userPage, $encName );
+                       $page = Title::makeTitle( NS_USER, $userText );
                }
+               return $this->link( $page, htmlspecialchars( $userText ) );
        }
 
        /**
@@ -829,9 +1057,10 @@ class Linker {
         * @param string $userText User name or IP address
         * @param bool $redContribsWhenNoEdits Should the contributions link be red if the user has no edits?
         * @param int $flags Customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
+        * @param int $edits, user edit count (optional, for performance)
         * @return string
         */
-       public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0 ) {
+       public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits=null ) {
                global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans;
                $talkable = !( $wgDisableAnonTalk && 0 == $userId );
                $blockable = ( $wgSysopUserBans || 0 == $userId ) && !$flags & self::TOOL_LINKS_NOBLOCK;
@@ -842,14 +1071,16 @@ class Linker {
                }
                if( $userId ) {
                        // check if the user has an edit
-                       if( $redContribsWhenNoEdits && User::edits( $userId ) == 0 ) {
-                               $style = " class='new'";
-                       } else {
-                               $style = '';
+                       $attribs = array();
+                       if( $redContribsWhenNoEdits ) {
+                               $count = !is_null($edits) ? $edits : User::edits( $userId );
+                               if( $count == 0 ) {
+                                       $attribs['class'] = 'new';
+                               }
                        }
                        $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
 
-                       $items[] = $this->makeKnownLinkObj( $contribsPage, wfMsgHtml( 'contribslink' ), '', '', '', '', $style );
+                       $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
                }
                if( $blockable && $wgUser->isAllowed( 'block' ) ) {
                        $items[] = $this->blockLink( $userId, $userText );
@@ -864,9 +1095,12 @@ class Linker {
 
        /**
         * Alias for userToolLinks( $userId, $userText, true );
+        * @param int $userId User identifier
+        * @param string $userText User name or IP address
+        * @param int $edits, user edit count (optional, for performance)
         */
-       public function userToolLinksRedContribs( $userId, $userText ) {
-               return $this->userToolLinks( $userId, $userText, true );
+       public function userToolLinksRedContribs( $userId, $userText, $edits=null ) {
+               return $this->userToolLinks( $userId, $userText, true, 0, $edits );
        }
 
 
@@ -878,7 +1112,7 @@ class Linker {
         */
        function userTalkLink( $userId, $userText ) {
                $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
-               $userTalkLink = $this->makeLinkObj( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
+               $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
                return $userTalkLink;
        }
 
@@ -890,18 +1124,20 @@ class Linker {
         */
        function blockLink( $userId, $userText ) {
                $blockPage = SpecialPage::getTitleFor( 'Blockip', $userText );
-               $blockLink = $this->makeKnownLinkObj( $blockPage,
-                       wfMsgHtml( 'blocklink' ) );
+               $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
                return $blockLink;
        }
-       
+
        /**
         * Generate a user link if the current user is allowed to view it
         * @param $rev Revision object.
+        * @param $isPublic, bool, show only if all users can see it
         * @return string HTML
         */
-       function revUserLink( $rev ) {
-               if( $rev->userCan( Revision::DELETED_USER ) ) {
+       function revUserLink( $rev, $isPublic = false ) {
+               if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
+                       $link = wfMsgHtml( 'rev-deleted-user' );
+               } else if( $rev->userCan( Revision::DELETED_USER ) ) {
                        $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() );
                } else {
                        $link = wfMsgHtml( 'rev-deleted-user' );
@@ -915,22 +1151,24 @@ class Linker {
        /**
         * Generate a user tool link cluster if the current user is allowed to view it
         * @param $rev Revision object.
+        * @param $isPublic, bool, show only if all users can see it
         * @return string HTML
         */
-       function revUserTools( $rev ) {
-               if( $rev->userCan( Revision::DELETED_USER ) ) {
+       function revUserTools( $rev, $isPublic = false ) {
+               if( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
+                       $link = wfMsgHtml( 'rev-deleted-user' );
+               } else if( $rev->userCan( Revision::DELETED_USER ) ) {
                        $link = $this->userLink( $rev->getRawUser(), $rev->getRawUserText() ) .
-                               ' ' .
-                               $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
+                       ' ' . $this->userToolLinks( $rev->getRawUser(), $rev->getRawUserText() );
                } else {
                        $link = wfMsgHtml( 'rev-deleted-user' );
                }
                if( $rev->isDeleted( Revision::DELETED_USER ) ) {
-                       return '<span class="history-deleted">' . $link . '</span>';
+                       return ' <span class="history-deleted">' . $link . '</span>';
                }
                return $link;
        }
-       
+
        /**
         * This function is called by all recent changes variants, by the page history,
         * and by the user contributions list. It is responsible for formatting edit
@@ -969,12 +1207,13 @@ class Linker {
         * add a separator where needed and format the comment itself with CSS
         * Called by Linker::formatComment.
         *
-        * @param $comment Comment text
-        * @param $title An optional title object used to links to sections
+        * @param string $comment Comment text
+        * @param object $title An optional title object used to links to sections
+        * @return string $comment formatted comment
         *
         * @todo Document the $local parameter.
         */
-       private function formatAutocomments( $comment, $title = NULL, $local = false ) {
+       private function formatAutocomments( $comment, $title = null, $local = false ) {
                $match = array();
                while (preg_match('!(.*)/\*\s*(.*?)\s*\*/(.*)!', $comment,$match)) {
                        $pre=$match[1];
@@ -993,19 +1232,26 @@ class Linker {
                                $section = str_replace( '[[', '', $section );
                                $section = str_replace( ']]', '', $section );
                                if ( $local ) {
-                                       $sectionTitle = Title::newFromText( '#' . $section);
+                                       $sectionTitle = Title::newFromText( '#' . $section );
                                } else {
-                                       $sectionTitle = wfClone( $title );
+                                       $sectionTitle = clone( $title );
                                        $sectionTitle->mFragment = $section;
                                }
-                               $link = $this->makeKnownLinkObj( $sectionTitle, wfMsg( 'sectionlink' ) );
+                               $link = $this->link( $sectionTitle,
+                                       wfMsgForContent( 'sectionlink' ), array(), array(),
+                                       'noclasses' );
+                       }
+                       $auto = $link . $auto;
+                       if( $pre ) {
+                               # written summary $presep autocomment (summary /* section */)
+                               $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
+                       }
+                       if( $post ) {
+                               # autocomment $postsep written summary (/* section */ summary)
+                               $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
                        }
-                       $sep='-';
-                       $auto=$link.$auto;
-                       if($pre) { $auto = $sep.' '.$auto; }
-                       if($post) { $auto .= ' '.$sep; }
-                       $auto='<span class="autocomment">'.$auto.'</span>';
-                       $comment=$pre.$auto.$post;
+                       $auto = '<span class="autocomment">' . $auto . '</span>';
+                       $comment = $pre . $auto . $post;
                }
 
                return $comment;
@@ -1025,15 +1271,20 @@ class Linker {
                        array( $this, 'formatLinksInCommentCallback' ),
                        $comment );
        }
-       
+
        protected function formatLinksInCommentCallback( $match ) {
                global $wgContLang;
 
-               $medians = '(?:' . preg_quote( Namespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
+               $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
                $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
-               
+
                $comment = $match[0];
 
+               # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
+               if( strpos( $match[1], '%' ) !== false ) {
+                       $match[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($match[1]) );
+               }
+
                # Handle link renaming [[foo|text]] will show link as "text"
                if( "" != $match[3] ) {
                        $text = $match[3];
@@ -1090,14 +1341,16 @@ class Linker {
         *
         * @param Revision $rev
         * @param bool $local Whether section links should refer to local page
+        * @param $isPublic, show only if all users can see it
         * @return string HTML
         */
-       function revComment( Revision $rev, $local = false ) {
-               if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
+       function revComment( Revision $rev, $local = false, $isPublic = false ) {
+               if( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
+                       $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
+               } else if( $rev->userCan( Revision::DELETED_COMMENT ) ) {
                        $block = $this->commentBlock( $rev->getRawComment(), $rev->getTitle(), $local );
                } else {
-                       $block = " <span class=\"comment\">" .
-                               wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
+                       $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
                }
                if( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
                        return " <span class=\"history-deleted\">$block</span>";
@@ -1105,6 +1358,18 @@ class Linker {
                return $block;
        }
 
+       public function formatRevisionSize( $size ) {
+               if ( $size == 0 ) {
+                       $stxt = wfMsgExt( 'historyempty', 'parsemag' );
+               } else {
+                       global $wgLang;
+                       $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
+                       $stxt = "($stxt)";
+               }
+               $stxt = htmlspecialchars( $stxt );
+               return "<span class=\"history-size\">$stxt</span>";
+       }
+
        /** @todo document */
        function tocIndent() {
                return "\n<ul>";
@@ -1158,8 +1423,9 @@ class Linker {
         * @param $section Integer: section number.
         */
        public function editSectionLinkForOther( $title, $section ) {
+               wfDeprecated( __METHOD__ );
                $title = Title::newFromText( $title );
-               return $this->doEditSectionLink( $title, $section, '', 'EditSectionLinkForOther' );
+               return $this->doEditSectionLink( $title, $section );
        }
 
        /**
@@ -1167,49 +1433,64 @@ class Linker {
         * @param $section Integer: section number.
         * @param $hint Link String: title, or default if omitted or empty
         */
-       public function editSectionLink( Title $nt, $section, $hint='' ) {
-               if( $hint != '' ) {
-                       $hint = wfMsgHtml( 'editsectionhint', htmlspecialchars( $hint ) );
-                       $hint = " title=\"$hint\"";
+       public function editSectionLink( Title $nt, $section, $hint = '' ) {
+               wfDeprecated( __METHOD__ );
+               if( $hint === '' ) {
+                       # No way to pass an actual empty $hint here!  The new interface al-
+                       # lows this, so we have to do this for compatibility.
+                       $hint = null;
                }
-               return $this->doEditSectionLink( $nt, $section, $hint, 'EditSectionLink' );
+               return $this->doEditSectionLink( $nt, $section, $hint );
        }
 
        /**
-        * Implement editSectionLink and editSectionLinkForOther.
+        * Create a section edit link.  This supersedes editSectionLink() and
+        * editSectionLinkForOther().
         *
-        * @param $nt      Title object
-        * @param $section Integer, section number
-        * @param $hint    String, for HTML title attribute
-        * @param $hook    String, name of hook to run
-        * @return         String, HTML to use for edit link
+        * @param $nt      Title  The title being linked to (may not be the same as
+        *   $wgTitle, if the section is included from a template)
+        * @param $section string The designation of the section being pointed to,
+        *   to be included in the link, like "&section=$section"
+        * @param $tooltip string The tooltip to use for the link: will be escaped
+        *   and wrapped in the 'editsectionhint' message
+        * @return         string HTML to use for edit link
         */
-       protected function doEditSectionLink( Title $nt, $section, $hint, $hook ) {
-               global $wgContLang;
-               $editurl = '&section='.$section;
-               $url = $this->makeKnownLinkObj(
-                       $nt,
-                       wfMsg('editsection'),
-                       'action=edit'.$editurl,
-                       '', '', '',  $hint
+       public function doEditSectionLink( Title $nt, $section, $tooltip = null ) {
+               $attribs = array();
+               if( !is_null( $tooltip ) ) {
+                       $attribs['title'] = wfMsg( 'editsectionhint', $tooltip );
+               }
+               $url = $this->link( $nt, wfMsg('editsection'),
+                       $attribs,
+                       array( 'action' => 'edit', 'section' => $section ),
+                       array( 'noclasses', 'known' )
                );
-               $result = null;
 
-               // The two hooks have slightly different interfaces . . .
-               if( $hook == 'EditSectionLink' ) {
-                       wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $hint, $url, &$result ) );
-               } elseif( $hook == 'EditSectionLinkForOther' ) {
-                       wfRunHooks( 'EditSectionLinkForOther', array( &$this, $nt, $section, $url, &$result ) );
-               }
-               
-               // For reverse compatibility, add the brackets *after* the hook is run,
-               // and even add them to hook-provided text.
-               if( is_null( $result ) ) {
-                       $result = wfMsg( 'editsection-brackets', $url );
-               } else {
-                       $result = wfMsg( 'editsection-brackets', $result );
+               # Run the old hook.  This takes up half of the function . . . hopefully
+               # we can rid of it someday.
+               $attribs = '';
+               if( $tooltip ) {
+                       $attribs = wfMsgHtml( 'editsectionhint', htmlspecialchars( $tooltip ) );
+                       $attribs = " title=\"$attribs\"";
+               }
+               $result = null;
+               wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $url, &$result ) );
+               if( !is_null( $result ) ) {
+                       # For reverse compatibility, add the brackets *after* the hook is
+                       # run, and even add them to hook-provided text.  (This is the main
+                       # reason that the EditSectionLink hook is deprecated in favor of
+                       # DoEditSectionLink: it can't change the brackets or the span.)
+                       $result = wfMsgHtml( 'editsection-brackets', $url );
+                       return "<span class=\"editsection\">$result</span>";
                }
-               return "<span class=\"editsection\">$result</span>";
+
+               # Add the brackets and the span, and *then* run the nice new hook, with
+               # clean and non-redundant arguments.
+               $result = wfMsgHtml( 'editsection-brackets', $url );
+               $result = "<span class=\"editsection\">$result</span>";
+
+               wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result ) );
+               return $result;
        }
 
        /**
@@ -1269,7 +1550,7 @@ class Linker {
                        . $this->buildRollbackLink( $rev )
                        . ']</span>';
        }
-       
+
        /**
         * Build a raw rollback link, useful for collections of "tool" links
         *
@@ -1279,14 +1560,17 @@ class Linker {
        public function buildRollbackLink( $rev ) {
                global $wgRequest, $wgUser;
                $title = $rev->getTitle();
-               $extra  = $wgRequest->getBool( 'bot' ) ? '&bot=1' : '';
-               $extra .= '&token=' . urlencode( $wgUser->editToken( array( $title->getPrefixedText(),
-                       $rev->getUserText() ) ) );
-               return $this->makeKnownLinkObj(
-                       $title,
-                       wfMsgHtml( 'rollbacklink' ),
-                       'action=rollback&from=' . urlencode( $rev->getUserText() ) . $extra
-               );              
+               $query = array(
+                       'action' => 'rollback',
+                       'from' => $rev->getUserText()
+               );
+               if( $wgRequest->getBool( 'bot' ) ) {
+                       $query['bot'] = '1';
+               }
+               $query['token'] = $wgUser->editToken( array( $title->getPrefixedText(),
+                       $rev->getUserText() ) );
+               return $this->link( $title, wfMsgHtml( 'rollbacklink' ), array(),
+                       $query, array( 'known', 'noclasses' ) );
        }
 
        /**
@@ -1324,23 +1608,53 @@ class Linker {
                        }
                        $outText .= '</div><ul>';
 
+                       usort( $templates, array( 'Title', 'compare' ) );
                        foreach ( $templates as $titleObj ) {
                                $r = $titleObj->getRestrictions( 'edit' );
-                               if ( in_array( 'sysop', $r ) ) { 
+                               if ( in_array( 'sysop', $r ) ) {
                                        $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
                                } elseif ( in_array( 'autoconfirmed', $r ) ) {
                                        $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
                                } else {
                                        $protected = '';
                                }
-                               $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . ' ' . $protected . '</li>';
+                               $outText .= '<li>' . $sk->link( $titleObj ) . ' ' . $protected . '</li>';
                        }
                        $outText .= '</ul>';
                }
                wfProfileOut( __METHOD__  );
                return $outText;
        }
-       
+
+       /**
+        * Returns HTML for the "hidden categories on this page" list.
+        *
+        * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
+        * or similar
+        * @return string HTML output
+        */
+       public function formatHiddenCategories( $hiddencats) {
+               global $wgUser, $wgLang;
+               wfProfileIn( __METHOD__ );
+
+               $sk = $wgUser->getSkin();
+
+               $outText = '';
+               if ( count( $hiddencats ) > 0 ) {
+                       # Construct the HTML
+                       $outText = '<div class="mw-hiddenCategoriesExplanation">';
+                       $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
+                       $outText .= '</div><ul>';
+
+                       foreach ( $hiddencats as $titleObj ) {
+                               $outText .= '<li>' . $sk->link( $titleObj, null, array(), array(), 'known' ) . '</li>'; # If it's hidden, it must exist - no need to check with a LinkBatch
+                       }
+                       $outText .= '</ul>';
+               }
+               wfProfileOut( __METHOD__  );
+               return $outText;
+       }
+
        /**
         * Format a size in bytes for output, using an appropriate
         * unit (B, KB, MB or GB) according to the magnitude in question