Experimental callback-based template processor, including MonoBook port.
authorTim Starling <tstarling@users.mediawiki.org>
Thu, 16 Mar 2006 03:03:53 +0000 (03:03 +0000)
committerTim Starling <tstarling@users.mediawiki.org>
Thu, 16 Mar 2006 03:03:53 +0000 (03:03 +0000)
includes/CBTProcessor.php [new file with mode: 0644]
skins/MonoBook.tpl [new file with mode: 0644]
skins/disabled/MonoBookCBT.php [new file with mode: 0644]

diff --git a/includes/CBTProcessor.php b/includes/CBTProcessor.php
new file mode 100644 (file)
index 0000000..0840bb2
--- /dev/null
@@ -0,0 +1,568 @@
+<?php
+
+/**
+ * PHP version of the callback template processor
+ * This is currently used as a test rig and is likely to be used for 
+ * compatibility purposes later, where the C++ extension is not available.
+ *
+ * Template syntax
+ * ---------------
+ *
+ * There are two modes: text mode and function mode. The brace characters "{" 
+ * and "}" are the only reserved characters. Either one of them will switch from
+ * text mode to function mode wherever they appear, no exceptions. 
+ *
+ * In text mode, all characters are passed through to the output. In function
+ * mode, text is split into tokens, delimited either by whitespace or by 
+ * matching pairs of braces. The first token is taken to be a function name. The
+ * other tokens are first processed in function mode themselves, then they are 
+ * passed to the named function as parameters. The return value of the function
+ * is passed through to the output.
+ *
+ * Example:
+ *    {escape {"hello"}}
+ *
+ * First brace switches to function mode. The function name is escape, the first
+ * and only parameter is {"hello"}. This parameter is executed. The braces around
+ * the parameter cause the parser to switch to text mode, thus the string "hello",
+ * including the quotes, is passed back and used as an argument to the escape 
+ * function. 
+ *
+ * Example:
+ *    {if title {<h1>{title}</h1>}}
+ *
+ * The function name is "if". The first parameter is the result of calling the 
+ * function "title". The second parameter is a level 1 HTML heading containing
+ * the result of the function "title". "if" is a built-in function which will 
+ * return the second parameter only if the first is non-blank, so the effect of
+ * this is to return a heading element only if a title exists.
+ *
+ * As a shortcut for generation of HTML attributes, if a function mode segment is
+ * surrounded by double quotes, quote characters in the return value will be 
+ * escaped. This only applies if the quote character immediately precedes the 
+ * opening brace, and immediately follows the closing brace, with no whitespace.
+ *
+ * User callback functions are defined by passing a function object to the 
+ * template processor. Function names appearing in the text are first checked
+ * against built-in function names, then against the method names in the function
+ * object. The function object forms a sandbox for execution of the template, so 
+ * security-conscious users may wish to avoid including functions that allow
+ * arbitrary filesystem access or code execution.
+ *
+ * The callback function will receive its parameters as strings. If the 
+ * result of the function depends only on the arguments, and certain things 
+ * understood to be "static", such as the source code, then the callback function
+ * should return a string. If the result depends on other things, then the function
+ * should return an object:
+ *
+ *    return new TplValue( $text, $deps );
+ *
+ * where $deps is an array of string tokens, each one naming a dependency. As a 
+ * shortcut, if there is only one dependency, $deps may be a string.
+ * 
+ */
+
+
+define( 'TP_WHITE', " \t\r\n" );
+define( 'TP_BRACE', '{}' );
+define( 'TP_DELIM', TP_WHITE . TP_BRACE );
+define( 'TP_DEBUG', 0 );
+
+/**
+ * Attempting to be a MediaWiki-independent module
+ */
+if ( !function_exists( 'wfProfileIn' ) ) {
+       function wfProfileIn() {}
+}
+if ( !function_exists( 'wfProfileOut' ) ) {
+       function wfProfileOut() {}
+}
+
+/**
+ * Escape text for inclusion in template
+ */
+function templateEscape( $text ) {
+       return strtr( $text, array( '{' => '{[}', '}' => '{]}' ) );
+}
+
+/**
+ * A dependency-tracking value class
+ * Callback functions should return one of these, unless they have 
+ * no dependencies in which case they can return a string.
+ */ 
+class TplValue {
+       var $mText, $mDeps, $mIsTemplate;
+
+       /**
+        * Create a new value
+        * @param string $text
+        * @param array $deps What this value depends on
+        * @param bool $isTemplate whether the result needs compilation/execution
+        */
+       function TplValue( $text = '', $deps = array(), $isTemplate = false ) {
+               $this->mText = $text;
+               if ( !is_array( $deps ) ) {
+                       $this->mDeps = array( $deps ) ;
+               } else {
+                       $this->mDeps = $deps;
+               }
+               $this->mIsTemplate = $isTemplate;
+       }
+
+       /** Concatenate two values, merging their dependencies */
+       function cat( $val ) {
+               if ( is_object( $val ) ) {
+                       $this->addDeps( $val );
+                       $this->mText .= $val->mText;
+               } else {
+                       $this->mText .= $val;
+               }
+       }
+
+       /** Add the dependencies of another value to this one */
+       function addDeps( $values ) {
+               if ( !is_array( $values ) ) {
+                       $this->mDeps = array_merge( $this->mDeps, $values->mDeps );
+               } else {
+                       foreach ( $values as $val ) {
+                               if ( !is_object( $val ) ) {
+                                       var_dump( debug_backtrace() );
+                                       exit;
+                               }
+                               $this->mDeps = array_merge( $this->mDeps, $val->mDeps );
+                       }
+               }
+       }
+
+       /** Remove a list of dependencies */
+       function removeDeps( $deps ) {
+               $this->mDeps = array_diff( $this->mDeps, $deps );
+       }
+
+       function setText( $text ) {
+               $this->mText = $text;
+       }
+
+       function getText() {
+               return $this->mText;
+       }
+
+       function getDeps() {
+               return $this->mDeps;
+       }
+
+       /** If the value is a template, execute it */
+       function execute( &$processor ) {
+               if ( $this->mIsTemplate ) {
+                       $myProcessor = new CBTProcessor( $this->mText,  $processor->mFunctionObj, $processor->mIgnorableDeps );
+                       $myProcessor->mCompiling = $processor->mCompiling;
+                       $val = $myProcessor->doText( 0, strlen( $this->mText ) );
+                       $this->mText = $val->mText;
+                       $this->addDeps( $val );
+                       if ( !$processor->mCompiling ) {
+                               $this->mIsTemplate = false;
+                       }
+               }
+       }
+
+       /** If the value is plain text, escape it for inclusion in a template */
+       function templateEscape() {
+               if ( !$this->mIsTemplate ) {
+                       $this->mText = templateEscape( $this->mText );
+               }
+       }
+
+       /** Return true if the value has no dependencies */
+       function isStatic() {
+               return count( $this->mDeps ) == 0;
+       }
+}
+
+/**
+ * Template processor, for compilation and execution
+ */
+class CBTProcessor {
+       var $mText,                     # The text being processed. This is immutable.
+               $mFunctionObj,              # The object containing callback functions
+               $mCompiling = false,        # True if compiling to a template, false if executing to text
+               $mIgnorableDeps = array(),  # Dependency names which should be treated as static
+               $mFunctionCache = array(),  # A cache of function results keyed by argument hash
+
+               /** Built-in functions */
+               $mBuiltins = array(
+               'if'       => 'bi_if',
+               'true'     => 'bi_true',
+               '['        => 'bi_lbrace',
+               'lbrace'   => 'bi_lbrace',
+               ']'        => 'bi_rbrace',
+               'rbrace'   => 'bi_rbrace',
+               'escape'   => 'bi_escape',
+               '~'        => 'bi_escape',
+       );
+
+       /**
+        * Create a template processor for a given text, callback object and static dependency list
+        */
+       function CBTProcessor( $text, $functionObj, $ignorableDeps = array() ) {
+               $this->mText = $text;
+               $this->mFunctionObj = $functionObj;
+               $this->mIgnorableDeps = $ignorableDeps;
+       }
+
+       /**
+        * Execute the template.
+        * If $compile is true, produces an optimised template where functions with static 
+        * dependencies have been replaced by their return values.
+        */
+       function execute( $compile = false ) {
+               $fname = 'CBTProcessor::execute';
+               wfProfileIn( $fname );
+               $this->mCompiling = $compile;
+               $this->mLastError = false;
+               $val = $this->doText( 0, strlen( $this->mText ) );
+               $text = $val->getText();
+               if ( $this->mLastError !== false ) {
+                       $pos = $this->mErrorPos;
+
+                       // Find the line number at which the error occurred
+                       $startLine = 0;
+                       $endLine = 0;
+                       $line = 0;
+                       do {
+                               if ( $endLine ) {
+                                       $startLine = $endLine + 1;
+                               }
+                               $endLine = strpos( $this->mText, "\n", $startLine );
+                               ++$line;
+                       } while ( $endLine !== false && $endLine < $pos );
+
+                       $text = "Template error at line $line: $this->mLastError\n<pre>\n";
+
+                       $context = rtrim( str_replace( "\t", " ", substr( $this->mText, $startLine, $endLine - $startLine ) ) );
+                       $text .= htmlspecialchars( $context ) . "\n" . str_repeat( ' ', $pos - $startLine ) . "^\n</pre>\n";
+               } 
+               wfProfileOut( $fname );
+               return $text;
+       }
+
+       /** Shortcut for execute(true) */
+       function compile() {
+               $fname = 'CBTProcessor::compile';
+               wfProfileIn( $fname );
+               $s = $this->execute( true );
+               wfProfileOut( $fname );
+               return $s;
+       }
+
+       /** Shortcut for doOpenText( $start, $end, false */
+       function doText( $start, $end ) {
+               return $this->doOpenText( $start, $end, false );
+       }
+
+       /** 
+        * Escape text for a template if we are producing a template. Do nothing
+        * if we are producing plain text.
+        */
+        function templateEscape( $text ) {
+               if ( $this->mCompiling ) {
+                       return templateEscape( $text );
+               } else {
+                       return $text;
+               }
+       }
+
+       /**
+        * Recursive workhorse for text mode.
+        * 
+        * Processes text mode starting from offset $p, until either $end is 
+        * reached or a closing brace is found. If $needClosing is false, a 
+        * closing brace will flag an error, if $needClosing is true, the lack
+        * of a closing brace will flag an error. 
+        *
+        * The parameter $p is advanced to the position after the closing brace, 
+        * or after the end. A TplValue is returned.
+        *
+        * @private
+        */
+       function doOpenText( &$p, $end, $needClosing = true ) {
+               $in =& $this->mText;
+               $start = $p;
+               $ret = new TplValue( '', array(), $this->mCompiling );
+               
+               $foundClosing = false;
+               while ( $p < $end ) {
+                       $matchLength = strcspn( $in, TP_BRACE, $p, $end - $p );
+                       $pToken = $p + $matchLength;
+
+                       if ( $pToken >= $end ) {
+                               // No more braces, output remainder
+                               $ret->cat( substr( $in, $p ) );
+                               $p = $end;
+                               break;
+                       }
+
+                       // Output the text before the brace
+                       $ret->cat( substr( $in, $p, $matchLength ) );
+
+                       // Advance the pointer 
+                       $p = $pToken + 1;
+                       
+                       // Check for closing brace
+                       if ( $in[$pToken] == '}' ) {
+                               $foundClosing = true;
+                               break;
+                       }
+                       
+                       // Handle the "{fn}" special case
+                       if ( $pToken > 0 && $in[$pToken-1] == '"' ) {
+                               $val = $this->doOpenFunction( $p, $end );
+                               if ( $p < $end && $in[$p] == '"' ) {
+                                       $val->setText( htmlspecialchars( $val->getText() ) );
+                               }
+                               $ret->cat( $val );
+                       } else {
+                               // Process the function mode component
+                               $ret->cat( $this->doOpenFunction( $p, $end ) );
+                       }
+               }
+               if ( $foundClosing && !$needClosing ) {
+                       $this->error( 'Errant closing brace', $p );
+               } elseif ( !$foundClosing && $needClosing ) {
+                       $this->error( 'Unclosed text section', $start );
+               }
+               return $ret;
+       }
+
+       /**
+        * Recursive workhorse for function mode.
+        *
+        * Processes function mode starting from offset $p, until either $end is 
+        * reached or a closing brace is found. If $needClosing is false, a 
+        * closing brace will flag an error, if $needClosing is true, the lack
+        * of a closing brace will flag an error. 
+        *
+        * The parameter $p is advanced to the position after the closing brace, 
+        * or after the end. A TplValue is returned.
+        *
+        * @private
+        */
+       function doOpenFunction( &$p, $end, $needClosing = true ) {
+               $in =& $this->mText;
+               $start = $p;
+               $tokens = array();
+               $unexecutedTokens = array();
+
+               $foundClosing = false;
+               while ( $p < $end ) {
+                       $char = $in[$p];
+                       if ( $char == '{' ) {
+                               // Switch to text mode
+                               ++$p;
+                               $tokenStart = $p;
+                               $token = $this->doOpenText( $p, $end );
+                               $tokens[] = $token;
+                               $unexecutedTokens[] = '{' . substr( $in, $tokenStart, $p - $tokenStart - 1 ) . '}';
+                       } elseif ( $char == '}' ) {
+                               // Block end
+                               ++$p;
+                               $foundClosing = true;
+                               break;
+                       } elseif ( false !== strpos( TP_WHITE, $char ) ) {
+                               // Whitespace
+                               // Consume the rest of the whitespace
+                               $p += strspn( $in, TP_WHITE, $p, $end - $p );
+                       } else {
+                               // Token, find the end of it
+                               $tokenLength = strcspn( $in, TP_DELIM, $p, $end - $p );
+                               $token = new TplValue( substr( $in, $p, $tokenLength ) );
+                               // Execute the token as a function if it's not the function name
+                               if ( count( $tokens ) ) {
+                                       $tokens[] = $this->doFunction( array( $token ), $p );
+                               } else {
+                                       $tokens[] = $token;
+                               }
+                               $unexecutedTokens[] = $token->getText();
+
+                               $p += $tokenLength;
+                       }
+               }
+               if ( !$foundClosing && $needClosing ) {
+                       $this->error( 'Unclosed function', $start );
+                       return '';
+               }
+
+               $val = $this->doFunction( $tokens, $start );
+               if ( $this->mCompiling && !$val->isStatic() ) {
+                       $compiled = '';
+                       $first = true;
+                       foreach( $tokens as $i => $token ) {
+                               if ( $first ) {
+                                       $first = false;
+                               } else {
+                                       $compiled .= ' ';
+                               }
+                               if ( $token->isStatic() ) {
+                                       if ( $i !== 0 ) {
+                                               $compiled .= '{' . $token->getText() . '}';
+                                       } else {
+                                               $compiled .= $token->getText();
+                                       }
+                               } else {
+                                       $compiled .= $unexecutedTokens[$i];
+                               }
+                       }
+
+                       // The dynamic parts of the string are still represented as functions, and 
+                       // function invocations have no dependencies. Thus the compiled result has 
+                       // no dependencies.
+                       $val = new TplValue( "{{$compiled}}", array(), true );
+               }
+               return $val;
+       }
+
+       /**
+        * Execute a function, caching and returning the result value.
+        * $tokens is an array of TplValue objects. $tokens[0] is the function 
+        * name, the others are arguments. $p is the string position, and is used
+        * for error messages only.
+        */
+       function doFunction( $tokens, $p ) {
+               if ( count( $tokens ) == 0 ) {
+                       return new TplValue;
+               }
+               $fname = 'CBTProcessor::doFunction';
+               wfProfileIn( $fname );
+               
+               $ret = new TplValue;
+               
+               // All functions implicitly depend on their arguments, and the function name
+               // While this is not strictly necessary for all functions, it's true almost 
+               // all the time and so convenient to do automatically. 
+               $ret->addDeps( $tokens );
+
+               $this->mCurrentPos = $p;
+               $func = array_shift( $tokens );
+               $func = $func->getText();
+
+               // Extract the text component from all the tokens
+               // And convert any templates to plain text
+               $textArgs = array();
+               foreach ( $tokens as $token ) {
+                       $token->execute( $this );
+                       $textArgs[] = $token->getText();
+               }
+
+               // Try the local cache
+               $cacheKey = $func . "\n" . implode( "\n", $textArgs );
+               if ( isset( $this->mFunctionCache[$cacheKey] ) ) {
+                       $val = $this->mFunctionCache[$cacheKey];
+               } elseif ( isset( $this->mBuiltins[$func] ) ) {
+                       $func = $this->mBuiltins[$func];
+                       $val = call_user_func_array( array( &$this, $func ), $tokens );
+                       $this->mFunctionCache[$cacheKey] = $val;
+               } elseif ( method_exists( $this->mFunctionObj, $func ) ) {
+                       $profName = get_class( $this->mFunctionObj ) . '::' . $func;
+                       wfProfileIn( "$fname-callback" );
+                       wfProfileIn( $profName );
+                       $val = call_user_func_array( array( &$this->mFunctionObj, $func ), $textArgs );
+                       wfProfileOut( $profName );
+                       wfProfileOut( "$fname-callback" );
+                       $this->mFunctionCache[$cacheKey] = $val;
+               } else {
+                       $this->error( "Call of undefined function \"$func\"", $p );
+                       $val = new TplValue;
+               }
+               if ( !is_object( $val ) ) {
+                       $val = new TplValue((string)$val);
+               }
+
+               if ( TP_DEBUG ) {
+                       $unexpanded = $val;
+               }
+
+               // If the output was a template, execute it
+               $val->execute( $this );
+               
+               if ( $this->mCompiling ) {
+                       // Escape any braces so that the output will be a valid template
+                       $val->templateEscape();
+               } 
+               $val->removeDeps( $this->mIgnorableDeps );
+               $ret->addDeps( $val );
+               $ret->setText( $val->getText() );
+
+               if ( TP_DEBUG ) {
+                       print "doFunction $func args = ";
+                       var_dump( $tokens );
+                       print "unexpanded return = ";
+                       var_dump( $unexpanded );
+                       print "expanded return = ";
+                       var_dump( $ret );
+               }
+               
+               wfProfileOut( $fname );
+               return $ret;
+       }
+
+       /**
+        * Set a flag indicating that an error has been found.
+        */
+       function error( $text, $pos = false ) {
+               $this->mLastError = $text;
+               if ( $pos === false ) {
+                       $this->mErrorPos = $this->mCurrentPos;
+               } else {
+                       $this->mErrorPos = $pos;
+               }
+       }
+
+       function getLastError() {
+               return $this->mLastError;
+       }
+
+       /** 'if' built-in function */
+       function bi_if( $condition, $trueBlock, $falseBlock = null ) {
+               if ( is_null( $condition ) ) {
+                       $this->error( "Missing condition in if" );
+                       return '';
+               }
+
+               if ( $condition->getText() != '' ) {
+                       return new TplValue( $trueBlock->getText(), 
+                               array_merge( $condition->getDeps(), $trueBlock->getDeps() ),
+                               $trueBlock->mIsTemplate );
+               } else {
+                       if ( !is_null( $falseBlock ) ) {
+                               return new TplValue( $falseBlock->getText(), 
+                                       array_merge( $condition->getDeps(), $falseBlock->getDeps() ),
+                                       $falseBlock->mIsTemplate );
+                       } else {
+                               return new TplValue( '', $condition->getDeps() );
+                       }
+               }
+       }
+
+       /** 'true' built-in function */
+       function bi_true() {
+               return "true";
+       }
+
+       /** left brace built-in */
+       function bi_lbrace() {
+               return '{';
+       }
+
+       /** right brace built-in */
+       function bi_rbrace() {
+               return '}';
+       }
+
+       /** 
+        * escape built-in.
+        * Escape text for inclusion in an HTML attribute 
+        */
+       function bi_escape( $val ) {
+               return new TplValue( htmlspecialchars( $val->getText() ), $val->getDeps() );
+       }
+}
+?>
diff --git a/skins/MonoBook.tpl b/skins/MonoBook.tpl
new file mode 100644 (file)
index 0000000..07b2822
--- /dev/null
@@ -0,0 +1,199 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{lang}" lang="{lang}" dir="{dir}">
+<head>
+       <meta http-equiv="Content-Type" content="{~ mimetype}; charset={~ charset}" />
+       {headlinks}
+       {headscripts}
+       <title>{pagetitle}</title>
+       <style type="text/css" media="screen,projection">/*<![CDATA[*/ @import "{~ stylepath}/{~ stylename}/main.css?5"; /*]]>*/</style>
+       <link rel="stylesheet" type="text/css" {if notprintable {media="print"}} href="{~ stylepath}/common/commonPrint.css" />
+       <!--[if lt IE 5.5000]><style type="text/css">@import "{~ stylepath}/{~ stylename}/IE50Fixes.css";</style><![endif]-->
+       <!--[if IE 5.5000]><style type="text/css">@import "{~ stylepath}/{~ stylename}/IE55Fixes.css";</style><![endif]-->
+       <!--[if IE 6]><style type="text/css">@import "{~ stylepath}/{~ stylename}/IE60Fixes.css";</style><![endif]-->
+       <!--[if IE 7]><style type="text/css">@import "{~ stylepath}/{~ stylename}/IE70Fixes.css?1";</style><![endif]-->
+       <!--[if lt IE 7]><script type="{jsmimetype}" src="{~ stylepath}/common/IEFixes.js"></script>
+       <meta http-equiv="imagetoolbar" content="no" /><![endif]-->
+       {if jsvarurl {<script type="{jsmimetype}" src="{jsvarurl}"><!-- site js --></script>}}
+       <script type="{jsmimetype}" src="{~ stylepath}/common/wikibits.js"><!-- wikibits js --></script>
+       {if pagecss {<style type="text/css">{pagecss}</style>}}
+       {usercss}
+       {sitecss}
+       {gencss}
+       {if userjs {<script type="{jsmimetype}" src="{userjs}"></script>}}
+       {if userjsprev {<script type="{jsmimetype}">{userjsprev}</script>}}
+       {trackbackhtml}
+</head>
+<body {if body_ondblclick {ondblclick="{body_ondblclick}"}} {if body_onload {onload="{body_onload}" }} class="{~ nsclass} {~ dir}">
+<div id="globalWrapper">
+       <div id="column-content">
+               <div id="content">
+                       <a name="top" id="top"></a>
+                       {if sitenotice {<div id="siteNotice">{sitenotice}</div> }}
+                       <h1 class="firstHeading">{title}</h1>
+                       <div id="bodyContent">
+                               <h3 id="siteSub">{msg {tagline}}</h3>
+                               <div id="contentSub">{subtitle}</div>
+                               {if undelete {<div id="contentSub2"><span class="subpages">{undelete}</span></div> }}
+                               {if newtalk {<div class="usermessage">{newtalk}</div> }}
+                               {if showjumplinks {
+                                       <div id="jump-to-nav">{msg {jumpto}} <a href="#column-one">{msg {jumptonavigation}}</a>, 
+                                       <a href="#searchInput">{msg {jumptosearch}}</a></div> 
+                               }}
+                               <!-- start content -->
+                               {bodytext}
+                               {if catlinks {<div id="catlinks">{catlinks}</div> }}
+                               <!-- end content -->
+                               <div class="visualClear"></div>
+                       </div>
+               </div>
+       </div>
+       <div id="column-one">
+               <div id="p-cactions" class="portlet">
+                       <h5>{msg {views}}</h5>
+                       <ul>
+                               {if is_special {
+                                       <li id="ca-article" class="selected"><a href="{request_url}">{msg {specialpage}}</a></li>
+                               } {
+                                       <li id="ca-{nskey}" {selecttab {subject} subject_newclass}><a href="{subject_url}">{msg nskey}</a></li>
+                                       <li id="ca-talk" {selecttab {talk} talk_newclass}><a href="{talk_url}">{msg {talk}}</a></li>
+                                       {if can_edit {
+                                               {if is_talk {
+                                                       <li id="ca-edit" {selecttab {edit} {istalk}}><a href="{edit_url}">{msg {edit}}</a></li>
+                                                       <li id="ca-addsection" {selecttab {addsection}}><a href="{localurl {action=edit&section=new}}">{msg {addsection}}</a></li>
+                                               } {
+                                                       <li id="ca-edit" {selecttab {edit}}><a href="{edit_url}">{msg {edit}}</a></li>
+                                               }}
+                                       } {
+                                               <li id="ca-viewsource" {selecttab {edit}}><a href="{edit_url}">{msg {viewsource}}</a></li>
+                                       }}
+
+                                       {if article_exists {
+                                               <li id="ca-history" {selecttab {history}}><a href="{localurl {action=history}}">{msg {history_short}}</a></li>
+                                               {if {{ is_allowed {protect} }} {
+                                                       {if is_ns_mediawiki {
+                                                               {if is_protected {
+                                                                       <li id="ca-protect" {selecttab {protect}}><a href="{localurl {action=protect}}">{msg {protect}}</a></li>
+                                                               } {
+                                                                       <li id="ca-protect" {selecttab {protect}}><a href="{localurl {action=unprotect}}">{msg {unprotect}}</a></li>
+                                                               }}
+                                                       }}
+                                               }}
+                                               
+                                               {if {{ is_allowed {delete} }} {
+                                                               <li id="ca-delete" {selecttab {delete}}><a href="{localurl {action=delete}}">{msg {delete}}</a></li>
+                                               }}
+                                               {if {{ is_allowed {move} }} {
+                                                       {if can_move {
+                                                                       <li id="ca-move" {selecttab {move}}><a href="{move_url}">{msg {move}}</a></li>
+                                                       }}
+                                               }}
+                                               {if is_loggedin {
+                                                       {if is_watching {
+                                                               <li id="ca-unwatch" {selecttab {watch}}><a href="{localurl {action=unwatch}}">{msg {unwatch}}</a></li>
+                                                       } {
+                                                               <li id="ca-watch" {selecttab {watch}}><a href="{localurl {action=watch}}">{msg {watch}}</a></li>
+                                                       }}
+                                               }}
+                                       }}
+                               }}
+                               {extratabs {<li id="ca-$id" $class><a href="$href">$text</a></li>}}
+                       </ul>
+               </div>
+               <div class="portlet" id="p-personal">
+                       <h5>{msg {personaltools}}</h5>
+                       <div class="pBody">
+                               <ul>                                            
+                                       {personal_urls { <li id="pt-$key" $classactive ><a href="$href" $class>$text</a></li> }}
+                               </ul>
+                       </div>
+               </div>
+               <div class="portlet" id="p-logo">
+                       <a style="background-image: url({~ logopath});" href="{mainpage}" title="{msg {mainpage}}"></a>
+               </div>
+               <script type="{jsmimetype}"> if (window.isMSIE55) fixalpha(); </script>
+               {sidebar {
+                       <div class='portlet' id="p-$bar">
+                               <h5>$barname</h5>
+                               <div class='pBody'>
+                               <ul>
+               } {
+                               </ul>
+                               </div>
+                       </div>
+               } {<li id="$id" $classactive><a href="$href">$text</a></li>
+                       }
+               }
+
+               <div id="p-search" class="portlet">
+                       <h5><label for="searchInput">{msg {search}}</label></h5>
+                       <div id="searchBody" class="pBody">
+                               <form action="{searchaction}" id="searchform"><div>
+                                       <input id="searchInput" name="search" type="text" {
+                                               }{if {{fallbackmsg {accesskey-search} {} }} {accesskey="{fallbackmsg {accesskey-search} {} }"}}{
+                                               }{if search { value="{search}"}} />
+                                       <input type='submit' name="go" class="searchButton" id="searchGoButton" value="{msg {go}}" />&nbsp;
+                                       <input type='submit' name="fulltext" class="searchButton" value="{msg {search}}" />
+                               </div></form>
+                       </div>
+               </div>
+               <div class="portlet" id="p-tb">
+                       <h5>{msg {toolbox}}</h5>
+                       <div class="pBody">
+                               <ul>
+                                       {if notspecialpage    {<li id="t-whatlinkshere"><a href="{nav_whatlinkshere}">{msg {whatlinkshere}}</a></li> }}
+                                       {if article_exists {<li id="t-recentchangeslinked"><a href="{nav_recentchangeslinked}">{msg {recentchangeslinked}}</a></li> }}
+                                       {if nav_trackbacklink {<li id="t-trackbacklink"><a href="{nav_trackbacklink}">{msg {trackbacklink}}</a></li>}}
+                                       {if feeds
+                                               {<li id="feedlinks">{feeds {<span id="feed-$key"><a href="$href">$text</a>&nbsp;</span>}}
+                                       </li>}}
+                                       {if is_userpage {
+                                               <li id="t-contributions"><a href="{nav_contributions}">{msg {contributions}}</a></li>
+                                               {if {{is_allowed {block}}} {<li id="t-blockip"><a href="{nav_blockip}">{msg {blockip}}</a></li>}}
+                                               {if is_loggedin     {<li id="t-emailuser"><a href="{nav_emailuser}">{msg {emailuser}}</a></li>}}
+                                       }}
+                                       {if nav_upload        {<li id="t-upload"><a href="{nav_upload}">{msg {upload}}</a></li>}}
+                                       {if nav_specialpages  {<li id="t-specialpages"><a href="{nav_specialpages}">{msg {specialpages}}</a></li>}}
+                                       {if nav_print         {<li id="t-print"><a href="{nav_print}">{msg {printableversion}}</a></li>}}
+                                       {if nav_permalink     {<li id="t-permalink"><a href="{nav_permalink}">{msg {permalink}}</a></li>}}
+                                       {if is_permalink      {<li id="t-ispermalink">{msg {permalink}}</li>}}
+
+                                       {toolboxend}
+                               </ul>
+                       </div>
+               </div>
+               {language_urls {
+                       <div id="p-lang" class="portlet">
+                               <h5>{msg {otherlanguages}}</h5>
+                               <div class="pBody">
+                                       <ul>
+                                               $body
+                                       </ul>
+                               </div>
+                       </div>
+               } {
+                       <li class="$class"><a href="$href">$text</a></li>
+               }}      
+       </div><!-- end of the left (by default at least) column -->
+       <div class="visualClear"></div>
+       <div id="footer">
+               {if poweredbyico { <div id="f-poweredbyico">{poweredbyico}</div> }}
+               {if copyrightico { <div id="f-copyrightico">{copyrightico}</div> }}
+
+               <ul id="f-list">
+                       {if lastmod                {  <li id="lastmod">{lastmod}</li> }}
+                       {if viewcount              {  <li id="viewcount">{viewcount}</li> }}
+                       {if numberofwatchingusers  {  <li id="numberofwatchingusers">{numberofwatchingusers}</li> }}
+                       {if credits                {  <li id="credits">{credits}</li> }}
+                       {if is_currentview         {  <li id="copyright">{normalcopyright}</li> }}
+                       {if usehistorycopyright    {  <li id="copyright">{historycopyright}</li> }}
+                       {if privacy                {  <li id="privacy">{privacy}</li> }}
+                       {if about                  {  <li id="about">{about}</li> }}
+                       {if disclaimer             {  <li id="disclaimer">{disclaimer}</li> }}
+                       {if tagline                {  <li id="tagline">{tagline}</li> }}
+               </ul>
+       </div>
+       <script type="text/javascript"> if (window.runOnloadHook) runOnloadHook();</script>
+</div>
+{reporttime}
+{if {} { vim: set syn=html ts=2 : }}
+</body></html>
diff --git a/skins/disabled/MonoBookCBT.php b/skins/disabled/MonoBookCBT.php
new file mode 100644 (file)
index 0000000..a5d5b54
--- /dev/null
@@ -0,0 +1,1327 @@
+<?php
+
+if ( !defined( 'MEDIAWIKI' ) ) {
+       die( "This file is part of MediaWiki, it is not a valid entry point\n" );
+}
+
+require_once( dirname(__FILE__) . '/../includes/CBTProcessor.php' );
+require_once( dirname(__FILE__) . '/../includes/SkinTemplate.php' );
+
+
+/**
+ * MonoBook clone using the new dependency-tracking template processor.
+ * EXPERIMENTAL - use only for testing and profiling at this stage
+ *
+ * The main thing that's missing is cache invalidation, on change of:
+ *   * messages
+ *   * user preferences
+ *   * source template
+ *   * source code and configuration files
+ *
+ * The other thing is that lots of dependencies that are declared in the callbacks
+ * are not intelligently handled. There's some room for improvement there.
+ *
+ * The class is derived from SkinTemplate, but that's only temporary. Eventually 
+ * it'll be derived from Skin, and I've avoided using SkinTemplate functions as 
+ * much as possible. In fact, the only SkinTemplate dependencies I know of at the 
+ * moment are the functions to generate the gen=css and gen=js files. 
+ * 
+ * It assumes that $wgMemc is valid, if not, performance will be glacial as it will 
+ * compile the skin on every invocation. 
+ */
+class SkinMonoBookCBT extends SkinTemplate {
+       var $mOut, $mTitle;
+       var $mStyleName = 'monobook';
+       var $mCompiling = false;
+
+       /******************************************************
+        * General functions                                  *
+        ******************************************************/
+       
+       /** Execute the template and write out the result */
+       function outputPage( &$out ) {
+               echo $this->execute( $out );
+       }
+
+       function execute( &$out ) {
+               global $wgTitle, $wgStyleDirectory, $wgParserCacheType;
+               $fname = 'SkinMonoBookCBT::execute';
+               wfProfileIn( $fname );
+               wfProfileIn( "$fname-setup" );
+               Skin::initPage( $out );
+               
+               $this->mOut =&  $out;
+               $this->mTitle =& $wgTitle;
+
+               $sourceFile = "$wgStyleDirectory/MonoBook.tpl";
+
+               wfProfileOut( "$fname-setup" );
+       
+               if ( $wgParserCacheType == CACHE_NONE ) {
+                       $template = file_get_contents( $sourceFile );
+                       $text = $this->executeTemplate( $template );
+               } else {
+                       $compiled = $this->getCompiledTemplate( $sourceFile );
+                       $text = $this->executeTemplate( $compiled );
+               }
+               wfProfileOut( $fname );
+               return $text;
+       }
+
+       function getCompiledTemplate( $sourceFile ) {
+               global $wgDBname, $wgMemc, $wgRequest, $wgUser, $parserMemc;
+               $fname = 'SkinMonoBookCBT::getCompiledTemplate';
+
+               // Sandbox template execution
+               if ( $this->mCompiling ) {
+                       return;
+               }
+               
+               wfProfileIn( $fname );
+
+               // Is the request an ordinary page view?
+               if ( $wgRequest->wasPosted() || 
+                               count( array_diff( array_keys( $_GET ), array( 'title', 'useskin', 'recompile' ) ) ) != 0 ) 
+               {
+                       $type = 'nonview';
+               } else {
+                       $type = 'view';
+               }
+
+               // Per-user compiled template
+               // Put all logged-out users on the same cache key
+               $cacheKey = "$wgDBname:monobookcbt:$type:" . $wgUser->getId();
+
+               $recompile = $wgRequest->getVal( 'recompile' );
+               if ( !$recompile ) { 
+                       $compiled = $parserMemc->get( $cacheKey );
+               }
+               if ( $recompile || !$compiled ) {
+                       $template = file_get_contents( $sourceFile );
+
+                       $ignore = array( 'lang', 'loggedin', 'user' );
+                       if ( $wgUser->isLoggedIn() ) {
+                               $ignore[] = '!loggedin dynamic';
+                       } else {
+                               $ignore[] = 'loggedin dynamic';
+                       }
+                       if ( $type == 'view' ) {
+                               $ignore[] = 'nonview dynamic';
+                       }
+                       $tp = new CBTProcessor( $template, $this, $ignore );
+                       $this->mCompiling = true;
+                       $compiled = $tp->compile();
+                       $this->mCompiling = false;
+                       if ( $tp->getLastError() ) {
+                               // If there was a compile error, don't save the template
+                               // Instead just print the error and exit
+                               echo $compiled;
+                               wfErrorExit();
+                       }
+
+                       // Reduce whitespace
+                       // This is done here instead of in CBTProcessor because we can be 
+                       // more sure it is safe here.
+                       $compiled = preg_replace( '/^[ \t]+/m', '', $compiled );
+                       $compiled = preg_replace( '/[\r\n]+/', "\n", $compiled );
+                       $parserMemc->set( $cacheKey, $compiled, 3600 );
+               }
+               wfProfileOut( $fname );
+               return $compiled;
+       }
+
+       function executeTemplate( $template ) {
+               $fname = 'SkinMonoBookCBT::executeTemplate';
+               wfProfileIn( $fname );
+               $tp = new CBTProcessor( $template, $this );
+               $this->mCompiling = true;
+               $text = $tp->execute();
+               $this->mCompiling = false;
+               wfProfileOut( $fname );
+               return $text;
+       }
+       
+       /******************************************************
+        * Callbacks                                          *
+        ******************************************************/
+
+       function lang() { return $GLOBALS['wgContLanguageCode']; }
+
+       function dir() {
+               global $wgContLang;
+               return $wgContLang->isRTL() ? 'rtl' : 'ltr';
+       }
+       
+       function mimetype() { return $GLOBALS['wgMimeType']; }
+       function charset() { return $GLOBALS['wgOutputEncoding']; }
+       function headlinks() { 
+               return new TplValue( $this->mOut->getHeadLinks(), 'dynamic' );
+       }
+       function headscripts() { 
+               return new TplValue( $this->mOut->getScript(), 'dynamic' );
+       }
+       
+       function pagetitle() { 
+               return new TplValue( $this->mOut->getHTMLTitle(), array( 'title', 'lang' ) ); 
+       }
+       
+       function stylepath() { return $GLOBALS['wgStylePath']; }
+       function stylename() { return $this->mStyleName; }
+       
+       function notprintable() {
+               global $wgRequest;
+               return new TplValue( !$wgRequest->getBool( 'printable' ), 'nonview dynamic' );
+       }
+       
+       function jsmimetype() { return $GLOBALS['wgJsMimeType']; }
+       
+       function jsvarurl() {
+               global $wgUseSiteJs, $wgUser;
+               if ( !$wgUseSiteJs ) return '';
+               
+               if ( $wgUser->isLoggedIn() ) {
+                       $url = $this->makeUrl('-','action=raw&smaxage=0&gen=js');
+               } else {
+                       $url = $this->makeUrl('-','action=raw&gen=js');
+               }
+               return new TplValue( $url, 'loggedin' );
+       }
+       
+       function pagecss() {
+               global $wgHooks;
+               
+               $out = false;
+               wfRunHooks( 'SkinTemplateSetupPageCss', array( &$out ) );
+
+               // Unknown dependencies
+               return new TplValue( $out, 'dynamic' );
+       }
+       
+       function usercss() {
+               if ( $this->isCssPreview() ) {
+                       global $wgRequest;
+                       $usercss = $this->makeStylesheetCdata( $wgRequest->getText('wpTextbox1') );
+               } else {
+                       $usercss = $this->makeStylesheetLink( $this->makeUrl($this->getUserPageText() . 
+                               '/'.$this->mStyleName.'.css', 'action=raw&ctype=text/css' ) );
+               }
+
+               // Dynamic when not an ordinary page view, also depends on the username
+               return new TplValue( $usercss, array( 'nonview dynamic', 'user' ) );
+       }
+       
+       function sitecss() {
+               global $wgUseSiteCss;
+               if ( !$wgUseSiteCss ) {
+                       return '';
+               }
+
+               global $wgSquidMaxage, $wgContLang, $wgStylePath;
+                       
+               $query = "action=raw&ctype=text/css&smaxage=$wgSquidMaxage";
+               
+               $sitecss = '';
+               if ( $wgContLang->isRTL() ) {
+                       $sitecss .= $this->makeStylesheetLink( $wgStylePath . '/' . $this->mStyleName . '/rtl.css' ) . "\n";
+               }
+
+               $sitecss .= $this->makeStylesheetLink( $this->makeNSUrl('Common.css', $query, NS_MEDIAWIKI) ) . "\n";
+               $sitecss .= $this->makeStylesheetLink( $this->makeNSUrl(
+                       ucfirst($this->mStyleName) . '.css', $query, NS_MEDIAWIKI) ) . "\n";
+
+               // No deps
+               return $sitecss;
+       }
+
+       function gencss() {
+               global $wgUseSiteCss;
+               if ( !$wgUseSiteCss ) return '';
+               
+               global $wgSquidMaxage, $wgUser, $wgAllowUserCss;
+               if ( $this->isCssPreview() ) {
+                       $siteargs = '&smaxage=0&maxage=0';
+               } else {
+                       $siteargs = '&maxage=' . $wgSquidMaxage;
+               }
+               if ( $wgAllowUserCss && $wgUser->isLoggedIn() ) {
+                       $siteargs .= '&ts={user_touched}';
+                       $isTemplate = true;
+               } else {
+                       $isTemplate = false;
+               }
+               
+               $link = $this->makeStylesheetLink( $this->makeUrl('-','action=raw&gen=css' . $siteargs) ) . "\n";
+
+               if ( $wgAllowUserCss ) {
+                       $deps = 'loggedin';
+               } else { 
+                       $deps = array();
+               }
+               return new TplValue( $link, $deps, $isTemplate );
+       }
+       
+       function user_touched() {
+               global $wgUser;
+               return new TplValue( $wgUser->mTouched, 'dynamic' );
+       }
+               
+       function userjs() {
+               global $wgAllowUserJs, $wgJsMimeType;
+               if ( !$wgAllowUserJs ) return '';
+               
+               if ( $this->isJsPreview() ) {
+                       $url = '';
+               } else {
+                       $url = $this->makeUrl($this->getUserPageText().'/'.$this->mStyleName.'.js', 'action=raw&ctype='.$wgJsMimeType.'&dontcountme=s');
+               }
+               return new TplValue( $url, array( 'nonview dynamic', 'user' ) );
+       }
+       
+       function userjsprev() {
+               global $wgAllowUserJs, $wgRequest;
+               if ( !$wgAllowUserJs ) return '';
+               if ( $this->isJsPreview() ) {
+                       $js = '/*<![CDATA[*/ ' . $wgRequest->getText('wpTextbox1') . ' /*]]>*/';
+               } else {
+                       $js = '';
+               }
+               return new TplValue( $js, array( 'nonview dynamic' ) );
+       }
+       
+       function trackbackhtml() {
+               global $wgUseTrackbacks;
+               if ( !$wgUseTrackbacks ) return '';
+
+               if ( $this->mOut->isArticleRelated() ) {
+                       $tb = $this->mTitle->trackbackRDF();
+               } else {
+                       $tb = '';
+               }
+               return new TplValue( $tb, 'dynamic' );
+       }
+       
+       function body_ondblclick() {
+               global $wgUser;
+               if( $this->isEditable() && $wgUser->getOption("editondblclick") ) {
+                       $js = 'document.location = "' . $this->getEditUrl() .'";';
+               } else {
+                       $js = '';
+               }
+
+               if ( User::getDefaultOption('editondblclick') ) {
+                       return new TplValue( $js, 'user', 'title' );
+               } else {
+                       // Optimise away for logged-out users
+                       return new TplValue( $js, 'loggedin dynamic' );
+               }
+       }
+       
+       function body_onload() {
+               global $wgUser;
+               if ( $this->isEditable() && $wgUser->getOption( 'editsectiononrightclick' ) ) {
+                       $js = 'setupRightClickEdit()';
+               } else {
+                       $js = '';
+               }
+               return new TplValue( $js, 'loggedin dynamic' );
+       }
+       
+       function nsclass() {
+               return new TplValue( 'ns-' . $this->mTitle->getNamespace(), 'title' );
+       }
+       
+       function sitenotice() {
+               // Perhaps this could be given special dependencies using our knowledge of what 
+               // wfGetSiteNotice() depends on.
+               return new TplValue( wfGetSiteNotice(), 'dynamic' );
+       }
+       
+       function title() {
+               return new TplValue( $this->mOut->getPageTitle(), array( 'title', 'lang' ) );
+       }
+
+       function title_urlform() {
+               return new TplValue( $this->getThisTitleUrlForm(), 'title' );
+       }
+
+       function title_userurl() {
+               return new TplValue( urlencode( $this->mTitle->getDBkey() ), 'title' );
+       }
+
+       function subtitle() {
+               $subpagestr = $this->subPageSubtitle();
+               if ( !empty( $subpagestr ) ) {
+                       $s = '<span class="subpages">'.$subpagestr.'</span>'.$this->mOut->getSubtitle();
+               } else {
+                       $s = $this->mOut->getSubtitle();
+               }
+               return new TplValue( $s, array( 'title', 'nonview dynamic' ) );
+       }
+       
+       function undelete() {
+               return new TplValue( $this->getUndeleteLink(), array( 'title', 'lang' ) );
+       }
+       
+       function newtalk() {
+               global $wgUser, $wgDBname;
+               $newtalks = $wgUser->getNewMessageLinks();
+
+               if (count($newtalks) == 1 && $newtalks[0]["wiki"] === $wgDBname) {
+                       $usertitle = $this->getUserPageTitle();
+                       $usertalktitle = $usertitle->getTalkPage();
+                       if( !$usertalktitle->equals( $this->mTitle ) ) {
+                               $ntl = wfMsg( 'youhavenewmessages',
+                                       $this->makeKnownLinkObj(
+                                               $usertalktitle,
+                                               wfMsgHtml( 'newmessageslink' ),
+                                               'redirect=no'
+                                       ),
+                                       $this->makeKnownLinkObj(
+                                               $usertalktitle,
+                                               wfMsgHtml( 'newmessagesdifflink' ),
+                                               'diff=cur'
+                                       )
+                               );
+                               # Disable Cache
+                               $this->mOut->setSquidMaxage(0);
+                       }
+               } else if (count($newtalks)) {
+                       $sep = str_replace("_", " ", wfMsgHtml("newtalkseperator"));
+                       $msgs = array();
+                       foreach ($newtalks as $newtalk) {
+                               $msgs[] = wfElement("a", 
+                                       array('href' => $newtalk["link"]), $newtalk["wiki"]);
+                       }
+                       $parts = implode($sep, $msgs);
+                       $ntl = wfMsgHtml('youhavenewmessagesmulti', $parts);
+                       $this->mOut->setSquidMaxage(0);
+               } else {
+                       $ntl = '';
+               }
+               return new TplValue( $ntl, 'dynamic' );
+       }
+       
+       function showjumplinks() {
+               global $wgUser;
+               return new TplValue( $wgUser->getOption( 'showjumplinks' ) ? 'true' : '', 'user' );
+       }
+       
+       function bodytext() {
+               return new TplValue( $this->mOut->getHTML(), 'dynamic' );
+       }
+       
+       function catlinks() {
+               return new TplValue( $this->getCategories(), 'dynamic' );
+       }
+       
+       function extratabs( $itemTemplate ) {
+               global $wgContLang, $wgDisableLangConversion;
+               
+               $etpl = templateEscape( $itemTemplate );
+
+               /* show links to different language variants */
+               $variants = $wgContLang->getVariants();
+               $s = '';
+               if ( !$wgDisableLangConversion && count( $wgContLang->getVariants() ) > 1 ) {
+                       $vcount=0;
+                       foreach ( $variants as $code ) {
+                               $name = $wgContLang->getVariantname( $code );
+                               if ( $name == 'disable' ) {
+                                       continue;
+                               }
+                               $name = templateEscape( $name );
+                               $s .= "{ca_variant {{$code}} {{$name}} {{$vcount}} {{$etpl}}}\n";
+                               $vcount ++;
+                       }
+               }
+               return new TplValue( $s, array(), true );
+       }
+
+       function is_special() { return new TplValue( $this->mTitle->getNamespace() == NS_SPECIAL, 'title' ); }
+       function can_edit() { return new TplValue( (string)($this->mTitle->userCanEdit()), 'dynamic' ); }
+       function can_move() { return new TplValue( (string)($this->mTitle->userCanMove()), 'dynamic' ); }
+       function is_talk() { return new TplValue( (string)($this->mTitle->isTalkPage()), 'title' ); }
+       function is_protected() { return new TplValue( (string)$this->mTitle->isProtected(), 'dynamic' ); }
+       function nskey() { return new TplValue( $this->mTitle->getNamespaceKey(), 'title' ); }
+
+       function request_url() {
+               global $wgRequest;
+               return new TplValue( $wgRequest->getRequestURL(), 'dynamic' );
+       }
+
+       function subject_url() { 
+               $title = $this->getSubjectPage();
+               if ( $title->exists() ) {
+                       $url = $title->getLocalUrl();
+               } else {
+                       $url = $title->getLocalUrl( 'action=edit' );
+               }
+               return new TplValue( $url, 'title' ); 
+       }
+
+       function talk_url() {
+               $title = $this->getTalkPage();
+               if ( $title->exists() ) {
+                       $url = $title->getLocalUrl();
+               } else {
+                       $url = $title->getLocalUrl( 'action=edit' );
+               }
+               return new TplValue( $url, 'title' );
+       }
+
+       function edit_url() {
+               return new TplValue( $this->getEditUrl(), array( 'title', 'nonview dynamic' ) );
+       }
+
+       function move_url() {
+               return new TplValue( $this->makeSpecialParamUrl( 'Movepage' ), array(), true );
+       }
+
+       function localurl( $query ) {
+               return new TplValue( $this->mTitle->getLocalURL( $query ), 'title' );
+       }
+
+       function selecttab( $tab, $extraclass = '' ) {
+               if ( !isset( $this->mSelectedTab ) ) {
+                       $prevent_active_tabs = false ;
+                       wfRunHooks( 'SkinTemplatePreventOtherActiveTabs', array( &$this , &$preventActiveTabs ) );
+
+                       $actionTabs = array(
+                               'edit' => 'edit',
+                               'submit' => 'edit',
+                               'history' => 'history',
+                               'protect' => 'protect',
+                               'unprotect' => 'protect',
+                               'delete' => 'delete',
+                               'watch' => 'watch',
+                               'unwatch' => 'watch',
+                       );
+                       if ( $preventActiveTabs ) {
+                               $this->mSelectedTab = false;
+                       } else {
+                               $action = $this->getAction();
+                               $section = $this->getSection();
+                               
+                               if ( isset( $actionTabs[$action] ) ) {
+                                       $this->mSelectedTab = $actionTabs[$action];
+
+                                       if ( $this->mSelectedTab == 'edit' && $section == 'new' ) {
+                                               $this->mSelectedTab = 'addsection';
+                                       }
+                               } elseif ( $this->mTitle->isTalkPage() ) {
+                                       $this->mSelectedTab = 'talk';
+                               } else {
+                                       $this->mSelectedTab = 'subject';
+                               }
+                       }
+               }
+               if ( $extraclass ) {
+                       if ( $this->mSelectedTab == $tab ) {
+                               $s = 'class="selected ' . htmlspecialchars( $extraclass ) . '"';
+                       } else {
+                               $s = 'class="' . htmlspecialchars( $extraclass ) . '"';
+                       }                       
+               } else {
+                       if ( $this->mSelectedTab == $tab ) {
+                               $s = 'class="selected"';
+                       } else {
+                               $s = '';
+                       }
+               }
+               return new TplValue( $s, array( 'nonview dynamic', 'title' ) );
+       }
+
+       function subject_newclass() {
+               $title = $this->getSubjectPage();
+               $class = $title->exists() ? '' : 'new';
+               return new TplValue( $class, 'dynamic' );
+       }
+
+       function talk_newclass() {
+               $title = $this->getTalkPage();
+               $class = $title->exists() ? '' : 'new';
+               return new TplValue( $class, 'dynamic' );
+       }       
+
+       function ca_variant( $code, $name, $index, $template ) {
+               global $wgContLang;
+               $selected = ($code == $wgContLang->getPreferredVariant());
+               $action = $this->getAction();
+               $actstr = '';
+               if( $action )
+                       $actstr = 'action=' . $action . '&';
+               $s = strtr( $template, array( 
+                       '$id' => htmlspecialchars( 'varlang-' . $index ),
+                       '$class' => $selected ? 'class="selected"' : '',
+                       '$text' => $name,
+                       '$href' => htmlspecialchars( $this->mTitle->getLocalUrl( $actstr . 'variant=' . $code ) )
+               ));
+               return new TplValue( $s, 'dynamic' );
+       }
+
+       function is_watching() {
+               return new TplValue( (string)$this->mTitle->userIsWatching(), array( 'dynamic' ) );
+       }
+
+       
+       function personal_urls( $itemTemplate ) {
+               global $wgShowIPinHeader, $wgContLang;
+
+               # Split this function up into many small functions, to obtain the
+               # best specificity in the dependencies of each one. The template below 
+               # has no dependencies, so its generation, and any static subfunctions,
+               # can be optimised away.
+               $etpl = templateEscape( $itemTemplate );
+               $s = "
+                       {userpage {{$etpl}}}
+                       {mytalk {{$etpl}}}
+                       {preferences {{$etpl}}}
+                       {watchlist {{$etpl}}}
+                       {mycontris {{$etpl}}}
+                       {logout {{$etpl}}}
+               ";
+
+
+               if ( $wgShowIPinHeader ) {
+                       $s .= "
+                               {anonuserpage {{$etpl}}}
+                               {anontalk {{$etpl}}}
+                               {anonlogin {{$etpl}}}
+                       ";
+               } else {
+                       $s .= "{login {{$etpl}}\n";
+               }
+               // No dependencies
+               return new TplValue( $s, array(), true /*this is a template*/ );
+       }
+
+       function userpage( $itemTemplate ) {
+               global $wgUser;
+               if ( $this->isLoggedIn() ) {
+                       $userPage = $this->getUserPageTitle();
+                       $s = $this->makeTemplateLink( $itemTemplate, 'userpage', $userPage, $wgUser->getName() );
+               } else {
+                       $s = '';
+               }
+               return new TplValue( $s, 'user' );
+       }
+       
+       function mytalk( $itemTemplate ) {
+               global $wgUser;
+               if ( $this->isLoggedIn() ) {
+                       $userPage = $this->getUserPageTitle();
+                       $talkPage = $userPage->getTalkPage();
+                       $s = $this->makeTemplateLink( $itemTemplate, 'mytalk', $talkPage, wfMsg('mytalk') );
+               } else {
+                       $s = '';
+               }
+               return new TplValue( $s, 'user' );
+       }
+       
+       function preferences( $itemTemplate ) {
+               if ( $this->isLoggedIn() ) {
+                       $s = $this->makeSpecialTemplateLink( $itemTemplate, 'preferences', 
+                               'Preferences', wfMsg( 'preferences' ) );
+               } else {
+                       $s = '';
+               }
+               return new TplValue( $s, array( 'loggedin', 'lang' ) );
+       }
+       
+       function watchlist( $itemTemplate ) {
+               if ( $this->isLoggedIn() ) {
+                       $s = $this->makeSpecialTemplateLink( $itemTemplate, 'watchlist', 
+                               'Watchlist', wfMsg( 'watchlist' ) );
+               } else {
+                       $s = '';
+               }
+               return new TplValue( $s, array( 'loggedin', 'lang' ) );
+       }
+       
+       function mycontris( $itemTemplate ) {
+               if ( $this->isLoggedIn() ) {
+                       global $wgUser;
+                       $s = $this->makeSpecialTemplateLink( $itemTemplate, 'mycontris', 
+                               "Contributions/" . $wgUser->getTitleKey(), wfMsg('mycontris') );
+               } else {
+                       $s = '';
+               }
+               return new TplValue( $s, 'user' );
+       }
+       
+       function logout( $itemTemplate ) {
+               if ( $this->isLoggedIn() ) {
+                       $s = $this->makeSpecialTemplateLink( $itemTemplate, 'logout', 
+                               'Userlogout', wfMsg( 'userlogout' ), 
+                                       $this->mTitle->getNamespace() === NS_SPECIAL && $this->mTitle->getText() === 'Preferences' 
+                                       ? '' : "returnto=" . $this->mTitle->getPrefixedURL() );
+               } else {
+                       $s = '';
+               }
+               return new TplValue( $s, 'loggedin dynamic' );
+       }
+       
+       function anonuserpage( $itemTemplate ) {
+               if ( $this->isLoggedIn() ) {
+                       $s = '';
+               } else {
+                       global $wgUser;
+                       $userPage = $this->getUserPageTitle();
+                       $s = $this->makeTemplateLink( $itemTemplate, 'userpage', $userPage, $wgUser->getName() );
+               }
+               return new TplValue( $s, '!loggedin dynamic' );
+       }
+       
+       function anontalk( $itemTemplate ) {
+               if ( $this->isLoggedIn() ) {
+                       $s = '';
+               } else {
+                       $userPage = $this->getUserPageTitle();
+                       $talkPage = $userPage->getTalkPage();
+                       $s = $this->makeTemplateLink( $itemTemplate, 'mytalk', $talkPage, wfMsg('anontalk') );
+               }
+               return new TplValue( $s, '!loggedin dynamic' );
+       }
+       
+       function anonlogin( $itemTemplate ) {
+               if ( $this->isLoggedIn() ) {
+                       $s = '';
+               } else {
+                       $s = $this->makeSpecialTemplateLink( $itemTemplate, 'anonlogin', 'Userlogin', 
+                               wfMsg( 'userlogin' ), 'returnto=' . urlencode( $this->getThisPDBK() ) );
+               }
+               return new TplValue( $s, '!loggedin dynamic' );
+       }
+       
+       function login( $itemTemplate ) {
+               if ( $this->isLoggedIn() ) {
+                       $s = '';
+               } else {
+                       $s = $this->makeSpecialTemplateLink( $itemTemplate, 'login', 'Userlogin', 
+                               wfMsg( 'userlogin' ), 'returnto=' . urlencode( $this->getThisPDBK() ) );
+               }
+               return new TplValue( $s, '!loggedin dynamic' );
+       }
+       
+       function logopath() { return $GLOBALS['wgLogo']; }
+       function mainpage() { return $this->makeI18nUrl( 'mainpage' ); }
+       
+       function sidebar( $startSection, $endSection, $innerTpl ) {
+               $s = '';
+               $lines = explode( "\n", wfMsgForContent( 'sidebar' ) );
+               $firstSection = true;
+               foreach ($lines as $line) {
+                       if (strpos($line, '*') !== 0)
+                               continue;
+                       if (strpos($line, '**') !== 0) {
+                               $bar = trim($line, '* ');
+                               $name = wfMsg( $bar ); 
+                               if (wfEmptyMsg($bar, $name)) {
+                                       $name = $bar;
+                               }
+                               if ( $firstSection ) {
+                                       $firstSection = false;
+                               } else {
+                                       $s .= $endSection;
+                               }
+                               $s .= strtr( $startSection,
+                                       array( 
+                                               '$bar' => htmlspecialchars( $bar ),
+                                               '$barname' => $name
+                                       ) );
+                       } else {
+                               if (strpos($line, '|') !== false) { // sanity check
+                                       $line = explode( '|' , trim($line, '* '), 2 );
+                                       $link = wfMsgForContent( $line[0] );
+                                       if ($link == '-')
+                                               continue;
+                                       if (wfEmptyMsg($line[1], $text = wfMsg($line[1])))
+                                               $text = $line[1];
+                                       if (wfEmptyMsg($line[0], $link))
+                                               $link = $line[0];
+                                       $href = $this->makeInternalOrExternalUrl( $link );
+                                       
+                                       $s .= strtr( $innerTpl,
+                                               array(
+                                                       '$text' => htmlspecialchars( $text ),
+                                                       '$href' => htmlspecialchars( $href ),
+                                                       '$id' => htmlspecialchars( 'n-' . strtr($line[1], ' ', '-') ),
+                                                       '$classactive' => ''
+                                               ) );
+                               } else { continue; }
+                       }
+               }
+               if ( !$firstSection ) {
+                       $s .= $endSection;
+               }
+
+               // Depends on user language only
+               return new TplValue( $s, 'lang' );
+       }
+       
+       function searchaction() {
+               // Static link
+               return $this->getSearchLink();
+       }
+       
+       function search() {
+               global $wgRequest;
+               return new TplValue( trim( $this->getSearch() ), 'special dynamic' );
+       }
+       
+       function notspecialpage() {
+               return new TplValue( $this->mTitle->getNamespace() != NS_SPECIAL, 'special' );
+       }
+       
+       function nav_whatlinkshere() {
+               return new TplValue( $this->makeSpecialParamUrl('Whatlinkshere' ), array(), true );
+       }
+
+       function article_exists() {
+               return new TplValue( (string)($this->mTitle->getArticleId() !== 0), 'title' );
+       }
+       
+       function nav_recentchangeslinked() {
+               return new TplValue( $this->makeSpecialParamUrl('Recentchangeslinked' ), array(), true );
+       }
+       
+       function feeds( $itemTemplate = '' ) {
+               if ( !$this->mOut->isSyndicated() ) {
+                       $feeds = '';
+               } elseif ( $itemTemplate == '' ) {
+                       // boolean only required
+                       $feeds = 'true';
+               } else {
+                       $feeds = '';
+                       global $wgFeedClasses, $wgRequest;
+                       foreach( $wgFeedClasses as $format => $class ) {
+                               $feeds .= strtr( $itemTemplate,
+                                       array( 
+                                               '$key' => htmlspecialchars( $format ),
+                                               '$text' => $format,
+                                               '$href' => $wgRequest->appendQuery( "feed=$format" )
+                                       ) );
+                       }
+               }
+               return new TplValue( $feeds, 'special dynamic' );
+       }
+
+       function is_userpage() {
+               list( $id, $ip ) = $this->getUserPageIdIp();
+               return new TplValue( (string)($id || $ip), 'title' );
+       }
+
+       function is_ns_mediawiki() {
+               return new TplValue( (string)$this->mTitle->getNamespace() == NS_MEDIAWIKI, 'title' );
+       }
+
+       function is_loggedin() {
+               global $wgUser;
+               return new TplValue( (string)($wgUser->isLoggedIn()), 'loggedin' );
+       }
+
+       function nav_contributions() {
+               $url = $this->makeSpecialParamUrl( 'Contributions', '', '{title_userurl}' );
+               return new TplValue( $url, array(), true );
+       }
+
+       function is_allowed( $right ) {
+               global $wgUser;
+               return new TplValue( (string)$wgUser->isAllowed( $right ), 'user' );
+       }
+       
+       function nav_blockip() {
+               $url = $this->makeSpecialParamUrl( 'Blockip', '', '{title_userurl}' );
+               return new TplValue( $url, array(), true );
+       }
+       
+       function nav_emailuser() {
+               global $wgEnableEmail, $wgEnableUserEmail, $wgUser;
+               if ( !$wgEnableEmail || !$wgEnableUserEmail ) return '';
+               
+               $url = $this->makeSpecialParamUrl( 'Emailuser', '', '{title_userurl}' );
+               return new TplValue( $url, array(), true );
+       }
+       
+       function nav_upload() {
+               global $wgEnableUploads, $wgUploadNavigationUrl;
+               if ( !$wgEnableUploads ) { 
+                       return '';
+               } elseif ( $wgUploadNavigationUrl ) {
+                       return $wgUploadNavigationUrl;
+               } else {
+                       return $this->makeSpecialUrl('Upload');
+               }
+       }
+       
+       function nav_specialpages() {
+               return $this->makeSpecialUrl('Specialpages');
+       }
+       
+       function nav_print() {
+               global $wgRequest, $wgArticle;
+               $action = $this->getAction();
+               $url = '';
+               if( $this->mTitle->getNamespace() !== NS_SPECIAL 
+                               && ($action == '' || $action == 'view' || $action == 'purge' ) ) 
+               {
+                       $revid = $wgArticle->getLatest();
+                       if ( $revid != 0 ) {
+                               $url = $wgRequest->appendQuery( 'printable=yes' );
+                       }
+               }
+               return new TplValue( $url, array( 'nonview dynamic', 'title' ) );
+       }
+       
+       function nav_permalink() {
+               $url = (string)$this->getPermalink();
+               return new TplValue( $url, 'dynamic' );
+       }
+
+       function nav_trackbacklink() {
+               global $wgUseTrackbacks;
+               if ( !$wgUseTrackbacks ) return '';
+
+               return new TplValue( $this->mTitle->trackbackURL(), 'title' );
+       }
+       
+       function is_permalink() {
+               return new TplValue( (string)($this->getPermalink() === false), 'nonview dynamic' );
+       }
+       
+       function toolboxend() {
+               // This is where the MonoBookTemplateToolboxEnd hook went in the old skin
+               return '';
+       }
+       
+       function language_urls( $outer, $inner ) {
+               global $wgHideInterlanguageLinks, $wgOut, $wgContLang;
+               if ( $wgHideInterlanguageLinks ) return '';
+
+               $links = $wgOut->getLanguageLinks();
+               $s = '';
+               if ( count( $links ) ) {
+                       foreach( $links as $l ) {
+                               $tmp = explode( ':', $l, 2 );
+                               $nt = Title::newFromText( $l );
+                               $s .= strtr( $inner,
+                                       array(
+                                               '$class' => htmlspecialchars( 'interwiki-' . $tmp[0] ),
+                                               '$href' => htmlspecialchars( $nt->getFullURL() ),
+                                               '$text' => ($wgContLang->getLanguageName( $nt->getInterwiki() ) != ''?
+                                                       $wgContLang->getLanguageName( $nt->getInterwiki() ) : $l ),
+                                       )
+                               );
+                       }
+                       $s = str_replace( '$body', $s, $outer );
+               }
+               return new TplValue( $s, 'dynamic' );
+       }
+       
+       function poweredbyico() { return $this->getPoweredBy(); }
+       function copyrightico() { return $this->getCopyrightIcon(); }
+
+       function lastmod() { 
+               global $wgMaxCredits;
+               if ( $wgMaxCredits ) return '';
+
+               if ( $this->isCurrentArticleView() ) {
+                       $s = $this->lastModified(); 
+               } else {
+                       $s = '';
+               }
+               return new TplValue( $s, 'dynamic' );
+       }
+       
+       function viewcount() {
+               global $wgDisableCounters;
+               if ( $wgDisableCounters ) return '';
+               
+               global $wgLang, $wgArticle;
+               if ( is_object( $wgArticle ) ) {
+                       $viewcount = $wgLang->formatNum( $wgArticle->getCount() );
+                       if ( $viewcount ) {
+                               $viewcount = wfMsg( "viewcount", $viewcount );
+                       } else {
+                               $viewcount = '';
+                       }
+               } else {
+                       $viewcount = '';
+               }
+               return new TplValue( $viewcount, 'dynamic' );
+       }
+       
+       function numberofwatchingusers() {
+               global $wgPageShowWatchingUsers;
+               if ( !$wgPageShowWatchingUsers ) return '';
+
+               $dbr =& wfGetDB( DB_SLAVE );
+               extract( $dbr->tableNames( 'watchlist' ) );
+               $sql = "SELECT COUNT(*) AS n FROM $watchlist
+                       WHERE wl_title='" . $dbr->strencode($this->mTitle->getDBKey()) .
+                       "' AND  wl_namespace=" . $this->mTitle->getNamespace() ;
+               $res = $dbr->query( $sql, 'SkinTemplate::outputPage');
+               $row = $dbr->fetchObject( $res );
+               $num = $row->n;
+               if ($num > 0) {
+                       $s = wfMsg('number_of_watching_users_pageview', $num);
+               } else {
+                       $s = '';
+               }
+               return new TplValue( $s, 'dynamic' );
+       }
+       
+       function credits() {
+               global $wgMaxCredits;
+               if ( !$wgMaxCredits ) return '';
+               
+               if ( $this->isCurrentArticleView() ) {
+                       require_once("Credits.php");
+                       global $wgArticle, $wgShowCreditsIfMax;
+                       $credits = getCredits($wgArticle, $wgMaxCredits, $wgShowCreditsIfMax);
+               } else {
+                       $credits = '';
+               }
+               return new TplValue( $credits, 'view dynamic' );
+       }
+       
+       function normalcopyright() {
+               return $this->getCopyright( 'normal' );
+       }
+
+       function historycopyright() {
+               return $this->getCopyright( 'history' );
+       }
+
+       function is_currentview() {
+               global $wgRequest;
+               return new TplValue( (string)$this->isCurrentArticleView(), 'view' );
+       }
+
+       function usehistorycopyright() {
+               global $wgRequest;
+               if ( wfMsgForContent( 'history_copyright' ) == '-' ) return '';
+               
+               $oldid = $this->getOldId();
+               $diff = $this->getDiff();
+               $use = (string)(!is_null( $oldid ) && is_null( $diff ));
+               return new TplValue( $use, 'nonview dynamic' );
+       }
+       
+       function privacy() {
+               return new TplValue( $this->privacyLink(), 'lang' );
+       }
+       function about() {
+               return new TplValue( $this->aboutLink(), 'lang' );
+       }
+       function disclaimer() {
+               return new TplValue( $this->disclaimerLink(), 'lang' );
+       }
+       function tagline() { 
+               # A reference to this tag existed in the old MonoBook.php, but the
+               # template data wasn't set anywhere
+               return ''; 
+       }
+       function reporttime() {
+               return new TplValue( $this->mOut->reportTime(), 'dynamic' );
+       }
+       
+       function msg( $name ) {
+               return new TplValue( wfMsg( $name ), 'lang' );
+       }
+       
+       function fallbackmsg( $name, $fallback ) {
+               $text = wfMsg( $name );
+               if ( wfEmptyMsg( $name, $text ) ) {
+                       $text = $fallback;
+               }
+               return new TplValue( $text,  'lang' );
+       }
+
+       /******************************************************
+        * Utility functions                                  *
+        ******************************************************/
+
+       /** Return true if this request is a valid, secure CSS preview */
+       function isCssPreview() {
+               if ( !isset( $this->mCssPreview ) ) {
+                       global $wgRequest, $wgAllowUserCss, $wgUser;
+                       $this->mCssPreview = 
+                               $wgAllowUserCss &&
+                               $wgUser->isLoggedIn() &&
+                               $this->mTitle->isCssSubpage() && 
+                               $this->userCanPreview( $this->getAction() );
+               }
+               return $this->mCssPreview;
+       }
+
+       /** Return true if this request is a valid, secure JS preview */
+       function isJsPreview() {
+               if ( !isset( $this->mJsPreview ) ) {
+                       global $wgRequest, $wgAllowUserJs, $wgUser;
+                       $this->mJsPreview = 
+                               $wgAllowUserJs &&
+                               $wgUser->isLoggedIn() &&
+                               $this->mTitle->isJsSubpage() && 
+                               $this->userCanPreview( $this->getAction() );
+               }
+               return $this->mJsPreview;
+       }
+
+       /** Get the title of the $wgUser's user page */
+       function getUserPageTitle() {
+               if ( !isset( $this->mUserPageTitle ) ) {
+                       global $wgUser;
+                       $this->mUserPageTitle = $wgUser->getUserPage();
+               }
+               return $this->mUserPageTitle;
+       }
+
+       /** Get the text of the user page title */
+       function getUserPageText() {
+               if ( !isset( $this->mUserPageText ) ) {
+                       $userPage = $this->getUserPageTitle();
+                       $this->mUserPageText = $userPage->getPrefixedText();
+               }
+               return $this->mUserPageText;
+       }
+
+       /** Make an HTML element for a stylesheet link */
+       function makeStylesheetLink( $url ) {
+               return '<link rel="stylesheet" type="text/css" href="' . htmlspecialchars( $url ) . "\"/>";
+       }
+
+       /** Make an XHTML element for inline CSS */
+       function makeStylesheetCdata( $style ) {
+               return "<style type=\"text/css\"> /*<![CDATA[*/ {$style} /*]]>*/ </style>";
+       }
+
+       /** Get the edit URL for this page */
+       function getEditUrl() {
+               if ( !isset( $this->mEditUrl ) ) {
+                       $this->mEditUrl = $this->mTitle->getLocalUrl( $this->editUrlOptions() );
+               }
+               return $this->mEditUrl;
+       }
+
+       /** Get the prefixed DB key for this page */
+       function getThisPDBK() {
+               if ( !isset( $this->mThisPDBK ) ) {
+                       $this->mThisPDBK = $this->mTitle->getPrefixedDbKey();
+               }
+               return $this->mThisPDBK;
+       }
+
+       function getThisTitleUrlForm() {
+               if ( !isset( $this->mThisTitleUrlForm ) ) {
+                       $this->mThisTitleUrlForm = $this->mTitle->getPrefixedURL();
+               }
+               return $this->mThisTitleUrlForm;
+       }
+
+       /** 
+        * If the current page is a user page, get the user's ID and IP. Otherwise return array(0,false)
+        */
+       function getUserPageIdIp() {
+               if ( !isset( $this->mUserPageId ) ) {
+                       if( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
+                               $this->mUserPageId = User::idFromName($this->mTitle->getText());
+                               $this->mUserPageIp = User::isIP($this->mTitle->getText());
+                       } else {
+                               $this->mUserPageId = 0;
+                               $this->mUserPageIp = false;
+                       }
+               }
+               return array( $this->mUserPageId, $this->mUserPageIp );
+       }
+       
+       /**
+        * Returns a permalink URL, or false if the current page is already a 
+        * permalink, or blank if a permalink shouldn't be displayed
+        */
+       function getPermalink() {
+               if ( !isset( $this->mPermalink ) ) {
+                       global $wgRequest, $wgArticle;
+                       $action = $this->getAction();
+                       $oldid = $this->getOldId();
+                       $url = '';
+                       if( $this->mTitle->getNamespace() !== NS_SPECIAL 
+                                       && $this->mTitle->getArticleId() != 0
+                                       && ($action == '' || $action == 'view' || $action == 'purge' ) ) 
+                       {
+                               if ( !$oldid ) {
+                                       $revid = $wgArticle->getLatest();                       
+                                       $url = $this->mTitle->getLocalURL( "oldid=$revid" );
+                               } else {
+                                       $url = false;
+                               }
+                       } else {
+                               $url = '';
+                       }
+               }
+               return $url;
+       }
+
+       /**
+        * Returns true if the current page is an article, not a special page,
+        * and we are viewing a revision, not a diff
+        */
+       function isArticleView() {
+               global $wgOut, $wgArticle, $wgRequest;
+               if ( !isset( $this->mIsArticleView ) ) {
+                       $oldid = $this->getOldId();
+                       $diff = $this->getDiff();
+                       $this->mIsArticleView = $wgOut->isArticle() and 
+                               (!is_null( $oldid ) or is_null( $diff )) and 0 != $wgArticle->getID();
+               }
+               return $this->mIsArticleView;
+       }
+
+       function isCurrentArticleView() {
+               if ( !isset( $this->mIsCurrentArticleView ) ) {
+                       global $wgOut, $wgArticle, $wgRequest;
+                       $oldid = $this->getOldId();
+                       $this->mIsCurrentArticleView = $wgOut->isArticle() && is_null( $oldid ) && 0 != $wgArticle->getID();
+               }
+               return $this->mIsCurrentArticleView;
+       }
+
+
+       /**
+        * Return true if the current page is editable; if edit section on right 
+        * click should be enabled.
+        */
+       function isEditable() {
+               global $wgRequest;
+               $action = $this->getAction();
+               return ($this->mTitle->getNamespace() != NS_SPECIAL and !($action == 'edit' or $action == 'submit'));
+       }
+
+       /** Return true if the user is logged in */
+       function isLoggedIn() {
+               global $wgUser;
+               return $wgUser->isLoggedIn();
+       }
+
+       /** Get the local URL of the current page */
+       function getPageUrl() {
+               if ( !isset( $this->mPageUrl ) ) {
+                       $this->mPageUrl = $this->mTitle->getLocalURL();
+               } 
+               return $this->mPageUrl;
+       }
+
+       /** Make a link to a title using a template */
+       function makeTemplateLink( $template, $key, $title, $text ) {
+               $url = $title->getLocalUrl();
+               return strtr( $template, 
+                       array( 
+                               '$key' => $key,
+                               '$classactive' => ($url == $this->getPageUrl()) ? 'class="active"' : '',
+                               '$class' => $title->getArticleID() == 0 ? 'class="new"' : '', 
+                               '$href' => htmlspecialchars( $url ),
+                               '$text' => $text
+                        ) );
+       }
+
+       /** Make a link to a URL using a template */
+       function makeTemplateLinkUrl( $template, $key, $url, $text ) {
+               return strtr( $template, 
+                       array( 
+                               '$key' => $key,
+                               '$classactive' => ($url == $this->getPageUrl()) ? 'class="active"' : '',
+                               '$class' => '', 
+                               '$href' => htmlspecialchars( $url ),
+                               '$text' => $text
+                        ) );
+       }
+
+       /** Make a link to a special page using a template */
+       function makeSpecialTemplateLink( $template, $key, $specialName, $text, $query = '' ) {
+               $url = $this->makeSpecialUrl( $specialName, $query );
+               // Ignore the query when comparing
+               $active = ($this->mTitle->getNamespace() == NS_SPECIAL && $this->mTitle->getDBkey() == $specialName);
+               return strtr( $template, 
+                       array( 
+                               '$key' => $key,
+                               '$classactive' => $active ? 'class="active"' : '',
+                               '$class' => '', 
+                               '$href' => htmlspecialchars( $url ),
+                               '$text' => $text
+                        ) );
+       }
+
+       function loadRequestValues() {
+               global $wgRequest;
+               $this->mAction = $wgRequest->getText( 'action' );
+               $this->mOldId = $wgRequest->getVal( 'oldid' );
+               $this->mDiff = $wgRequest->getVal( 'diff' );
+               $this->mSection = $wgRequest->getVal( 'section' );
+               $this->mSearch = $wgRequest->getVal( 'search' );
+               $this->mRequestValuesLoaded = true;
+       }
+               
+
+
+       /** Get the action parameter of the request */
+       function getAction() {
+               if ( !isset( $this->mRequestValuesLoaded ) ) {
+                       $this->loadRequestValues();
+               }
+               return $this->mAction;
+       }
+
+       /** Get the oldid parameter */
+       function getOldId() {
+               if ( !isset( $this->mRequestValuesLoaded ) ) {
+                       $this->loadRequestValues();
+               }
+               return $this->mOldId;
+       }
+
+       /** Get the diff parameter */
+       function getDiff() {
+               if ( !isset( $this->mRequestValuesLoaded ) ) {
+                       $this->loadRequestValues();
+               }
+               return $this->mDiff;
+       }
+
+       function getSection() {
+               if ( !isset( $this->mRequestValuesLoaded ) ) {
+                       $this->loadRequestValues();
+               }
+               return $this->mSection;
+       }
+
+       function getSearch() {
+               if ( !isset( $this->mRequestValuesLoaded ) ) {
+                       $this->loadRequestValues();
+               }
+               return $this->mSearch;
+       }
+
+       /** Make a special page URL of the form [[Special:Somepage/{title_urlform}]] */
+       function makeSpecialParamUrl( $name, $query = '', $param = '{title_urlform}' ) {
+               // Abuse makeTitle's lax validity checking to slip a control character into the URL
+               $title = Title::makeTitle( NS_SPECIAL, "$name/\x1a" );
+               $url = templateEscape( $title->getLocalURL( $query ) );
+               // Now replace it with the parameter
+               return str_replace( '%1A', $param, $url );
+       }
+
+       function getSubjectPage() {
+               if ( !isset( $this->mSubjectPage ) ) {
+                       $this->mSubjectPage = $this->mTitle->getSubjectPage();
+               }
+               return $this->mSubjectPage;
+       }
+
+       function getTalkPage() {
+               if ( !isset( $this->mTalkPage ) ) {
+                       $this->mTalkPage = $this->mTitle->getTalkPage();
+               }
+               return $this->mTalkPage;
+       }
+}
+?>