Merge "resourceloader: Move registration of Resources.php to ServiceWiring"
authorjenkins-bot <jenkins-bot@gerrit.wikimedia.org>
Mon, 8 Apr 2019 03:54:04 +0000 (03:54 +0000)
committerGerrit Code Review <gerrit@wikimedia.org>
Mon, 8 Apr 2019 03:54:04 +0000 (03:54 +0000)
42 files changed:
.phan/config.php
RELEASE-NOTES-1.33
docs/hooks.txt
includes/CommentStore.php
includes/GlobalFunctions.php
includes/Title.php
includes/debug/DeprecationHelper.php
includes/export/Dump7ZipOutput.php
includes/export/DumpPipeOutput.php
includes/jobqueue/JobQueueMemory.php
includes/jobqueue/jobs/DeletePageJob.php
includes/jobqueue/jobs/UserGroupExpiryJob.php
includes/libs/objectcache/WinCacheBagOStuff.php
includes/libs/rdbms/database/Database.php
includes/libs/rdbms/database/IDatabase.php
includes/logging/LogEntry.php
includes/media/BitmapHandler.php
includes/media/DjVuHandler.php
includes/media/DjVuImage.php
includes/media/SvgHandler.php
includes/media/TransformationalImageHandler.php
includes/parser/Preprocessor_DOM.php
includes/resourceloader/ResourceLoader.php
includes/resourceloader/ResourceLoaderImage.php
includes/specials/SpecialEmailuser.php
includes/specials/SpecialVersion.php
includes/upload/UploadBase.php
includes/user/User.php
languages/Language.php
maintenance/7zip.inc
maintenance/Maintenance.php
maintenance/dumpTextPass.php
maintenance/hhvm/makeRepo.php
maintenance/hhvm/run-server
maintenance/mwdocgen.php
maintenance/populateImageSha1.php
maintenance/storage/checkStorage.php
maintenance/storage/recompressTracked.php
resources/src/mediawiki.Title/.eslintrc.json [new file with mode: 0644]
resources/src/mediawiki.Title/Title.js
tests/phpunit/MediaWikiTestCase.php
tests/phpunit/includes/db/LBFactoryTest.php

index 37b2153..12e723d 100644 (file)
@@ -90,8 +90,6 @@ $cfg['suppress_issue_types'] = array_merge( $cfg['suppress_issue_types'], [
        // approximate error count: 127
        "PhanParamTooMany",
        // approximate error count: 2
-       "PhanPluginDuplicateExpressionBinaryOp",
-       // approximate error count: 2
        "PhanTraitParentReference",
        // approximate error count: 30
        "PhanTypeArraySuspicious",
@@ -99,26 +97,16 @@ $cfg['suppress_issue_types'] = array_merge( $cfg['suppress_issue_types'], [
        "PhanTypeArraySuspiciousNullable",
        // approximate error count: 26
        "PhanTypeComparisonFromArray",
-       // approximate error count: 2
-       "PhanTypeComparisonToArray",
-       // approximate error count: 7
-       "PhanTypeExpectedObjectPropAccess",
        // approximate error count: 63
        "PhanTypeInvalidDimOffset",
-       // approximate error count: 6
-       "PhanTypeInvalidExpressionArrayDestructuring",
        // approximate error count: 7
        "PhanTypeInvalidLeftOperandOfIntegerOp",
        // approximate error count: 2
-       "PhanTypeInvalidRightOperand",
-       // approximate error count: 2
        "PhanTypeInvalidRightOperandOfIntegerOp",
        // approximate error count: 154
        "PhanTypeMismatchArgument",
        // approximate error count: 27
        "PhanTypeMismatchArgumentInternal",
-       // approximate error count: 1
-       "PhanTypeMismatchBitwiseBinaryOperands",
        // approximate error count: 2
        "PhanTypeMismatchDimEmpty",
        // approximate error count: 27
index 9c5081c..419560d 100644 (file)
@@ -436,6 +436,8 @@ because of Phabricator reports.
   insertions into links tables.
 * Category::newFromID( $id )->getID() will now return $id without any
   validation, to avoid a mostly unnecessary DB query.
+* On Special:Version, the name for an extension can no longer be arbitrary
+  html when no link is specified.
 
 == Compatibility ==
 MediaWiki 1.33 requires PHP 7.0.13 or later. Although HHVM 3.18.5 or later is
index 5f2c129..21e535c 100644 (file)
@@ -1612,7 +1612,7 @@ $out: OutputPage object
 notifications.
 &$title: Title object of page
 &$url: string value as output (out parameter, can modify)
-$query: query options passed to Title::getCanonicalURL()
+$query: query options as string passed to Title::getCanonicalURL()
 
 'GetContentModels': Add content models to the list of available models.
 &$models: array containing current model list, as strings. Extensions should add to this list.
@@ -1650,7 +1650,7 @@ $single: Only extract the current language; if false, the prop value should
 'GetFullURL': Modify fully-qualified URLs used in redirects/export/offsite data.
 &$title: Title object of page
 &$url: string value as output (out parameter, can modify)
-$query: query options passed to Title::getFullURL()
+$query: query options as string passed to Title::getFullURL()
 
 'GetHumanTimestamp': Pre-emptively override the human-readable timestamp
 generated by MWTimestamp::getHumanTimestamp(). Return false in this hook to use
@@ -1664,7 +1664,7 @@ $lang: Language that will be used to render the timestamp
 'GetInternalURL': Modify fully-qualified URLs used for squid cache purging.
 &$title: Title object of page
 &$url: string value as output (out parameter, can modify)
-$query: query options passed to Title::getInternalURL()
+$query: query options as string passed to Title::getInternalURL()
 
 'GetIP': modify the ip of the current user (called only once).
 &$ip: string holding the ip as determined so far
@@ -1689,7 +1689,7 @@ be buggy for internal urls on render if you do not re-implement the horrible
 hack that Title::getLocalURL uses in your own extension.
 &$title: Title object of page
 &$url: string value as output (out parameter, can modify)
-$query: query options passed to Title::getLocalURL()
+$query: query options as string passed to Title::getLocalURL()
 
 'GetLocalURL::Article': Modify local URLs specifically pointing to article paths
 without any fancy queries or variants.
@@ -1699,7 +1699,7 @@ without any fancy queries or variants.
 'GetLocalURL::Internal': Modify local URLs to internal pages.
 &$title: Title object of page
 &$url: string value as output (out parameter, can modify)
-$query: query options passed to Title::getLocalURL()
+$query: query options as string passed to Title::getLocalURL()
 
 'GetLogTypesOnUser': Add log types where the target is a userpage
 &$types: Array of log types
index 1a60bb7..4a673c4 100644 (file)
@@ -202,6 +202,7 @@ class CommentStore {
         *   - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
         *   - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
         *  All tables, fields, and joins are aliased, so `+` is safe to use.
+        * @phan-return array{tables:string[],fields:string[],joins:array}
         */
        public function getJoin( $key = null ) {
                $key = $this->getKey( $key );
index b0a79e8..cdbc27a 100644 (file)
@@ -2136,7 +2136,7 @@ function wfStringToBool( $val ) {
  * @param string|string[] ...$args strings to escape and glue together,
  *  or a single array of strings parameter
  * @return string
- * @deprecated since 1.30 use MediaWiki\Shell::escape()
+ * @deprecated since 1.30 use MediaWiki\Shell\Shell::escape()
  */
 function wfEscapeShellArg( ...$args ) {
        return Shell::escape( ...$args );
index 3d54750..3891c82 100644 (file)
@@ -58,6 +58,8 @@ class Title implements LinkTarget, IDBAccessObject {
         * Flag for use with factory methods like newFromLinkTarget() that have
         * a $forceClone parameter. If set, the method must return a new instance.
         * Without this flag, some factory methods may return existing instances.
+        *
+        * @since 1.33
         */
        const NEW_CLONE = 'clone';
 
@@ -2063,8 +2065,8 @@ class Title implements LinkTarget, IDBAccessObject {
         * protocol-relative, the URL will be expanded to http://
         *
         * @see self::getLocalURL for the arguments.
-        * @param string $query
-        * @param string|bool $query2
+        * @param string|string[] $query
+        * @param string|bool $query2 Deprecated
         * @return string The URL
         */
        public function getInternalURL( $query = '', $query2 = false ) {
@@ -2086,8 +2088,8 @@ class Title implements LinkTarget, IDBAccessObject {
         * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
         *
         * @see self::getLocalURL for the arguments.
-        * @param string $query
-        * @param string|bool $query2
+        * @param string|string[] $query
+        * @param string|bool $query2 Deprecated
         * @return string The URL
         * @since 1.18
         */
@@ -2730,7 +2732,7 @@ class Title implements LinkTarget, IDBAccessObject {
                $id = $this->getArticleID();
                if ( $id ) {
                        $fname = __METHOD__;
-                       $loadRestrictionsFromDb = function ( Database $dbr ) use ( $fname, $id ) {
+                       $loadRestrictionsFromDb = function ( IDatabase $dbr ) use ( $fname, $id ) {
                                return iterator_to_array(
                                        $dbr->select(
                                                'page_restrictions',
index cd78005..dc73ac9 100644 (file)
@@ -50,7 +50,7 @@ trait DeprecationHelper {
         * the name of the class defining the property, <component> is the MediaWiki component
         * (extension, skin etc.) for use in the deprecation warning) or null if it is MediaWiki.
         * E.g. [ 'mNewRev' => [ '1.32', 'DifferenceEngine', null ]
-        * @var string[]
+        * @var string[][]
         */
        protected $deprecatedPublicProperties = [];
 
@@ -68,7 +68,7 @@ trait DeprecationHelper {
        protected function deprecatePublicProperty(
                $property, $version, $class = null, $component = null
        ) {
-               $this->deprecatedPublicProperties[$property] = [ $version, $class ?: get_class(), $component ];
+               $this->deprecatedPublicProperties[$property] = [ $version, $class ?: __CLASS__, $component ];
        }
 
        public function __get( $name ) {
@@ -79,7 +79,7 @@ trait DeprecationHelper {
                        return $this->$name;
                }
 
-               $qualifiedName = get_class() . '::$' . $name;
+               $qualifiedName = __CLASS__ . '::$' . $name;
                if ( $this->deprecationHelperGetPropertyOwner( $name ) ) {
                        // Someone tried to access a normal non-public property. Try to behave like PHP would.
                        trigger_error( "Cannot access non-public property $qualifiedName", E_USER_ERROR );
@@ -99,7 +99,7 @@ trait DeprecationHelper {
                        return;
                }
 
-               $qualifiedName = get_class() . '::$' . $name;
+               $qualifiedName = __CLASS__ . '::$' . $name;
                if ( $this->deprecationHelperGetPropertyOwner( $name ) ) {
                        // Someone tried to access a normal non-public property. Try to behave like PHP would.
                        trigger_error( "Cannot access non-public property $qualifiedName", E_USER_ERROR );
index 31c945c..a50150e 100644 (file)
@@ -23,6 +23,8 @@
  * @file
  */
 
+use MediaWiki\Shell\Shell;
+
 /**
  * @ingroup Dump
  */
@@ -49,8 +51,8 @@ class Dump7ZipOutput extends DumpPipeOutput {
         */
        function setup7zCommand( $file ) {
                $command = "7za a -bd -si -mx=";
-               $command .= wfEscapeShellArg( $this->compressionLevel ) . ' ';
-               $command .= wfEscapeShellArg( $file );
+               $command .= Shell::escape( $this->compressionLevel ) . ' ';
+               $command .= Shell::escape( $file );
                // Suppress annoying useless crap from p7zip
                // Unfortunately this could suppress real error messages too
                $command .= ' >' . wfGetNull() . ' 2>&1';
index 26010da..a353c44 100644 (file)
@@ -25,6 +25,8 @@
  * @file
  */
 
+use MediaWiki\Shell\Shell;
+
 /**
  * @ingroup Dump
  */
@@ -38,7 +40,7 @@ class DumpPipeOutput extends DumpFileOutput {
         */
        function __construct( $command, $file = null ) {
                if ( !is_null( $file ) ) {
-                       $command .= " > " . wfEscapeShellArg( $file );
+                       $command .= " > " . Shell::escape( $file );
                }
 
                $this->startCommand( $command );
@@ -94,7 +96,7 @@ class DumpPipeOutput extends DumpFileOutput {
                        $this->renameOrException( $newname );
                        if ( $open ) {
                                $command = $this->command;
-                               $command .= " > " . wfEscapeShellArg( $this->filename );
+                               $command .= " > " . Shell::escape( $this->filename );
                                $this->startCommand( $command );
                        }
                }
index b6c4005..cbcd4fb 100644 (file)
@@ -151,7 +151,7 @@ class JobQueueMemory extends JobQueue {
                }
 
                $claimed =& $this->getQueueData( 'claimed' );
-               $job->setMetadata( 'claimId', null );
+               unset( $claimed[$job->getMetadata( 'claimId' )] );
        }
 
        /**
index 9b5cef4..e6dfae4 100644 (file)
@@ -4,7 +4,7 @@
  * Class DeletePageJob
  */
 class DeletePageJob extends Job {
-       public function __construct( $title, $params ) {
+       public function __construct( $title, $params = [] ) {
                parent::__construct( 'deletePage', $title, $params );
        }
 
index 0945e58..bd0df5b 100644 (file)
@@ -22,7 +22,7 @@
  */
 
 class UserGroupExpiryJob extends Job {
-       public function __construct( $params = false ) {
+       public function __construct( $params = [] ) {
                parent::__construct( 'userGroupExpiry', Title::newMainPage(), $params );
                $this->removeDuplicates = true;
        }
index 818f6f1..8c419b2 100644 (file)
@@ -70,12 +70,18 @@ class WinCacheBagOStuff extends BagOStuff {
        public function set( $key, $value, $expire = 0, $flags = 0 ) {
                $result = wincache_ucache_set( $key, serialize( $value ), $expire );
 
+               // false positive, wincache_ucache_set returns an empty array
+               // in some circumstances.
+               // @phan-suppress-next-line PhanTypeComparisonToArray
                return ( $result === [] || $result === true );
        }
 
        public function add( $key, $value, $exptime = 0, $flags = 0 ) {
                $result = wincache_ucache_add( $key, serialize( $value ), $exptime );
 
+               // false positive, wincache_ucache_add returns an empty array
+               // in some circumstances.
+               // @phan-suppress-next-line PhanTypeComparisonToArray
                return ( $result === [] || $result === true );
        }
 
index c5ef758..ba97887 100644 (file)
@@ -104,7 +104,7 @@ abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAware
        /** @var callable Deprecation logging callback */
        protected $deprecationLogger;
 
-       /** @var resource|null Database connection */
+       /** @var object|resource|null Database connection */
        protected $conn = null;
        /** @var bool */
        protected $opened = false;
index a8d4f1e..e25b4d2 100644 (file)
@@ -1013,6 +1013,7 @@ interface IDatabase {
         * @param string $valuename
         *
         * @return string
+        * @deprecated Since 1.33
         */
        public function aggregateValue( $valuedata, $valuename = 'value' );
 
index 5cad31f..c5e4a92 100644 (file)
@@ -100,7 +100,7 @@ interface LogEntry {
        /**
         * Get the access restriction.
         *
-        * @return string
+        * @return int
         */
        public function getDeleted();
 
index f003554..2d1c3b2 100644 (file)
@@ -21,6 +21,8 @@
  * @ingroup Media
  */
 
+use MediaWiki\Shell\Shell;
+
 /**
  * Generic handler for bitmap images
  *
@@ -228,7 +230,7 @@ class BitmapHandler extends TransformationalImageHandler {
                $rotation = isset( $params['disableRotation'] ) ? 0 : $this->getRotation( $image );
                list( $width, $height ) = $this->extractPreRotationDimensions( $params, $rotation );
 
-               $cmd = wfEscapeShellArg( ...array_merge(
+               $cmd = Shell::escape( ...array_merge(
                        [ $wgImageMagickConvertCommand ],
                        $quality,
                        // Specify white background color, will be used for transparent images
@@ -373,12 +375,12 @@ class BitmapHandler extends TransformationalImageHandler {
                global $wgCustomConvertCommand;
 
                # Variables: %s %d %w %h
-               $src = wfEscapeShellArg( $params['srcPath'] );
-               $dst = wfEscapeShellArg( $params['dstPath'] );
+               $src = Shell::escape( $params['srcPath'] );
+               $dst = Shell::escape( $params['dstPath'] );
                $cmd = $wgCustomConvertCommand;
                $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
-               $cmd = str_replace( '%h', wfEscapeShellArg( $params['physicalHeight'] ),
-                       str_replace( '%w', wfEscapeShellArg( $params['physicalWidth'] ), $cmd ) ); # Size
+               $cmd = str_replace( '%h', Shell::escape( $params['physicalHeight'] ),
+                       str_replace( '%w', Shell::escape( $params['physicalWidth'] ), $cmd ) ); # Size
                wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
                $retval = 0;
                $err = wfShellExecWithStderr( $cmd, $retval );
@@ -569,10 +571,10 @@ class BitmapHandler extends TransformationalImageHandler {
                $scaler = $this->getScalerType( null, false );
                switch ( $scaler ) {
                        case 'im':
-                               $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " .
-                                       wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
-                                       " -rotate " . wfEscapeShellArg( "-$rotation" ) . " " .
-                                       wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) );
+                               $cmd = Shell::escape( $wgImageMagickConvertCommand ) . " " .
+                                       Shell::escape( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
+                                       " -rotate " . Shell::escape( "-$rotation" ) . " " .
+                                       Shell::escape( $this->escapeMagickOutput( $params['dstPath'] ) );
                                wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
                                $retval = 0;
                                $err = wfShellExecWithStderr( $cmd, $retval );
index a0e7f2c..3b904e8 100644 (file)
@@ -21,6 +21,7 @@
  * @ingroup Media
  */
 use MediaWiki\MediaWikiServices;
+use MediaWiki\Shell\Shell;
 
 /**
  * Handler for DjVu images
@@ -204,7 +205,7 @@ class DjVuHandler extends ImageHandler {
 
                # Use a subshell (brackets) to aggregate stderr from both pipeline commands
                # before redirecting it to the overall stdout. This works in both Linux and Windows XP.
-               $cmd = '(' . wfEscapeShellArg(
+               $cmd = '(' . Shell::escape(
                        $wgDjvuRenderer,
                        "-format=ppm",
                        "-page={$page}",
@@ -213,7 +214,7 @@ class DjVuHandler extends ImageHandler {
                if ( $wgDjvuPostProcessor ) {
                        $cmd .= " | {$wgDjvuPostProcessor}";
                }
-               $cmd .= ' > ' . wfEscapeShellArg( $dstPath ) . ') 2>&1';
+               $cmd .= ' > ' . Shell::escape( $dstPath ) . ') 2>&1';
                wfDebug( __METHOD__ . ": $cmd\n" );
                $retval = '';
                $err = wfShellExec( $cmd, $retval );
index d059cd8..7189179 100644 (file)
@@ -24,6 +24,8 @@
  * @ingroup Media
  */
 
+use MediaWiki\Shell\Shell;
+
 /**
  * Support for detecting/validating DjVu image files and getting
  * some basic file metadata (resolution etc)
@@ -108,7 +110,7 @@ class DjVuImage {
                                $this->dumpForm( $file, $chunkLength, $indent + 1 );
                        } else {
                                fseek( $file, $chunkLength, SEEK_CUR );
-                               if ( $chunkLength & 1 == 1 ) {
+                               if ( ( $chunkLength & 1 ) == 1 ) {
                                        // Padding byte between chunks
                                        fseek( $file, 1, SEEK_CUR );
                                }
@@ -166,7 +168,7 @@ class DjVuImage {
        private function skipChunk( $file, $chunkLength ) {
                fseek( $file, $chunkLength, SEEK_CUR );
 
-               if ( $chunkLength & 0x01 == 1 && !feof( $file ) ) {
+               if ( ( $chunkLength & 0x01 ) == 1 && !feof( $file ) ) {
                        // padding byte
                        fseek( $file, 1, SEEK_CUR );
                }
@@ -253,19 +255,19 @@ class DjVuImage {
                if ( isset( $wgDjvuDump ) ) {
                        # djvudump is faster as of version 3.5
                        # https://sourceforge.net/p/djvu/bugs/71/
-                       $cmd = wfEscapeShellArg( $wgDjvuDump ) . ' ' . wfEscapeShellArg( $this->mFilename );
+                       $cmd = Shell::escape( $wgDjvuDump ) . ' ' . Shell::escape( $this->mFilename );
                        $dump = wfShellExec( $cmd );
                        $xml = $this->convertDumpToXML( $dump );
                } elseif ( isset( $wgDjvuToXML ) ) {
-                       $cmd = wfEscapeShellArg( $wgDjvuToXML ) . ' --without-anno --without-text ' .
-                               wfEscapeShellArg( $this->mFilename );
+                       $cmd = Shell::escape( $wgDjvuToXML ) . ' --without-anno --without-text ' .
+                               Shell::escape( $this->mFilename );
                        $xml = wfShellExec( $cmd );
                } else {
                        $xml = null;
                }
                # Text layer
                if ( isset( $wgDjvuTxt ) ) {
-                       $cmd = wfEscapeShellArg( $wgDjvuTxt ) . ' --detail=page ' . wfEscapeShellArg( $this->mFilename );
+                       $cmd = Shell::escape( $wgDjvuTxt ) . ' --detail=page ' . Shell::escape( $this->mFilename );
                        wfDebug( __METHOD__ . ": $cmd\n" );
                        $retval = '';
                        $txt = wfShellExec( $cmd, $retval, [], [ 'memory' => self::DJVUTXT_MEMORY_LIMIT ] );
index 4d75d04..bdda674 100644 (file)
@@ -20,6 +20,8 @@
  * @file
  * @ingroup Media
  */
+
+use MediaWiki\Shell\Shell;
 use Wikimedia\ScopedCallback;
 
 /**
@@ -335,11 +337,11 @@ class SvgHandler extends ImageHandler {
                                // External command
                                $cmd = str_replace(
                                        [ '$path/', '$width', '$height', '$input', '$output' ],
-                                       [ $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
+                                       [ $wgSVGConverterPath ? Shell::escape( "$wgSVGConverterPath/" ) : "",
                                                intval( $width ),
                                                intval( $height ),
-                                               wfEscapeShellArg( $srcPath ),
-                                               wfEscapeShellArg( $dstPath ) ],
+                                               Shell::escape( $srcPath ),
+                                               Shell::escape( $dstPath ) ],
                                        $wgSVGConverters[$wgSVGConverter]
                                );
 
index 38dc390..dbeca0b 100644 (file)
@@ -26,6 +26,7 @@
  * @ingroup Media
  */
 use MediaWiki\MediaWikiServices;
+use MediaWiki\Shell\Shell;
 
 /**
  * Handler for images that need to be transformed
@@ -517,7 +518,7 @@ abstract class TransformationalImageHandler extends ImageHandler {
                        function () use ( $method ) {
                                global $wgImageMagickConvertCommand;
 
-                               $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
+                               $cmd = Shell::escape( $wgImageMagickConvertCommand ) . ' -version';
                                wfDebug( $method . ": Running convert -version\n" );
                                $retval = '';
                                $return = wfShellExecWithStderr( $cmd, $retval );
index 3bcd012..4ed6b79 100644 (file)
@@ -858,6 +858,9 @@ class PPDStack {
                return $this->accum;
        }
 
+       /**
+        * @return bool|PPDPart
+        */
        public function getCurrentPart() {
                if ( $this->top === false ) {
                        return false;
@@ -970,6 +973,9 @@ class PPDStackElement {
                $this->parts[] = new $class( $s );
        }
 
+       /**
+        * @return PPDPart
+        */
        public function getCurrentPart() {
                return $this->parts[count( $this->parts ) - 1];
        }
index b8569d4..02e02bb 100644 (file)
@@ -1172,7 +1172,7 @@ MESSAGE;
         */
        private function ensureNewline( $str ) {
                $end = substr( $str, -1 );
-               if ( $end === false || $end === "\n" ) {
+               if ( $end === false || $end === '' || $end === "\n" ) {
                        return $str;
                }
                return $str . "\n";
@@ -1444,7 +1444,7 @@ MESSAGE;
                        }
                }
 
-               array_walk( $modules, [ 'self', 'trimArray' ] );
+               array_walk( $modules, [ self::class, 'trimArray' ] );
 
                return Xml::encodeJsCall(
                        'mw.loader.register',
index d10be12..27fa5ad 100644 (file)
@@ -20,6 +20,8 @@
  * @file
  */
 
+use MediaWiki\Shell\Shell;
+
 /**
  * Class encapsulating an image used in a ResourceLoaderImageModule.
  *
@@ -373,7 +375,7 @@ class ResourceLoaderImage {
                if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
                        $command = 'rsvg-convert';
                        if ( $wgSVGConverterPath ) {
-                               $command = wfEscapeShellArg( "$wgSVGConverterPath/" ) . $command;
+                               $command = Shell::escape( "$wgSVGConverterPath/" ) . $command;
                        }
 
                        $process = proc_open(
index ded0891..5f80215 100644 (file)
@@ -248,7 +248,8 @@ class SpecialEmailUser extends UnlistedSpecialPage {
         * @param User $user
         * @param string $editToken Edit token
         * @param Config|null $config optional for backwards compatibility
-        * @return string|null Null on success or string on error
+        * @return null|string|array Null on success, string on error, or array on
+        *  hook error
         */
        public static function getPermissionsError( $user, $editToken, Config $config = null ) {
                if ( $config === null ) {
index 2ad0def..391d9ab 100644 (file)
@@ -703,7 +703,7 @@ class SpecialVersion extends SpecialPage {
                                [ 'class' => 'mw-version-ext-name' ]
                        );
                } else {
-                       $extensionNameLink = $extensionName;
+                       $extensionNameLink = htmlspecialchars( $extensionName );
                }
 
                // ... and the version information
index 9e92e78..2bbe7c3 100644 (file)
@@ -21,6 +21,7 @@
  * @ingroup Upload
  */
 use MediaWiki\MediaWikiServices;
+use MediaWiki\Shell\Shell;
 
 /**
  * @defgroup Upload Upload related
@@ -1863,10 +1864,10 @@ abstract class UploadBase {
 
                if ( strpos( $command, "%f" ) === false ) {
                        # simple pattern: append file to scan
-                       $command .= " " . wfEscapeShellArg( $file );
+                       $command .= " " . Shell::escape( $file );
                } else {
                        # complex pattern: replace "%f" with file to scan
-                       $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
+                       $command = str_replace( "%f", Shell::escape( $file ), $command );
                }
 
                wfDebug( __METHOD__ . ": running virus scan: $command \n" );
index 311cac2..d2edbdf 100644 (file)
@@ -1675,7 +1675,7 @@ class User implements IDBAccessObject, UserIdentity {
         * @param array $conditions WHERE conditions for use with Database::update
         * @return array WHERE conditions for use with Database::update
         */
-       protected function makeUpdateConditions( Database $db, array $conditions ) {
+       protected function makeUpdateConditions( IDatabase $db, array $conditions ) {
                if ( $this->mTouched ) {
                        // CAS check: only update if the row wasn't changed sicne it was loaded.
                        $conditions['user_touched'] = $db->timestamp( $this->mTouched );
@@ -2205,6 +2205,9 @@ class User implements IDBAccessObject, UserIdentity {
 
                // Set the user limit key
                if ( $userLimit !== false ) {
+                       // phan is confused because &can-bypass's value is a bool, so it assumes
+                       // that $userLimit is also a bool here.
+                       // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
                        list( $max, $period ) = $userLimit;
                        wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
                        $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
@@ -2236,6 +2239,9 @@ class User implements IDBAccessObject, UserIdentity {
 
                $triggered = false;
                foreach ( $keys as $key => $limit ) {
+                       // phan is confused because &can-bypass's value is a bool, so it assumes
+                       // that $userLimit is also a bool here.
+                       // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
                        list( $max, $period ) = $limit;
                        $summary = "(limit $max in {$period}s)";
                        $count = $cache->get( $key );
index f72ac1a..52cb231 100644 (file)
@@ -3697,6 +3697,7 @@ class Language {
                                        }
                                } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
                                        # String in fact does need truncation, the truncation point was OK.
+                                       // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
                                        list( $ret, $openTags ) = $maybeState; // reload state
                                        $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
                                        $ret .= $ellipsis; // add ellipsis
index 9c1093b..6a763f2 100644 (file)
@@ -24,6 +24,8 @@
  * @ingroup Maintenance
  */
 
+use MediaWiki\Shell\Shell;
+
 /**
  * Stream wrapper around 7za filter program.
  * Required since we can't pass an open file resource to XMLReader->open()
@@ -48,7 +50,7 @@ class SevenZipStream {
                } else {
                        return false;
                }
-               $arg = wfEscapeShellArg( $this->stripPath( $path ) );
+               $arg = Shell::escape( $this->stripPath( $path ) );
                $command = "7za $options $arg";
                if ( !wfIsWindows() ) {
                        // Suppress the stupid messages on stderr
index 6e545a6..0d4f14c 100644 (file)
@@ -1615,10 +1615,10 @@ abstract class Maintenance {
                $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
                if ( !wfIsWindows() && $bash ) {
                        $retval = false;
-                       $encPrompt = wfEscapeShellArg( $prompt );
+                       $encPrompt = Shell::escape( $prompt );
                        $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
-                       $encCommand = wfEscapeShellArg( $command );
-                       $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
+                       $encCommand = Shell::escape( $command );
+                       $line = Shell::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
 
                        if ( $retval == 0 ) {
                                return $line;
index 61c63e9..7566fe0 100644 (file)
@@ -29,6 +29,7 @@ require_once __DIR__ . '/7zip.inc';
 require_once __DIR__ . '/../includes/export/WikiExporter.php';
 
 use MediaWiki\MediaWikiServices;
+use MediaWiki\Shell\Shell;
 use MediaWiki\Storage\BlobAccessException;
 use MediaWiki\Storage\SqlBlobStore;
 use Wikimedia\Rdbms\IMaintainableDatabase;
@@ -756,7 +757,7 @@ TEXT
 
                if ( file_exists( "$IP/../multiversion/MWScript.php" ) ) {
                        $cmd = implode( " ",
-                               array_map( 'wfEscapeShellArg',
+                               array_map( [ Shell::class, 'escape' ],
                                        [
                                                $this->php,
                                                "$IP/../multiversion/MWScript.php",
@@ -764,7 +765,7 @@ TEXT
                                                '--wiki', wfWikiID() ] ) );
                } else {
                        $cmd = implode( " ",
-                               array_map( 'wfEscapeShellArg',
+                               array_map( [ Shell::class, 'escape' ],
                                        [
                                                $this->php,
                                                "$IP/maintenance/fetchText.php",
index a8a0c71..9502cdc 100644 (file)
@@ -1,5 +1,7 @@
 <?php
 
+use MediaWiki\Shell\Shell;
+
 require __DIR__ . '/../Maintenance.php';
 
 class HHVMMakeRepo extends Maintenance {
@@ -103,7 +105,7 @@ class HHVMMakeRepo extends Maintenance {
 
                $hhvm = $this->getOption( 'hhvm', 'hhvm' );
                $verbose = $this->getOption( 'verbose', 3 );
-               $cmd = wfEscapeShellArg(
+               $cmd = Shell::escape(
                        $hhvm,
                        '--hphp',
                        '--target', 'hhbc',
index d84e02f..e1deb4c 100755 (executable)
@@ -1,6 +1,8 @@
 #!/usr/bin/hhvm -f
 <?php
 
+use MediaWiki\Shell\Shell;
+
 require __DIR__ . '/../Maintenance.php';
 
 class RunHipHopServer extends Maintenance {
@@ -12,8 +14,8 @@ class RunHipHopServer extends Maintenance {
                global $IP;
 
                passthru(
-                       'cd ' . wfEscapeShellArg( $IP ) . " && " .
-                       wfEscapeShellArg(
+                       'cd ' . Shell::escape( $IP ) . " && " .
+                       Shell::escape(
                                'hhvm',
                                '-c', __DIR__."/server.conf",
                                '--mode=server',
index 2d6a0be..791b360 100644 (file)
@@ -33,6 +33,8 @@
  * @version first release
  */
 
+use MediaWiki\Shell\Shell;
+
 require_once __DIR__ . '/Maintenance.php';
 
 /**
@@ -88,7 +90,7 @@ class MWDocGen extends Maintenance {
 
                // Do not use wfShellWikiCmd, because mwdoc-filter.php is not
                // a Maintenance script.
-               $this->inputFilter = wfEscapeShellArg( [
+               $this->inputFilter = Shell::escape( [
                        $wgPhpCli,
                        $IP . '/maintenance/mwdoc-filter.php'
                ] );
index 212a20d..a71abb6 100644 (file)
@@ -21,6 +21,8 @@
  * @ingroup Maintenance
  */
 
+use MediaWiki\Shell\Shell;
+
 require_once __DIR__ . '/Maintenance.php';
 
 /**
@@ -107,9 +109,9 @@ class PopulateImageSha1 extends LoggedUpdateMaintenance {
                        // in the pipe buffer. This can improve performance by up to a
                        // factor of 2.
                        global $wgDBuser, $wgDBserver, $wgDBpassword, $wgDBname;
-                       $cmd = 'mysql -u' . wfEscapeShellArg( $wgDBuser ) .
-                               ' -h' . wfEscapeShellArg( $wgDBserver ) .
-                               ' -p' . wfEscapeShellArg( $wgDBpassword, $wgDBname );
+                       $cmd = 'mysql -u' . Shell::escape( $wgDBuser ) .
+                               ' -h' . Shell::escape( $wgDBserver ) .
+                               ' -p' . Shell::escape( $wgDBpassword, $wgDBname );
                        $this->output( "Using pipe method\n" );
                        $pipe = popen( $cmd, 'w' );
                }
index 26d4e79..68184ea 100644 (file)
@@ -22,6 +22,7 @@
  */
 
 use MediaWiki\MediaWikiServices;
+use MediaWiki\Shell\Shell;
 
 if ( !defined( 'MEDIAWIKI' ) ) {
        $optionsWithoutArgs = [ 'fix' ];
@@ -451,7 +452,7 @@ class CheckStorage {
                echo "Filtering XML dump...\n";
                $exitStatus = 0;
                passthru( 'mwdumper ' .
-                       wfEscapeShellArg(
+                       Shell::escape(
                                "--output=file:$filteredXmlFileName",
                                "--filter=revlist:$revFileName",
                                $xml
index 7f89ce9..de52e7a 100644 (file)
@@ -24,6 +24,7 @@
 
 use MediaWiki\Logger\LegacyLogger;
 use MediaWiki\MediaWikiServices;
+use MediaWiki\Shell\Shell;
 use Wikimedia\Rdbms\IDatabase;
 
 $optionsWithArgs = RecompressTracked::getOptionsWithArgs();
@@ -215,19 +216,19 @@ class RecompressTracked {
         * writing are all slow.
         */
        function startReplicaProcs() {
-               $cmd = 'php ' . wfEscapeShellArg( __FILE__ );
+               $cmd = 'php ' . Shell::escape( __FILE__ );
                foreach ( self::$cmdLineOptionMap as $cmdOption => $classOption ) {
                        if ( $cmdOption == 'replica-id' ) {
                                continue;
                        } elseif ( in_array( $cmdOption, self::$optionsWithArgs ) && isset( $this->$classOption ) ) {
-                               $cmd .= " --$cmdOption " . wfEscapeShellArg( $this->$classOption );
+                               $cmd .= " --$cmdOption " . Shell::escape( $this->$classOption );
                        } elseif ( $this->$classOption ) {
                                $cmd .= " --$cmdOption";
                        }
                }
                $cmd .= ' --child' .
-                       ' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
-                       ' ' . wfEscapeShellArg( ...$this->destClusters );
+                       ' --wiki ' . Shell::escape( wfWikiID() ) .
+                       ' ' . Shell::escape( ...$this->destClusters );
 
                $this->replicaPipes = $this->replicaProcs = [];
                for ( $i = 0; $i < $this->numProcs; $i++ ) {
diff --git a/resources/src/mediawiki.Title/.eslintrc.json b/resources/src/mediawiki.Title/.eslintrc.json
new file mode 100644 (file)
index 0000000..ad8dbb3
--- /dev/null
@@ -0,0 +1,5 @@
+{
+       "parserOptions": {
+               "sourceType": "module"
+       }
+}
index 78ae135..900dab2 100644 (file)
 /*!
  * @author Neil Kandalgaonkar, 2010
- * @author Timo Tijhof
  * @since 1.18
  */
 
-( function () {
-       /**
-        * Parse titles into an object structure. Note that when using the constructor
-        * directly, passing invalid titles will result in an exception. Use #newFromText to use the
-        * logic directly and get null for invalid titles which is easier to work with.
-        *
-        * Note that in the constructor and #newFromText method, `namespace` is the **default** namespace
-        * only, and can be overridden by a namespace prefix in `title`. If you do not want this behavior,
-        * use #makeTitle. Compare:
-        *
-        *     new mw.Title( 'Foo', NS_TEMPLATE ).getPrefixedText();                  // => 'Template:Foo'
-        *     mw.Title.newFromText( 'Foo', NS_TEMPLATE ).getPrefixedText();          // => 'Template:Foo'
-        *     mw.Title.makeTitle( NS_TEMPLATE, 'Foo' ).getPrefixedText();            // => 'Template:Foo'
-        *
-        *     new mw.Title( 'Category:Foo', NS_TEMPLATE ).getPrefixedText();         // => 'Category:Foo'
-        *     mw.Title.newFromText( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
-        *     mw.Title.makeTitle( NS_TEMPLATE, 'Category:Foo' ).getPrefixedText();   // => 'Template:Category:Foo'
-        *
-        *     new mw.Title( 'Template:Foo', NS_TEMPLATE ).getPrefixedText();         // => 'Template:Foo'
-        *     mw.Title.newFromText( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
-        *     mw.Title.makeTitle( NS_TEMPLATE, 'Template:Foo' ).getPrefixedText();   // => 'Template:Template:Foo'
-        *
-        * @class mw.Title
-        */
-
-       /* Private members */
-
-       var
-               mwString = require( 'mediawiki.String' ),
-
-               toUpperMapping = require( './phpCharToUpper.json' ),
-
-               namespaceIds = mw.config.get( 'wgNamespaceIds' ),
-
-               /**
-                * @private
-                * @static
-                * @property NS_MAIN
-                */
-               NS_MAIN = namespaceIds[ '' ],
-
-               /**
-                * @private
-                * @static
-                * @property NS_TALK
-                */
-               NS_TALK = namespaceIds.talk,
-
-               /**
-                * @private
-                * @static
-                * @property NS_SPECIAL
-                */
-               NS_SPECIAL = namespaceIds.special,
-
-               /**
-                * @private
-                * @static
-                * @property NS_MEDIA
-                */
-               NS_MEDIA = namespaceIds.media,
-
-               /**
-                * @private
-                * @static
-                * @property NS_FILE
-                */
-               NS_FILE = namespaceIds.file,
-
-               /**
-                * @private
-                * @static
-                * @property FILENAME_MAX_BYTES
-                */
-               FILENAME_MAX_BYTES = 240,
-
-               /**
-                * @private
-                * @static
-                * @property TITLE_MAX_BYTES
-                */
-               TITLE_MAX_BYTES = 255,
-
-               /**
-                * Get the namespace id from a namespace name (either from the localized, canonical or alias
-                * name).
-                *
-                * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
-                * even 'Bild'.
-                *
-                * @private
-                * @static
-                * @method getNsIdByName
-                * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
-                * @return {number|boolean} Namespace id or boolean false
-                */
-               getNsIdByName = function ( ns ) {
-                       var id;
-
-                       // Don't cast non-strings to strings, because null or undefined should not result in
-                       // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
-                       // Also, toLowerCase throws exception on null/undefined, because it is a String method.
-                       if ( typeof ns !== 'string' ) {
-                               return false;
-                       }
-                       // TODO: Should just use local var namespaceIds here but it
-                       // breaks test which modify the config
-                       id = mw.config.get( 'wgNamespaceIds' )[ ns.toLowerCase() ];
-                       if ( id === undefined ) {
-                               return false;
-                       }
-                       return id;
-               },
-
-               /**
-                * @private
-                * @method getNamespacePrefix_
-                * @param {number} namespace
-                * @return {string}
-                */
-               getNamespacePrefix = function ( namespace ) {
-                       return namespace === NS_MAIN ?
-                               '' :
-                               ( mw.config.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g, '_' ) + ':' );
-               },
-
-               rUnderscoreTrim = /^_+|_+$/g,
-
-               rSplit = /^(.+?)_*:_*(.*)$/,
-
-               // See MediaWikiTitleCodec.php#getTitleInvalidRegex
-               rInvalid = new RegExp(
-                       '[^' + mw.config.get( 'wgLegalTitleChars' ) + ']' +
-                       // URL percent encoding sequences interfere with the ability
-                       // to round-trip titles -- you can't link to them consistently.
-                       '|%[0-9A-Fa-f]{2}' +
-                       // XML/HTML character references produce similar issues.
-                       '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
-                       '|&#[0-9]+;' +
-                       '|&#x[0-9A-Fa-f]+;'
-               ),
-
-               // From MediaWikiTitleCodec::splitTitleString() in PHP
-               // Note that this is not equivalent to /\s/, e.g. underscore is included, tab is not included.
-               rWhitespace = /[ _\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/g,
-
-               // From MediaWikiTitleCodec::splitTitleString() in PHP
-               rUnicodeBidi = /[\u200E\u200F\u202A-\u202E]/g,
-
-               /**
-                * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
-                * @private
-                * @static
-                * @property sanitationRules
-                */
-               sanitationRules = [
-                       // "signature"
-                       {
-                               pattern: /~{3}/g,
-                               replace: '',
-                               generalRule: true
-                       },
-                       // control characters
-                       {
-                               // eslint-disable-next-line no-control-regex
-                               pattern: /[\x00-\x1f\x7f]/g,
-                               replace: '',
-                               generalRule: true
-                       },
-                       // URL encoding (possibly)
-                       {
-                               pattern: /%([0-9A-Fa-f]{2})/g,
-                               replace: '% $1',
-                               generalRule: true
-                       },
-                       // HTML-character-entities
-                       {
-                               pattern: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
-                               replace: '& $1',
-                               generalRule: true
-                       },
-                       // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
-                       {
-                               pattern: new RegExp( '[' + mw.config.get( 'wgIllegalFileChars', '' ) + ']', 'g' ),
-                               replace: '-',
-                               fileRule: true
-                       },
-                       // brackets, greater than
-                       {
-                               pattern: /[}\]>]/g,
-                               replace: ')',
-                               generalRule: true
-                       },
-                       // brackets, lower than
-                       {
-                               pattern: /[{[<]/g,
-                               replace: '(',
-                               generalRule: true
-                       },
-                       // everything that wasn't covered yet
-                       {
-                               pattern: new RegExp( rInvalid.source, 'g' ),
-                               replace: '-',
-                               generalRule: true
-                       },
-                       // directory structures
-                       {
-                               pattern: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
-                               replace: '',
-                               generalRule: true
-                       }
-               ],
-
-               /**
-                * Internal helper for #constructor and #newFromText.
-                *
-                * Based on Title.php#secureAndSplit
-                *
-                * @private
-                * @static
-                * @method parse
-                * @param {string} title
-                * @param {number} [defaultNamespace=NS_MAIN]
-                * @return {Object|boolean}
-                */
-               parse = function ( title, defaultNamespace ) {
-                       var namespace, m, id, i, fragment, ext;
-
-                       namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
-
-                       title = title
-                               // Strip Unicode bidi override characters
-                               .replace( rUnicodeBidi, '' )
-                               // Normalise whitespace to underscores and remove duplicates
-                               .replace( rWhitespace, '_' )
-                               // Trim underscores
-                               .replace( rUnderscoreTrim, '' );
-
-                       // Process initial colon
-                       if ( title !== '' && title[ 0 ] === ':' ) {
-                               // Initial colon means main namespace instead of specified default
-                               namespace = NS_MAIN;
-                               title = title
-                                       // Strip colon
-                                       .slice( 1 )
-                                       // Trim underscores
-                                       .replace( rUnderscoreTrim, '' );
-                       }
-
-                       if ( title === '' ) {
-                               return false;
-                       }
-
-                       // Process namespace prefix (if any)
-                       m = title.match( rSplit );
-                       if ( m ) {
-                               id = getNsIdByName( m[ 1 ] );
-                               if ( id !== false ) {
-                                       // Ordinary namespace
-                                       namespace = id;
-                                       title = m[ 2 ];
-
-                                       // For Talk:X pages, make sure X has no "namespace" prefix
-                                       if ( namespace === NS_TALK && ( m = title.match( rSplit ) ) ) {
-                                               // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
-                                               if ( getNsIdByName( m[ 1 ] ) !== false ) {
-                                                       return false;
-                                               }
-                                       }
-                               }
-                       }
-
-                       // Process fragment
-                       i = title.indexOf( '#' );
-                       if ( i === -1 ) {
-                               fragment = null;
-                       } else {
-                               fragment = title
-                                       // Get segment starting after the hash
-                                       .slice( i + 1 )
-                                       // Convert to text
-                                       // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
-                                       .replace( /_/g, ' ' );
-
-                               title = title
-                                       // Strip hash
-                                       .slice( 0, i )
-                                       // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
-                                       .replace( rUnderscoreTrim, '' );
-                       }
-
-                       // Reject illegal characters
-                       if ( title.match( rInvalid ) ) {
-                               return false;
-                       }
-
-                       // Disallow titles that browsers or servers might resolve as directory navigation
-                       if (
-                               title.indexOf( '.' ) !== -1 && (
-                                       title === '.' || title === '..' ||
-                                       title.indexOf( './' ) === 0 ||
-                                       title.indexOf( '../' ) === 0 ||
-                                       title.indexOf( '/./' ) !== -1 ||
-                                       title.indexOf( '/../' ) !== -1 ||
-                                       title.slice( -2 ) === '/.' ||
-                                       title.slice( -3 ) === '/..'
-                               )
-                       ) {
-                               return false;
-                       }
-
-                       // Disallow magic tilde sequence
-                       if ( title.indexOf( '~~~' ) !== -1 ) {
-                               return false;
-                       }
-
-                       // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
-                       // Except for special pages, e.g. [[Special:Block/Long name]]
-                       // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
-                       // be less than 512 bytes.
-                       if ( namespace !== NS_SPECIAL && mwString.byteLength( title ) > TITLE_MAX_BYTES ) {
-                               return false;
-                       }
+/**
+ * Parse titles into an object structure. Note that when using the constructor
+ * directly, passing invalid titles will result in an exception. Use #newFromText to use the
+ * logic directly and get null for invalid titles which is easier to work with.
+ *
+ * Note that in the constructor and #newFromText method, `namespace` is the **default** namespace
+ * only, and can be overridden by a namespace prefix in `title`. If you do not want this behavior,
+ * use #makeTitle. Compare:
+ *
+ *     new mw.Title( 'Foo', NS_TEMPLATE ).getPrefixedText();                  // => 'Template:Foo'
+ *     mw.Title.newFromText( 'Foo', NS_TEMPLATE ).getPrefixedText();          // => 'Template:Foo'
+ *     mw.Title.makeTitle( NS_TEMPLATE, 'Foo' ).getPrefixedText();            // => 'Template:Foo'
+ *
+ *     new mw.Title( 'Category:Foo', NS_TEMPLATE ).getPrefixedText();         // => 'Category:Foo'
+ *     mw.Title.newFromText( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
+ *     mw.Title.makeTitle( NS_TEMPLATE, 'Category:Foo' ).getPrefixedText();   // => 'Template:Category:Foo'
+ *
+ *     new mw.Title( 'Template:Foo', NS_TEMPLATE ).getPrefixedText();         // => 'Template:Foo'
+ *     mw.Title.newFromText( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
+ *     mw.Title.makeTitle( NS_TEMPLATE, 'Template:Foo' ).getPrefixedText();   // => 'Template:Template:Foo'
+ *
+ * @class mw.Title
+ */
 
-                       // Can't make a link to a namespace alone.
-                       if ( title === '' && namespace !== NS_MAIN ) {
-                               return false;
-                       }
+/* Private members */
 
-                       // Any remaining initial :s are illegal.
-                       if ( title[ 0 ] === ':' ) {
-                               return false;
-                       }
+var
+       mwString = require( 'mediawiki.String' ),
 
-                       // For backwards-compatibility with old mw.Title, we separate the extension from the
-                       // rest of the title.
-                       i = title.lastIndexOf( '.' );
-                       if ( i === -1 || title.length <= i + 1 ) {
-                               // Extensions are the non-empty segment after the last dot
-                               ext = null;
-                       } else {
-                               ext = title.slice( i + 1 );
-                               title = title.slice( 0, i );
-                       }
+       toUpperMapping = require( './phpCharToUpper.json' ),
 
-                       return {
-                               namespace: namespace,
-                               title: title,
-                               ext: ext,
-                               fragment: fragment
-                       };
-               },
+       namespaceIds = mw.config.get( 'wgNamespaceIds' ),
 
-               /**
-                * Convert db-key to readable text.
-                *
-                * @private
-                * @static
-                * @method text
-                * @param {string} s
-                * @return {string}
-                */
-               text = function ( s ) {
-                       return s.replace( /_/g, ' ' );
-               },
+       /**
+        * @private
+        * @static
+        * @property NS_MAIN
+        */
+       NS_MAIN = namespaceIds[ '' ],
 
-               /**
-                * Sanitizes a string based on a rule set and a filter
-                *
-                * @private
-                * @static
-                * @method sanitize
-                * @param {string} s
-                * @param {Array} filter
-                * @return {string}
-                */
-               sanitize = function ( s, filter ) {
-                       var i, ruleLength, rule, m, filterLength,
-                               rules = sanitationRules;
-
-                       for ( i = 0, ruleLength = rules.length; i < ruleLength; ++i ) {
-                               rule = rules[ i ];
-                               for ( m = 0, filterLength = filter.length; m < filterLength; ++m ) {
-                                       if ( rule[ filter[ m ] ] ) {
-                                               s = s.replace( rule.pattern, rule.replace );
-                                       }
-                               }
-                       }
-                       return s;
-               },
+       /**
+        * @private
+        * @static
+        * @property NS_TALK
+        */
+       NS_TALK = namespaceIds.talk,
 
-               /**
-                * Cuts a string to a specific byte length, assuming UTF-8
-                * or less, if the last character is a multi-byte one
-                *
-                * @private
-                * @static
-                * @method trimToByteLength
-                * @param {string} s
-                * @param {number} length
-                * @return {string}
-                */
-               trimToByteLength = function ( s, length ) {
-                       return mwString.trimByteLength( '', s, length ).newVal;
-               },
+       /**
+        * @private
+        * @static
+        * @property NS_SPECIAL
+        */
+       NS_SPECIAL = namespaceIds.special,
 
-               /**
-                * Cuts a file name to a specific byte length
-                *
-                * @private
-                * @static
-                * @method trimFileNameToByteLength
-                * @param {string} name without extension
-                * @param {string} extension file extension
-                * @return {string} The full name, including extension
-                */
-               trimFileNameToByteLength = function ( name, extension ) {
-                       // There is a special byte limit for file names and ... remember the dot
-                       return trimToByteLength( name, FILENAME_MAX_BYTES - extension.length - 1 ) + '.' + extension;
-               };
+       /**
+        * @private
+        * @static
+        * @property NS_MEDIA
+        */
+       NS_MEDIA = namespaceIds.media,
 
        /**
-        * @method constructor
-        * @param {string} title Title of the page. If no second argument given,
-        *  this will be searched for a namespace
-        * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
-        * @throws {Error} When the title is invalid
+        * @private
+        * @static
+        * @property NS_FILE
         */
-       function Title( title, namespace ) {
-               var parsed = parse( title, namespace );
-               if ( !parsed ) {
-                       throw new Error( 'Unable to parse title' );
-               }
+       NS_FILE = namespaceIds.file,
 
-               this.namespace = parsed.namespace;
-               this.title = parsed.title;
-               this.ext = parsed.ext;
-               this.fragment = parsed.fragment;
-       }
+       /**
+        * @private
+        * @static
+        * @property FILENAME_MAX_BYTES
+        */
+       FILENAME_MAX_BYTES = 240,
 
-       /* Static members */
+       /**
+        * @private
+        * @static
+        * @property TITLE_MAX_BYTES
+        */
+       TITLE_MAX_BYTES = 255,
 
        /**
-        * Constructor for Title objects with a null return instead of an exception for invalid titles.
+        * Get the namespace id from a namespace name (either from the localized, canonical or alias
+        * name).
         *
-        * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
-        * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
-        * details.
+        * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
+        * even 'Bild'.
         *
+        * @private
         * @static
-        * @param {string} title
-        * @param {number} [namespace=NS_MAIN] Default namespace
-        * @return {mw.Title|null} A valid Title object or null if the title is invalid
+        * @method getNsIdByName
+        * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
+        * @return {number|boolean} Namespace id or boolean false
         */
-       Title.newFromText = function ( title, namespace ) {
-               var t, parsed = parse( title, namespace );
-               if ( !parsed ) {
-                       return null;
+       getNsIdByName = function ( ns ) {
+               var id;
+
+               // Don't cast non-strings to strings, because null or undefined should not result in
+               // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
+               // Also, toLowerCase throws exception on null/undefined, because it is a String method.
+               if ( typeof ns !== 'string' ) {
+                       return false;
                }
+               // TODO: Should just use local var namespaceIds here but it
+               // breaks test which modify the config
+               id = mw.config.get( 'wgNamespaceIds' )[ ns.toLowerCase() ];
+               if ( id === undefined ) {
+                       return false;
+               }
+               return id;
+       },
 
-               t = Object.create( Title.prototype );
-               t.namespace = parsed.namespace;
-               t.title = parsed.title;
-               t.ext = parsed.ext;
-               t.fragment = parsed.fragment;
-
-               return t;
-       };
+       /**
+        * @private
+        * @method getNamespacePrefix_
+        * @param {number} namespace
+        * @return {string}
+        */
+       getNamespacePrefix = function ( namespace ) {
+               return namespace === NS_MAIN ?
+                       '' :
+                       ( mw.config.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g, '_' ) + ':' );
+       },
+
+       rUnderscoreTrim = /^_+|_+$/g,
+
+       rSplit = /^(.+?)_*:_*(.*)$/,
+
+       // See MediaWikiTitleCodec.php#getTitleInvalidRegex
+       rInvalid = new RegExp(
+               '[^' + mw.config.get( 'wgLegalTitleChars' ) + ']' +
+               // URL percent encoding sequences interfere with the ability
+               // to round-trip titles -- you can't link to them consistently.
+               '|%[0-9A-Fa-f]{2}' +
+               // XML/HTML character references produce similar issues.
+               '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
+               '|&#[0-9]+;' +
+               '|&#x[0-9A-Fa-f]+;'
+       ),
+
+       // From MediaWikiTitleCodec::splitTitleString() in PHP
+       // Note that this is not equivalent to /\s/, e.g. underscore is included, tab is not included.
+       rWhitespace = /[ _\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/g,
+
+       // From MediaWikiTitleCodec::splitTitleString() in PHP
+       rUnicodeBidi = /[\u200E\u200F\u202A-\u202E]/g,
 
        /**
-        * Constructor for Title objects with predefined namespace.
-        *
-        * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
-        * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
-        *
-        * The single exception to this is when `namespace` is 0, indicating the main namespace. The
-        * function behaves like #newFromText in that case.
-        *
+        * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
+        * @private
         * @static
-        * @param {number} namespace Namespace to use for the title
-        * @param {string} title
-        * @return {mw.Title|null} A valid Title object or null if the title is invalid
+        * @property sanitationRules
         */
-       Title.makeTitle = function ( namespace, title ) {
-               return mw.Title.newFromText( getNamespacePrefix( namespace ) + title );
-       };
+       sanitationRules = [
+               // "signature"
+               {
+                       pattern: /~{3}/g,
+                       replace: '',
+                       generalRule: true
+               },
+               // control characters
+               {
+                       // eslint-disable-next-line no-control-regex
+                       pattern: /[\x00-\x1f\x7f]/g,
+                       replace: '',
+                       generalRule: true
+               },
+               // URL encoding (possibly)
+               {
+                       pattern: /%([0-9A-Fa-f]{2})/g,
+                       replace: '% $1',
+                       generalRule: true
+               },
+               // HTML-character-entities
+               {
+                       pattern: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
+                       replace: '& $1',
+                       generalRule: true
+               },
+               // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
+               {
+                       pattern: new RegExp( '[' + mw.config.get( 'wgIllegalFileChars', '' ) + ']', 'g' ),
+                       replace: '-',
+                       fileRule: true
+               },
+               // brackets, greater than
+               {
+                       pattern: /[}\]>]/g,
+                       replace: ')',
+                       generalRule: true
+               },
+               // brackets, lower than
+               {
+                       pattern: /[{[<]/g,
+                       replace: '(',
+                       generalRule: true
+               },
+               // everything that wasn't covered yet
+               {
+                       pattern: new RegExp( rInvalid.source, 'g' ),
+                       replace: '-',
+                       generalRule: true
+               },
+               // directory structures
+               {
+                       pattern: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
+                       replace: '',
+                       generalRule: true
+               }
+       ],
 
        /**
-        * Constructor for Title objects from user input altering that input to
-        * produce a title that MediaWiki will accept as legal
+        * Internal helper for #constructor and #newFromText.
+        *
+        * Based on Title.php#secureAndSplit
         *
+        * @private
         * @static
+        * @method parse
         * @param {string} title
-        * @param {number|Object} [defaultNamespaceOrOptions=NS_MAIN]
-        *  If given, will used as default namespace for the given title.
-        *  This method can also be called with two arguments, in which case
-        *  this becomes options (see below).
-        * @param {Object} [options] additional options
-        * @param {boolean} [options.forUploading=true]
-        *  Makes sure that a file is uploadable under the title returned.
-        *  There are pages in the file namespace under which file upload is impossible.
-        *  Automatically assumed if the title is created in the Media namespace.
-        * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
+        * @param {number} [defaultNamespace=NS_MAIN]
+        * @return {Object|boolean}
         */
-       Title.newFromUserInput = function ( title, defaultNamespaceOrOptions, options ) {
-               var namespace, m, id, ext, parts,
-                       defaultNamespace;
-
-               // defaultNamespace is optional; check whether options moves up
-               if ( arguments.length < 3 && typeof defaultNamespace === 'object' ) {
-                       options = defaultNamespaceOrOptions;
-               } else {
-                       defaultNamespace = defaultNamespaceOrOptions;
-               }
-
-               // merge options into defaults
-               options = $.extend( {
-                       forUploading: true
-               }, options );
+       parse = function ( title, defaultNamespace ) {
+               var namespace, m, id, i, fragment, ext;
 
                namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
 
-               // Normalise additional whitespace
-               title = title.replace( /\s/g, ' ' ).trim();
+               title = title
+                       // Strip Unicode bidi override characters
+                       .replace( rUnicodeBidi, '' )
+                       // Normalise whitespace to underscores and remove duplicates
+                       .replace( rWhitespace, '_' )
+                       // Trim underscores
+                       .replace( rUnderscoreTrim, '' );
 
                // Process initial colon
                if ( title !== '' && title[ 0 ] === ':' ) {
                        namespace = NS_MAIN;
                        title = title
                                // Strip colon
-                               .substr( 1 )
+                               .slice( 1 )
                                // Trim underscores
                                .replace( rUnderscoreTrim, '' );
                }
 
+               if ( title === '' ) {
+                       return false;
+               }
+
                // Process namespace prefix (if any)
                m = title.match( rSplit );
                if ( m ) {
                                // Ordinary namespace
                                namespace = id;
                                title = m[ 2 ];
+
+                               // For Talk:X pages, make sure X has no "namespace" prefix
+                               if ( namespace === NS_TALK && ( m = title.match( rSplit ) ) ) {
+                                       // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
+                                       if ( getNsIdByName( m[ 1 ] ) !== false ) {
+                                               return false;
+                                       }
+                               }
                        }
                }
 
-               if (
-                       namespace === NS_MEDIA ||
-                       ( options.forUploading && ( namespace === NS_FILE ) )
-               ) {
-
-                       title = sanitize( title, [ 'generalRule', 'fileRule' ] );
+               // Process fragment
+               i = title.indexOf( '#' );
+               if ( i === -1 ) {
+                       fragment = null;
+               } else {
+                       fragment = title
+                               // Get segment starting after the hash
+                               .slice( i + 1 )
+                               // Convert to text
+                               // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
+                               .replace( /_/g, ' ' );
 
-                       // Operate on the file extension
-                       // Although it is possible having spaces between the name and the ".ext" this isn't nice for
-                       // operating systems hiding file extensions -> strip them later on
-                       parts = title.split( '.' );
+                       title = title
+                               // Strip hash
+                               .slice( 0, i )
+                               // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
+                               .replace( rUnderscoreTrim, '' );
+               }
 
-                       if ( parts.length > 1 ) {
+               // Reject illegal characters
+               if ( title.match( rInvalid ) ) {
+                       return false;
+               }
 
-                               // Get the last part, which is supposed to be the file extension
-                               ext = parts.pop();
+               // Disallow titles that browsers or servers might resolve as directory navigation
+               if (
+                       title.indexOf( '.' ) !== -1 && (
+                               title === '.' || title === '..' ||
+                               title.indexOf( './' ) === 0 ||
+                               title.indexOf( '../' ) === 0 ||
+                               title.indexOf( '/./' ) !== -1 ||
+                               title.indexOf( '/../' ) !== -1 ||
+                               title.slice( -2 ) === '/.' ||
+                               title.slice( -3 ) === '/..'
+                       )
+               ) {
+                       return false;
+               }
 
-                               // Remove whitespace of the name part (that W/O extension)
-                               title = parts.join( '.' ).trim();
+               // Disallow magic tilde sequence
+               if ( title.indexOf( '~~~' ) !== -1 ) {
+                       return false;
+               }
 
-                               // Cut, if too long and append file extension
-                               title = trimFileNameToByteLength( title, ext );
+               // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
+               // Except for special pages, e.g. [[Special:Block/Long name]]
+               // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
+               // be less than 512 bytes.
+               if ( namespace !== NS_SPECIAL && mwString.byteLength( title ) > TITLE_MAX_BYTES ) {
+                       return false;
+               }
 
-                       } else {
+               // Can't make a link to a namespace alone.
+               if ( title === '' && namespace !== NS_MAIN ) {
+                       return false;
+               }
 
-                               // Missing file extension
-                               title = parts.join( '.' ).trim();
+               // Any remaining initial :s are illegal.
+               if ( title[ 0 ] === ':' ) {
+                       return false;
+               }
 
-                               // Name has no file extension and a fallback wasn't provided either
-                               return null;
-                       }
+               // For backwards-compatibility with old mw.Title, we separate the extension from the
+               // rest of the title.
+               i = title.lastIndexOf( '.' );
+               if ( i === -1 || title.length <= i + 1 ) {
+                       // Extensions are the non-empty segment after the last dot
+                       ext = null;
                } else {
-
-                       title = sanitize( title, [ 'generalRule' ] );
-
-                       // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
-                       // (size of underlying database field)
-                       if ( namespace !== NS_SPECIAL ) {
-                               title = trimToByteLength( title, TITLE_MAX_BYTES );
-                       }
+                       ext = title.slice( i + 1 );
+                       title = title.slice( 0, i );
                }
 
-               // Any remaining initial :s are illegal.
-               title = title.replace( /^:+/, '' );
-
-               return Title.newFromText( title, namespace );
-       };
+               return {
+                       namespace: namespace,
+                       title: title,
+                       ext: ext,
+                       fragment: fragment
+               };
+       },
 
        /**
-        * Sanitizes a file name as supplied by the user, originating in the user's file system
-        * so it is most likely a valid MediaWiki title and file name after processing.
-        * Returns null on fatal errors.
+        * Convert db-key to readable text.
         *
+        * @private
         * @static
-        * @param {string} uncleanName The unclean file name including file extension but
-        *   without namespace
-        * @return {mw.Title|null} A valid Title object or null if the title is invalid
+        * @method text
+        * @param {string} s
+        * @return {string}
         */
-       Title.newFromFileName = function ( uncleanName ) {
+       text = function ( s ) {
+               return s.replace( /_/g, ' ' );
+       },
 
-               return Title.newFromUserInput( 'File:' + uncleanName, {
-                       forUploading: true
-               } );
-       };
+       /**
+        * Sanitizes a string based on a rule set and a filter
+        *
+        * @private
+        * @static
+        * @method sanitize
+        * @param {string} s
+        * @param {Array} filter
+        * @return {string}
+        */
+       sanitize = function ( s, filter ) {
+               var i, ruleLength, rule, m, filterLength,
+                       rules = sanitationRules;
+
+               for ( i = 0, ruleLength = rules.length; i < ruleLength; ++i ) {
+                       rule = rules[ i ];
+                       for ( m = 0, filterLength = filter.length; m < filterLength; ++m ) {
+                               if ( rule[ filter[ m ] ] ) {
+                                       s = s.replace( rule.pattern, rule.replace );
+                               }
+                       }
+               }
+               return s;
+       },
 
        /**
-        * Get the file title from an image element
+        * Cuts a string to a specific byte length, assuming UTF-8
+        * or less, if the last character is a multi-byte one
         *
-        *     var title = mw.Title.newFromImg( $( 'img:first' ) );
+        * @private
+        * @static
+        * @method trimToByteLength
+        * @param {string} s
+        * @param {number} length
+        * @return {string}
+        */
+       trimToByteLength = function ( s, length ) {
+               return mwString.trimByteLength( '', s, length ).newVal;
+       },
+
+       /**
+        * Cuts a file name to a specific byte length
         *
+        * @private
         * @static
-        * @param {HTMLElement|jQuery} img The image to use as a base
-        * @return {mw.Title|null} The file title or null if unsuccessful
+        * @method trimFileNameToByteLength
+        * @param {string} name without extension
+        * @param {string} extension file extension
+        * @return {string} The full name, including extension
         */
-       Title.newFromImg = function ( img ) {
-               var matches, i, regex, src, decodedSrc,
+       trimFileNameToByteLength = function ( name, extension ) {
+               // There is a special byte limit for file names and ... remember the dot
+               return trimToByteLength( name, FILENAME_MAX_BYTES - extension.length - 1 ) + '.' + extension;
+       };
+
+/**
+ * @method constructor
+ * @param {string} title Title of the page. If no second argument given,
+ *  this will be searched for a namespace
+ * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
+ * @throws {Error} When the title is invalid
+ */
+function Title( title, namespace ) {
+       var parsed = parse( title, namespace );
+       if ( !parsed ) {
+               throw new Error( 'Unable to parse title' );
+       }
 
-                       // thumb.php-generated thumbnails
-                       thumbPhpRegex = /thumb\.php/,
-                       regexes = [
-                               // Thumbnails
-                               /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)\/[^\s/]+-[^\s/]*$/,
+       this.namespace = parsed.namespace;
+       this.title = parsed.title;
+       this.ext = parsed.ext;
+       this.fragment = parsed.fragment;
+}
+
+/* Static members */
+
+/**
+ * Constructor for Title objects with a null return instead of an exception for invalid titles.
+ *
+ * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
+ * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
+ * details.
+ *
+ * @static
+ * @param {string} title
+ * @param {number} [namespace=NS_MAIN] Default namespace
+ * @return {mw.Title|null} A valid Title object or null if the title is invalid
+ */
+Title.newFromText = function ( title, namespace ) {
+       var t, parsed = parse( title, namespace );
+       if ( !parsed ) {
+               return null;
+       }
+
+       t = Object.create( Title.prototype );
+       t.namespace = parsed.namespace;
+       t.title = parsed.title;
+       t.ext = parsed.ext;
+       t.fragment = parsed.fragment;
+
+       return t;
+};
+
+/**
+ * Constructor for Title objects with predefined namespace.
+ *
+ * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
+ * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
+ *
+ * The single exception to this is when `namespace` is 0, indicating the main namespace. The
+ * function behaves like #newFromText in that case.
+ *
+ * @static
+ * @param {number} namespace Namespace to use for the title
+ * @param {string} title
+ * @return {mw.Title|null} A valid Title object or null if the title is invalid
+ */
+Title.makeTitle = function ( namespace, title ) {
+       return mw.Title.newFromText( getNamespacePrefix( namespace ) + title );
+};
+
+/**
+ * Constructor for Title objects from user input altering that input to
+ * produce a title that MediaWiki will accept as legal
+ *
+ * @static
+ * @param {string} title
+ * @param {number|Object} [defaultNamespaceOrOptions=NS_MAIN]
+ *  If given, will used as default namespace for the given title.
+ *  This method can also be called with two arguments, in which case
+ *  this becomes options (see below).
+ * @param {Object} [options] additional options
+ * @param {boolean} [options.forUploading=true]
+ *  Makes sure that a file is uploadable under the title returned.
+ *  There are pages in the file namespace under which file upload is impossible.
+ *  Automatically assumed if the title is created in the Media namespace.
+ * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
+ */
+Title.newFromUserInput = function ( title, defaultNamespaceOrOptions, options ) {
+       var namespace, m, id, ext, parts,
+               defaultNamespace;
+
+       // defaultNamespace is optional; check whether options moves up
+       if ( arguments.length < 3 && typeof defaultNamespace === 'object' ) {
+               options = defaultNamespaceOrOptions;
+       } else {
+               defaultNamespace = defaultNamespaceOrOptions;
+       }
+
+       // merge options into defaults
+       options = $.extend( {
+               forUploading: true
+       }, options );
+
+       namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
+
+       // Normalise additional whitespace
+       title = title.replace( /\s/g, ' ' ).trim();
+
+       // Process initial colon
+       if ( title !== '' && title[ 0 ] === ':' ) {
+               // Initial colon means main namespace instead of specified default
+               namespace = NS_MAIN;
+               title = title
+                       // Strip colon
+                       .substr( 1 )
+                       // Trim underscores
+                       .replace( rUnderscoreTrim, '' );
+       }
+
+       // Process namespace prefix (if any)
+       m = title.match( rSplit );
+       if ( m ) {
+               id = getNsIdByName( m[ 1 ] );
+               if ( id !== false ) {
+                       // Ordinary namespace
+                       namespace = id;
+                       title = m[ 2 ];
+               }
+       }
 
-                               // Full size images
-                               /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)$/,
+       if (
+               namespace === NS_MEDIA ||
+               ( options.forUploading && ( namespace === NS_FILE ) )
+       ) {
 
-                               // Thumbnails in non-hashed upload directories
-                               /\/([^\s/]+)\/[^\s/]+-(?:\1|thumbnail)[^\s/]*$/,
+               title = sanitize( title, [ 'generalRule', 'fileRule' ] );
 
-                               // Full-size images in non-hashed upload directories
-                               /\/([^\s/]+)$/
-                       ],
+               // Operate on the file extension
+               // Although it is possible having spaces between the name and the ".ext" this isn't nice for
+               // operating systems hiding file extensions -> strip them later on
+               parts = title.split( '.' );
 
-                       recount = regexes.length;
+               if ( parts.length > 1 ) {
 
-               src = img.jquery ? img[ 0 ].src : img.src;
+                       // Get the last part, which is supposed to be the file extension
+                       ext = parts.pop();
 
-               matches = src.match( thumbPhpRegex );
+                       // Remove whitespace of the name part (that W/O extension)
+                       title = parts.join( '.' ).trim();
 
-               if ( matches ) {
-                       return mw.Title.newFromText( 'File:' + mw.util.getParamValue( 'f', src ) );
+                       // Cut, if too long and append file extension
+                       title = trimFileNameToByteLength( title, ext );
+
+               } else {
+
+                       // Missing file extension
+                       title = parts.join( '.' ).trim();
+
+                       // Name has no file extension and a fallback wasn't provided either
+                       return null;
                }
+       } else {
 
-               decodedSrc = decodeURIComponent( src );
+               title = sanitize( title, [ 'generalRule' ] );
 
-               for ( i = 0; i < recount; i++ ) {
-                       regex = regexes[ i ];
-                       matches = decodedSrc.match( regex );
+               // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
+               // (size of underlying database field)
+               if ( namespace !== NS_SPECIAL ) {
+                       title = trimToByteLength( title, TITLE_MAX_BYTES );
+               }
+       }
 
-                       if ( matches && matches[ 1 ] ) {
-                               return mw.Title.newFromText( 'File:' + matches[ 1 ] );
-                       }
+       // Any remaining initial :s are illegal.
+       title = title.replace( /^:+/, '' );
+
+       return Title.newFromText( title, namespace );
+};
+
+/**
+ * Sanitizes a file name as supplied by the user, originating in the user's file system
+ * so it is most likely a valid MediaWiki title and file name after processing.
+ * Returns null on fatal errors.
+ *
+ * @static
+ * @param {string} uncleanName The unclean file name including file extension but
+ *   without namespace
+ * @return {mw.Title|null} A valid Title object or null if the title is invalid
+ */
+Title.newFromFileName = function ( uncleanName ) {
+
+       return Title.newFromUserInput( 'File:' + uncleanName, {
+               forUploading: true
+       } );
+};
+
+/**
+ * Get the file title from an image element
+ *
+ *     var title = mw.Title.newFromImg( $( 'img:first' ) );
+ *
+ * @static
+ * @param {HTMLElement|jQuery} img The image to use as a base
+ * @return {mw.Title|null} The file title or null if unsuccessful
+ */
+Title.newFromImg = function ( img ) {
+       var matches, i, regex, src, decodedSrc,
+
+               // thumb.php-generated thumbnails
+               thumbPhpRegex = /thumb\.php/,
+               regexes = [
+                       // Thumbnails
+                       /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)\/[^\s/]+-[^\s/]*$/,
+
+                       // Full size images
+                       /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)$/,
+
+                       // Thumbnails in non-hashed upload directories
+                       /\/([^\s/]+)\/[^\s/]+-(?:\1|thumbnail)[^\s/]*$/,
+
+                       // Full-size images in non-hashed upload directories
+                       /\/([^\s/]+)$/
+               ],
+
+               recount = regexes.length;
+
+       src = img.jquery ? img[ 0 ].src : img.src;
+
+       matches = src.match( thumbPhpRegex );
+
+       if ( matches ) {
+               return mw.Title.newFromText( 'File:' + mw.util.getParamValue( 'f', src ) );
+       }
+
+       decodedSrc = decodeURIComponent( src );
+
+       for ( i = 0; i < recount; i++ ) {
+               regex = regexes[ i ];
+               matches = decodedSrc.match( regex );
+
+               if ( matches && matches[ 1 ] ) {
+                       return mw.Title.newFromText( 'File:' + matches[ 1 ] );
                }
+       }
+
+       return null;
+};
+
+/**
+ * Check if a given namespace is a talk namespace
+ *
+ * See MWNamespace::isTalk in PHP
+ *
+ * @param {number} namespaceId Namespace ID
+ * @return {boolean} Namespace is a talk namespace
+ */
+Title.isTalkNamespace = function ( namespaceId ) {
+       return !!( namespaceId > NS_MAIN && namespaceId % 2 );
+};
+
+/**
+ * Check if signature buttons should be shown in a given namespace
+ *
+ * See MWNamespace::wantSignatures in PHP
+ *
+ * @param {number} namespaceId Namespace ID
+ * @return {boolean} Namespace is a signature namespace
+ */
+Title.wantSignaturesNamespace = function ( namespaceId ) {
+       return Title.isTalkNamespace( namespaceId ) ||
+               mw.config.get( 'wgExtraSignatureNamespaces' ).indexOf( namespaceId ) !== -1;
+};
+
+/**
+ * Whether this title exists on the wiki.
+ *
+ * @static
+ * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
+ * @return {boolean|null} Boolean if the information is available, otherwise null
+ * @throws {Error} If title is not a string or mw.Title
+ */
+Title.exists = function ( title ) {
+       var match,
+               obj = Title.exist.pages;
+
+       if ( typeof title === 'string' ) {
+               match = obj[ title ];
+       } else if ( title instanceof Title ) {
+               match = obj[ title.toString() ];
+       } else {
+               throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
+       }
 
+       if ( typeof match !== 'boolean' ) {
                return null;
-       };
+       }
+
+       return match;
+};
+
+/**
+ * Store page existence
+ *
+ * @static
+ * @property {Object} exist
+ * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
+ *
+ * @property {Function} exist.set The setter function.
+ *
+ *  Example to declare existing titles:
+ *
+ *     Title.exist.set( ['User:John_Doe', ...] );
+ *
+ *  Example to declare titles nonexistent:
+ *
+ *     Title.exist.set( ['File:Foo_bar.jpg', ...], false );
+ *
+ * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
+ * @property {boolean} [exist.set.state=true] State of the given titles
+ * @return {boolean}
+ */
+Title.exist = {
+       pages: {},
+
+       set: function ( titles, state ) {
+               var i, len,
+                       pages = this.pages;
+
+               titles = Array.isArray( titles ) ? titles : [ titles ];
+               state = state === undefined ? true : !!state;
+
+               for ( i = 0, len = titles.length; i < len; i++ ) {
+                       pages[ titles[ i ] ] = state;
+               }
+               return true;
+       }
+};
+
+/**
+ * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
+ * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
+ * Keep in sync with File::normalizeExtension() in PHP.
+ *
+ * @param {string} extension File extension (without the leading dot)
+ * @return {string} File extension in canonical form
+ */
+Title.normalizeExtension = function ( extension ) {
+       var
+               lower = extension.toLowerCase(),
+               squish = {
+                       htm: 'html',
+                       jpeg: 'jpg',
+                       mpeg: 'mpg',
+                       tiff: 'tif',
+                       ogv: 'ogg'
+               };
+       if ( Object.prototype.hasOwnProperty.call( squish, lower ) ) {
+               return squish[ lower ];
+       } else if ( /^[0-9a-z]+$/.test( lower ) ) {
+               return lower;
+       } else {
+               return '';
+       }
+};
+
+/**
+ * PHP's strtoupper differs from String.toUpperCase in a number of cases (T147646).
+ *
+ * @param {string} chr Unicode character
+ * @return {string} Unicode character, in upper case, according to the same rules as in PHP
+ */
+Title.phpCharToUpper = function ( chr ) {
+       var mapped = toUpperMapping[ chr ];
+       return mapped || chr.toUpperCase();
+};
+
+/* Public members */
+
+Title.prototype = {
+       constructor: Title,
 
        /**
-        * Check if a given namespace is a talk namespace
+        * Get the namespace number
         *
-        * See MWNamespace::isTalk in PHP
+        * Example: 6 for "File:Example_image.svg".
         *
-        * @param {number} namespaceId Namespace ID
-        * @return {boolean} Namespace is a talk namespace
+        * @return {number}
         */
-       Title.isTalkNamespace = function ( namespaceId ) {
-               return !!( namespaceId > NS_MAIN && namespaceId % 2 );
-       };
+       getNamespaceId: function () {
+               return this.namespace;
+       },
 
        /**
-        * Check if signature buttons should be shown in a given namespace
+        * Get the namespace prefix (in the content language)
         *
-        * See MWNamespace::wantSignatures in PHP
+        * Example: "File:" for "File:Example_image.svg".
+        * In #NS_MAIN this is '', otherwise namespace name plus ':'
         *
-        * @param {number} namespaceId Namespace ID
-        * @return {boolean} Namespace is a signature namespace
+        * @return {string}
         */
-       Title.wantSignaturesNamespace = function ( namespaceId ) {
-               return Title.isTalkNamespace( namespaceId ) ||
-                       mw.config.get( 'wgExtraSignatureNamespaces' ).indexOf( namespaceId ) !== -1;
-       };
+       getNamespacePrefix: function () {
+               return getNamespacePrefix( this.namespace );
+       },
 
        /**
-        * Whether this title exists on the wiki.
+        * Get the page name without extension or namespace prefix
         *
-        * @static
-        * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
-        * @return {boolean|null} Boolean if the information is available, otherwise null
-        * @throws {Error} If title is not a string or mw.Title
+        * Example: "Example_image" for "File:Example_image.svg".
+        *
+        * For the page title (full page name without namespace prefix), see #getMain.
+        *
+        * @return {string}
         */
-       Title.exists = function ( title ) {
-               var match,
-                       obj = Title.exist.pages;
-
-               if ( typeof title === 'string' ) {
-                       match = obj[ title ];
-               } else if ( title instanceof Title ) {
-                       match = obj[ title.toString() ];
-               } else {
-                       throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
-               }
-
-               if ( typeof match !== 'boolean' ) {
-                       return null;
+       getName: function () {
+               if (
+                       mw.config.get( 'wgCaseSensitiveNamespaces' ).indexOf( this.namespace ) !== -1 ||
+                       !this.title.length
+               ) {
+                       return this.title;
                }
-
-               return match;
-       };
+               return mw.Title.phpCharToUpper( this.title[ 0 ] ) + this.title.slice( 1 );
+       },
 
        /**
-        * Store page existence
+        * Get the page name (transformed by #text)
         *
-        * @static
-        * @property {Object} exist
-        * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
+        * Example: "Example image" for "File:Example_image.svg".
         *
-        * @property {Function} exist.set The setter function.
+        * For the page title (full page name without namespace prefix), see #getMainText.
         *
-        *  Example to declare existing titles:
+        * @return {string}
+        */
+       getNameText: function () {
+               return text( this.getName() );
+       },
+
+       /**
+        * Get the extension of the page name (if any)
         *
-        *     Title.exist.set( ['User:John_Doe', ...] );
+        * @return {string|null} Name extension or null if there is none
+        */
+       getExtension: function () {
+               return this.ext;
+       },
+
+       /**
+        * Shortcut for appendable string to form the main page name.
         *
-        *  Example to declare titles nonexistent:
+        * Returns a string like ".json", or "" if no extension.
         *
-        *     Title.exist.set( ['File:Foo_bar.jpg', ...], false );
+        * @return {string}
+        */
+       getDotExtension: function () {
+               return this.ext === null ? '' : '.' + this.ext;
+       },
+
+       /**
+        * Get the main page name
         *
-        * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
-        * @property {boolean} [exist.set.state=true] State of the given titles
-        * @return {boolean}
+        * Example: "Example_image.svg" for "File:Example_image.svg".
+        *
+        * @return {string}
         */
-       Title.exist = {
-               pages: {},
+       getMain: function () {
+               return this.getName() + this.getDotExtension();
+       },
 
-               set: function ( titles, state ) {
-                       var i, len,
-                               pages = this.pages;
+       /**
+        * Get the main page name (transformed by #text)
+        *
+        * Example: "Example image.svg" for "File:Example_image.svg".
+        *
+        * @return {string}
+        */
+       getMainText: function () {
+               return text( this.getMain() );
+       },
 
-                       titles = Array.isArray( titles ) ? titles : [ titles ];
-                       state = state === undefined ? true : !!state;
+       /**
+        * Get the full page name
+        *
+        * Example: "File:Example_image.svg".
+        * Most useful for API calls, anything that must identify the "title".
+        *
+        * @return {string}
+        */
+       getPrefixedDb: function () {
+               return this.getNamespacePrefix() + this.getMain();
+       },
 
-                       for ( i = 0, len = titles.length; i < len; i++ ) {
-                               pages[ titles[ i ] ] = state;
-                       }
-                       return true;
-               }
-       };
+       /**
+        * Get the full page name (transformed by #text)
+        *
+        * Example: "File:Example image.svg" for "File:Example_image.svg".
+        *
+        * @return {string}
+        */
+       getPrefixedText: function () {
+               return text( this.getPrefixedDb() );
+       },
 
        /**
-        * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
-        * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
-        * Keep in sync with File::normalizeExtension() in PHP.
+        * Get the page name relative to a namespace
         *
-        * @param {string} extension File extension (without the leading dot)
-        * @return {string} File extension in canonical form
+        * Example:
+        *
+        * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
+        * - "Bar" relative to any non-main namespace becomes ":Bar".
+        * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
+        *
+        * @param {number} namespace The namespace to be relative to
+        * @return {string}
         */
-       Title.normalizeExtension = function ( extension ) {
-               var
-                       lower = extension.toLowerCase(),
-                       squish = {
-                               htm: 'html',
-                               jpeg: 'jpg',
-                               mpeg: 'mpg',
-                               tiff: 'tif',
-                               ogv: 'ogg'
-                       };
-               if ( Object.prototype.hasOwnProperty.call( squish, lower ) ) {
-                       return squish[ lower ];
-               } else if ( /^[0-9a-z]+$/.test( lower ) ) {
-                       return lower;
+       getRelativeText: function ( namespace ) {
+               if ( this.getNamespaceId() === namespace ) {
+                       return this.getMainText();
+               } else if ( this.getNamespaceId() === NS_MAIN ) {
+                       return ':' + this.getPrefixedText();
                } else {
-                       return '';
+                       return this.getPrefixedText();
                }
-       };
+       },
 
        /**
-        * PHP's strtoupper differs from String.toUpperCase in a number of cases (T147646).
+        * Get the fragment (if any).
         *
-        * @param {string} chr Unicode character
-        * @return {string} Unicode character, in upper case, according to the same rules as in PHP
+        * Note that this method (by design) does not include the hash character and
+        * the value is not url encoded.
+        *
+        * @return {string|null}
         */
-       Title.phpCharToUpper = function ( chr ) {
-               var mapped = toUpperMapping[ chr ];
-               return mapped || chr.toUpperCase();
-       };
-
-       /* Public members */
-
-       Title.prototype = {
-               constructor: Title,
-
-               /**
-                * Get the namespace number
-                *
-                * Example: 6 for "File:Example_image.svg".
-                *
-                * @return {number}
-                */
-               getNamespaceId: function () {
-                       return this.namespace;
-               },
-
-               /**
-                * Get the namespace prefix (in the content language)
-                *
-                * Example: "File:" for "File:Example_image.svg".
-                * In #NS_MAIN this is '', otherwise namespace name plus ':'
-                *
-                * @return {string}
-                */
-               getNamespacePrefix: function () {
-                       return getNamespacePrefix( this.namespace );
-               },
-
-               /**
-                * Get the page name without extension or namespace prefix
-                *
-                * Example: "Example_image" for "File:Example_image.svg".
-                *
-                * For the page title (full page name without namespace prefix), see #getMain.
-                *
-                * @return {string}
-                */
-               getName: function () {
-                       if (
-                               mw.config.get( 'wgCaseSensitiveNamespaces' ).indexOf( this.namespace ) !== -1 ||
-                               !this.title.length
-                       ) {
-                               return this.title;
-                       }
-                       return mw.Title.phpCharToUpper( this.title[ 0 ] ) + this.title.slice( 1 );
-               },
-
-               /**
-                * Get the page name (transformed by #text)
-                *
-                * Example: "Example image" for "File:Example_image.svg".
-                *
-                * For the page title (full page name without namespace prefix), see #getMainText.
-                *
-                * @return {string}
-                */
-               getNameText: function () {
-                       return text( this.getName() );
-               },
-
-               /**
-                * Get the extension of the page name (if any)
-                *
-                * @return {string|null} Name extension or null if there is none
-                */
-               getExtension: function () {
-                       return this.ext;
-               },
-
-               /**
-                * Shortcut for appendable string to form the main page name.
-                *
-                * Returns a string like ".json", or "" if no extension.
-                *
-                * @return {string}
-                */
-               getDotExtension: function () {
-                       return this.ext === null ? '' : '.' + this.ext;
-               },
-
-               /**
-                * Get the main page name
-                *
-                * Example: "Example_image.svg" for "File:Example_image.svg".
-                *
-                * @return {string}
-                */
-               getMain: function () {
-                       return this.getName() + this.getDotExtension();
-               },
-
-               /**
-                * Get the main page name (transformed by #text)
-                *
-                * Example: "Example image.svg" for "File:Example_image.svg".
-                *
-                * @return {string}
-                */
-               getMainText: function () {
-                       return text( this.getMain() );
-               },
-
-               /**
-                * Get the full page name
-                *
-                * Example: "File:Example_image.svg".
-                * Most useful for API calls, anything that must identify the "title".
-                *
-                * @return {string}
-                */
-               getPrefixedDb: function () {
-                       return this.getNamespacePrefix() + this.getMain();
-               },
-
-               /**
-                * Get the full page name (transformed by #text)
-                *
-                * Example: "File:Example image.svg" for "File:Example_image.svg".
-                *
-                * @return {string}
-                */
-               getPrefixedText: function () {
-                       return text( this.getPrefixedDb() );
-               },
-
-               /**
-                * Get the page name relative to a namespace
-                *
-                * Example:
-                *
-                * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
-                * - "Bar" relative to any non-main namespace becomes ":Bar".
-                * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
-                *
-                * @param {number} namespace The namespace to be relative to
-                * @return {string}
-                */
-               getRelativeText: function ( namespace ) {
-                       if ( this.getNamespaceId() === namespace ) {
-                               return this.getMainText();
-                       } else if ( this.getNamespaceId() === NS_MAIN ) {
-                               return ':' + this.getPrefixedText();
-                       } else {
-                               return this.getPrefixedText();
-                       }
-               },
-
-               /**
-                * Get the fragment (if any).
-                *
-                * Note that this method (by design) does not include the hash character and
-                * the value is not url encoded.
-                *
-                * @return {string|null}
-                */
-               getFragment: function () {
-                       return this.fragment;
-               },
-
-               /**
-                * Get the URL to this title
-                *
-                * @see mw.util#getUrl
-                * @param {Object} [params] A mapping of query parameter names to values,
-                *     e.g. `{ action: 'edit' }`.
-                * @return {string}
-                */
-               getUrl: function ( params ) {
-                       var fragment = this.getFragment();
-                       if ( fragment ) {
-                               return mw.util.getUrl( this.toString() + '#' + fragment, params );
-                       } else {
-                               return mw.util.getUrl( this.toString(), params );
-                       }
-               },
-
-               /**
-                * Check if the title is in a talk namespace
-                *
-                * @return {boolean} The title is in a talk namespace
-                */
-               isTalkPage: function () {
-                       return Title.isTalkNamespace( this.getNamespaceId() );
-               },
-
-               /**
-                * Get the title for the associated talk page
-                *
-                * @return {mw.Title|null} The title for the associated talk page, null if not available
-                */
-               getTalkPage: function () {
-                       if ( !this.canHaveTalkPage() ) {
-                               return null;
-                       }
-                       return this.isTalkPage() ?
-                               this :
-                               Title.makeTitle( this.getNamespaceId() + 1, this.getMainText() );
-               },
+       getFragment: function () {
+               return this.fragment;
+       },
 
-               /**
-                * Get the title for the subject page of a talk page
-                *
-                * @return {mw.Title|null} The title for the subject page of a talk page, null if not available
-                */
-               getSubjectPage: function () {
-                       return this.isTalkPage() ?
-                               Title.makeTitle( this.getNamespaceId() - 1, this.getMainText() ) :
-                               this;
-               },
+       /**
+        * Get the URL to this title
+        *
+        * @see mw.util#getUrl
+        * @param {Object} [params] A mapping of query parameter names to values,
+        *     e.g. `{ action: 'edit' }`.
+        * @return {string}
+        */
+       getUrl: function ( params ) {
+               var fragment = this.getFragment();
+               if ( fragment ) {
+                       return mw.util.getUrl( this.toString() + '#' + fragment, params );
+               } else {
+                       return mw.util.getUrl( this.toString(), params );
+               }
+       },
 
-               /**
-                * Check the the title can have an associated talk page
-                *
-                * @return {boolean} The title can have an associated talk page
-                */
-               canHaveTalkPage: function () {
-                       return this.getNamespaceId() >= NS_MAIN;
-               },
+       /**
+        * Check if the title is in a talk namespace
+        *
+        * @return {boolean} The title is in a talk namespace
+        */
+       isTalkPage: function () {
+               return Title.isTalkNamespace( this.getNamespaceId() );
+       },
 
-               /**
-                * Whether this title exists on the wiki.
-                *
-                * @see #static-method-exists
-                * @return {boolean|null} Boolean if the information is available, otherwise null
-                */
-               exists: function () {
-                       return Title.exists( this );
+       /**
+        * Get the title for the associated talk page
+        *
+        * @return {mw.Title|null} The title for the associated talk page, null if not available
+        */
+       getTalkPage: function () {
+               if ( !this.canHaveTalkPage() ) {
+                       return null;
                }
-       };
+               return this.isTalkPage() ?
+                       this :
+                       Title.makeTitle( this.getNamespaceId() + 1, this.getMainText() );
+       },
 
        /**
-        * @alias #getPrefixedDb
-        * @method
+        * Get the title for the subject page of a talk page
+        *
+        * @return {mw.Title|null} The title for the subject page of a talk page, null if not available
         */
-       Title.prototype.toString = Title.prototype.getPrefixedDb;
+       getSubjectPage: function () {
+               return this.isTalkPage() ?
+                       Title.makeTitle( this.getNamespaceId() - 1, this.getMainText() ) :
+                       this;
+       },
 
        /**
-        * @alias #getPrefixedText
-        * @method
+        * Check the the title can have an associated talk page
+        *
+        * @return {boolean} The title can have an associated talk page
         */
-       Title.prototype.toText = Title.prototype.getPrefixedText;
+       canHaveTalkPage: function () {
+               return this.getNamespaceId() >= NS_MAIN;
+       },
 
-       // Expose
-       mw.Title = Title;
+       /**
+        * Whether this title exists on the wiki.
+        *
+        * @see #static-method-exists
+        * @return {boolean|null} Boolean if the information is available, otherwise null
+        */
+       exists: function () {
+               return Title.exists( this );
+       }
+};
+
+/**
+ * @alias #getPrefixedDb
+ * @method
+ */
+Title.prototype.toString = Title.prototype.getPrefixedDb;
+
+/**
+ * @alias #getPrefixedText
+ * @method
+ */
+Title.prototype.toText = Title.prototype.getPrefixedText;
 
-}() );
+// Expose
+mw.Title = Title;
index 5119d73..8a38f42 100644 (file)
@@ -401,7 +401,8 @@ abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase {
                        self::$useTemporaryTables = !$this->getCliArg( 'use-normal-tables' );
                        self::$reuseDB = $this->getCliArg( 'reuse-db' );
 
-                       $this->db = wfGetDB( DB_MASTER );
+                       $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
+                       $this->db = $lb->getConnection( DB_MASTER );
 
                        $this->checkDbIsSupported();
 
@@ -1457,12 +1458,12 @@ abstract class MediaWikiTestCase extends PHPUnit\Framework\TestCase {
         * @note this method only works when first called. Subsequent calls have no effect,
         * even if using different parameters.
         *
-        * @param Database $db The database connection
+        * @param IMaintainableDatabase $db The database connection
         * @param string $prefix The prefix to use for the new table set (aka schema).
         *
         * @throws MWException If the database table prefix is already $prefix
         */
-       public static function setupTestDB( Database $db, $prefix ) {
+       public static function setupTestDB( IMaintainableDatabase $db, $prefix ) {
                if ( self::$dbSetup ) {
                        return;
                }
index 02c25e7..7d13ac6 100644 (file)
@@ -23,7 +23,6 @@
  * @copyright © 2013 Wikimedia Foundation Inc.
  */
 
-use Wikimedia\Rdbms\Database;
 use Wikimedia\Rdbms\IDatabase;
 use Wikimedia\Rdbms\IMaintainableDatabase;
 use Wikimedia\Rdbms\LBFactory;
@@ -730,7 +729,7 @@ class LBFactoryTest extends MediaWikiTestCase {
                $factory->destroy();
        }
 
-       private function quoteTable( Database $db, $table ) {
+       private function quoteTable( IDatabase $db, $table ) {
                if ( $db->getType() === 'sqlite' ) {
                        return $table;
                } else {