Merge "jquery.tablesorter: Silence an expected "sort-rowspan-error" warning"
[mediawiki.git] / resources / src / mediawiki.Title / Title.js
blobfd034852b6d791ba1b61b8fc7f783dab3c542d27
1 /*!
2 * @author Neil Kandalgaonkar, 2010
3 * @since 1.18
4 */
6 /* Private members */
8 let toUpperMap;
10 const mwString = require( 'mediawiki.String' ),
12 namespaceIds = mw.config.get( 'wgNamespaceIds' ),
14 /**
15 * @private
16 * @static
17 * @property {number} NS_MAIN
19 NS_MAIN = namespaceIds[ '' ],
21 /**
22 * @private
23 * @static
24 * @property {number} NS_TALK
26 NS_TALK = namespaceIds.talk,
28 /**
29 * @private
30 * @static
31 * @property {number} NS_SPECIAL
33 NS_SPECIAL = namespaceIds.special,
35 /**
36 * @private
37 * @static
38 * @property {number} NS_MEDIA
40 NS_MEDIA = namespaceIds.media,
42 /**
43 * @private
44 * @static
45 * @property {number} NS_FILE
47 NS_FILE = namespaceIds.file,
49 /**
50 * @private
51 * @static
52 * @property {number} FILENAME_MAX_BYTES
54 FILENAME_MAX_BYTES = 240,
56 /**
57 * @private
58 * @static
59 * @property {number} TITLE_MAX_BYTES
61 TITLE_MAX_BYTES = 255,
63 /**
64 * Get the namespace id from a namespace name (either from the localized, canonical or alias
65 * name).
67 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
68 * even 'Bild'.
70 * @private
71 * @static
72 * @method getNsIdByName
73 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
74 * @return {number|boolean} Namespace id or boolean false
76 getNsIdByName = function ( ns ) {
77 // Don't cast non-strings to strings, because null or undefined should not result in
78 // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
79 // Also, toLowerCase throws exception on null/undefined, because it is a String method.
80 if ( typeof ns !== 'string' ) {
81 return false;
83 // TODO: Should just use the local variable namespaceIds here, but it
84 // breaks test which modify the config
85 const id = mw.config.get( 'wgNamespaceIds' )[ ns.toLowerCase() ];
86 if ( id === undefined ) {
87 return false;
89 return id;
92 /**
93 * @private
94 * @method isKnownNamespace
95 * @param {number} namespace that may or may not exist
96 * @return {boolean}
98 isKnownNamespace = function ( namespace ) {
99 return namespace === NS_MAIN || mw.config.get( 'wgFormattedNamespaces' )[ namespace ] !== undefined;
103 * @private
104 * @method getNamespacePrefix
105 * @param {number} namespace that is valid and known. Callers should call
106 * `isKnownNamespace` before executing this method.
107 * @return {string}
109 getNamespacePrefix = function ( namespace ) {
110 return namespace === NS_MAIN ?
111 '' :
112 ( mw.config.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g, '_' ) + ':' );
115 rUnderscoreTrim = /^_+|_+$/g,
117 rSplit = /^(.+?)_*:_*(.*)$/,
119 // See MediaWikiTitleCodec.php#getTitleInvalidRegex
121 rInvalid = new RegExp(
122 '[^' + mw.config.get( 'wgLegalTitleChars' ) + ']' +
123 // URL percent encoding sequences interfere with the ability
124 // to round-trip titles -- you can't link to them consistently.
125 '|%[\\dA-Fa-f]{2}' +
126 // XML/HTML character references produce similar issues.
127 '|&[\\dA-Za-z\u0080-\uFFFF]+;'
130 // From MediaWikiTitleCodec::splitTitleString() in PHP
131 // Note that this is not equivalent to /\s/, e.g. underscore is included, tab is not included.
132 rWhitespace = /[ _\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/g,
134 // From MediaWikiTitleCodec::splitTitleString() in PHP
135 rUnicodeBidi = /[\u200E\u200F\u202A-\u202E]+/g,
138 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
140 * @private
141 * @static
142 * @property {Object[]} sanitationRules
144 sanitationRules = [
145 // "signature"
147 pattern: /~{3}/g,
148 replace: '',
149 generalRule: true
151 // control characters
153 // eslint-disable-next-line no-control-regex
154 pattern: /[\x00-\x1f\x7f]/g,
155 replace: '',
156 generalRule: true
158 // URL encoding (possibly)
160 pattern: /%([\dA-Fa-f]{2})/g,
161 replace: '% $1',
162 generalRule: true
164 // HTML-character-entities
166 pattern: /&(([\dA-Za-z\x80-\xff]+|#\d+|#x[\dA-Fa-f]+);)/g,
167 replace: '& $1',
168 generalRule: true
170 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
173 pattern: new RegExp( '[' + mw.config.get( 'wgIllegalFileChars', '' ) + ']', 'g' ),
174 replace: '-',
175 fileRule: true
177 // brackets, greater than
179 pattern: /[}\]>]/g,
180 replace: ')',
181 generalRule: true
183 // brackets, lower than
185 pattern: /[{[<]/g,
186 replace: '(',
187 generalRule: true
189 // everything that wasn't covered yet
192 pattern: new RegExp( rInvalid.source, 'g' ),
193 replace: '-',
194 generalRule: true
196 // directory structures
198 pattern: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
199 replace: '',
200 generalRule: true
205 * Internal helper for #constructor and #newFromText.
207 * Based on Title.php#secureAndSplit
209 * @private
210 * @static
211 * @method parse
212 * @param {string} title
213 * @param {number} [defaultNamespace=NS_MAIN]
214 * @return {Object|boolean}
216 parse = function ( title, defaultNamespace ) {
217 let namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
219 title = title
220 // Strip Unicode bidi override characters
221 .replace( rUnicodeBidi, '' )
222 // Normalise whitespace to underscores and remove duplicates
223 .replace( rWhitespace, '_' )
224 // Trim underscores
225 .replace( rUnderscoreTrim, '' );
227 if ( title.indexOf( '\uFFFD' ) !== -1 ) {
228 // Contained illegal UTF-8 sequences or forbidden Unicode chars.
229 // Commonly occurs when the text was obtained using the `URL` API, and the 'title' parameter
230 // was using a legacy 8-bit encoding, for example:
231 // new URL( 'https://en.wikipedia.org/w/index.php?title=Apollo%96Soyuz' ).searchParams.get( 'title' )
232 return false;
235 // Process initial colon
236 if ( title !== '' && title[ 0 ] === ':' ) {
237 // Initial colon means main namespace instead of specified default
238 namespace = NS_MAIN;
239 title = title
240 // Strip colon
241 .slice( 1 )
242 // Trim underscores
243 .replace( rUnderscoreTrim, '' );
246 if ( title === '' ) {
247 return false;
250 // Process namespace prefix (if any)
251 let m = title.match( rSplit );
252 if ( m ) {
253 const id = getNsIdByName( m[ 1 ] );
254 if ( id !== false ) {
255 // Ordinary namespace
256 namespace = id;
257 title = m[ 2 ];
259 // For Talk:X pages, make sure X has no "namespace" prefix
260 if ( namespace === NS_TALK && ( m = title.match( rSplit ) ) ) {
261 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
262 if ( getNsIdByName( m[ 1 ] ) !== false ) {
263 return false;
269 // Process fragment
270 const i = title.indexOf( '#' );
271 let fragment;
272 if ( i === -1 ) {
273 fragment = null;
274 } else {
275 fragment = title
276 // Get segment starting after the hash
277 .slice( i + 1 )
278 // Convert to text
279 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
280 .replace( /_/g, ' ' );
282 title = title
283 // Strip hash
284 .slice( 0, i )
285 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
286 .replace( rUnderscoreTrim, '' );
289 // Reject illegal characters
290 if ( rInvalid.test( title ) ) {
291 return false;
294 // Disallow titles that browsers or servers might resolve as directory navigation
295 if (
296 title.indexOf( '.' ) !== -1 && (
297 title === '.' || title === '..' ||
298 title.indexOf( './' ) === 0 ||
299 title.indexOf( '../' ) === 0 ||
300 title.indexOf( '/./' ) !== -1 ||
301 title.indexOf( '/../' ) !== -1 ||
302 title.slice( -2 ) === '/.' ||
303 title.slice( -3 ) === '/..'
306 return false;
309 // Disallow magic tilde sequence
310 if ( title.indexOf( '~~~' ) !== -1 ) {
311 return false;
314 // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
315 // Except for special pages, e.g. [[Special:Block/Long name]]
316 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
317 // be less than 512 bytes.
318 if ( namespace !== NS_SPECIAL && mwString.byteLength( title ) > TITLE_MAX_BYTES ) {
319 return false;
322 // Can't make a link to a namespace alone.
323 if ( title === '' && namespace !== NS_MAIN ) {
324 return false;
327 // Any remaining initial :s are illegal.
328 if ( title[ 0 ] === ':' ) {
329 return false;
332 return {
333 namespace: namespace,
334 title: title,
335 fragment: fragment
340 * Convert db-key to readable text.
342 * @private
343 * @static
344 * @method text
345 * @param {string} s
346 * @return {string}
348 text = function ( s ) {
349 return s.replace( /_/g, ' ' );
353 * Sanitizes a string based on a rule set and a filter
355 * @private
356 * @static
357 * @method sanitize
358 * @param {string} s
359 * @param {Array} filter
360 * @return {string}
362 sanitize = function ( s, filter ) {
363 const rules = sanitationRules;
365 for ( let i = 0, ruleLength = rules.length; i < ruleLength; ++i ) {
366 const rule = rules[ i ];
367 for ( let m = 0, filterLength = filter.length; m < filterLength; ++m ) {
368 if ( rule[ filter[ m ] ] ) {
369 s = s.replace( rule.pattern, rule.replace );
373 return s;
377 * Cuts a string to a specific byte length, assuming UTF-8
378 * or less, if the last character is a multi-byte one
380 * @private
381 * @static
382 * @method trimToByteLength
383 * @param {string} s
384 * @param {number} length
385 * @return {string}
387 trimToByteLength = function ( s, length ) {
388 return mwString.trimByteLength( '', s, length ).newVal;
392 * Cuts a file name to a specific byte length
394 * @private
395 * @static
396 * @method trimFileNameToByteLength
397 * @param {string} name without extension
398 * @param {string} extension file extension
399 * @return {string} The full name, including extension
401 trimFileNameToByteLength = function ( name, extension ) {
402 // There is a special byte limit for file names and ... remember the dot
403 return trimToByteLength( name, FILENAME_MAX_BYTES - extension.length - 1 ) + '.' + extension;
407 * @class mw.Title
408 * @classdesc Library for constructing MediaWiki titles.
410 * @example
411 * new mw.Title( 'Foo', NS_TEMPLATE ).getPrefixedText();
412 * // => 'Template:Foo'
413 * mw.Title.newFromText( 'Foo', NS_TEMPLATE ).getPrefixedText();
414 * // => 'Template:Foo'
415 * mw.Title.makeTitle( NS_TEMPLATE, 'Foo' ).getPrefixedText();
416 * // => 'Template:Foo'
418 * new mw.Title( 'Category:Foo', NS_TEMPLATE ).getPrefixedText();
419 * // => 'Category:Foo'
420 * mw.Title.newFromText( 'Category:Foo', NS_TEMPLATE ).getPrefixedText();
421 * // => 'Category:Foo'
422 * mw.Title.makeTitle( NS_TEMPLATE, 'Category:Foo' ).getPrefixedText();
423 * // => 'Template:Category:Foo'
425 * new mw.Title( 'Template:Foo', NS_TEMPLATE ).getPrefixedText();
426 * // => 'Template:Foo'
427 * mw.Title.newFromText( 'Template:Foo', NS_TEMPLATE ).getPrefixedText();
428 * // => 'Template:Foo'
429 * mw.Title.makeTitle( NS_TEMPLATE, 'Template:Foo' ).getPrefixedText();
430 * // => 'Template:Template:Foo'
432 * @constructor
433 * @description Parse titles into an object structure. Note that when using the constructor
434 * directly, passing invalid titles will result in an exception.
435 * Use [newFromText]{@link mw.Title.newFromText} to use the
436 * logic directly and get null for invalid titles which is easier to work with.
438 * Note that in the constructor and [newFromText]{@link mw.Title.newFromText} method,
439 * `namespace` is the **default** namespace only, and can be overridden by a namespace
440 * prefix in `title`. If you do not want this behavior,
441 * use [makeTitle]{@link mw.Title.makeTitle}.
443 * @param {string} title Title of the page. If no second argument given,
444 * this will be searched for a namespace
445 * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
446 * @throws {Error} When the title is invalid
448 function Title( title, namespace ) {
449 const parsed = parse( title, namespace );
450 if ( !parsed ) {
451 throw new Error( 'Unable to parse title' );
454 this.namespace = parsed.namespace;
455 this.title = parsed.title;
456 this.fragment = parsed.fragment;
459 /* Static members */
462 * Constructor for Title objects with a null return instead of an exception for invalid titles.
464 * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
465 * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
466 * details.
468 * @name mw.Title.newFromText
469 * @method
470 * @param {string} title
471 * @param {number} [namespace=NS_MAIN] Default namespace
472 * @return {mw.Title|null} A valid Title object or null if the title is invalid
474 Title.newFromText = function ( title, namespace ) {
475 const parsed = parse( title, namespace );
476 if ( !parsed ) {
477 return null;
480 const t = Object.create( Title.prototype );
481 t.namespace = parsed.namespace;
482 t.title = parsed.title;
483 t.fragment = parsed.fragment;
485 return t;
489 * Constructor for Title objects with predefined namespace.
491 * Unlike [newFromText]{@link mw.Title.newFromText} or the constructor, this function doesn't allow the given `namespace` to be
492 * overridden by a namespace prefix in `title`. See the constructor documentation for details about this behavior.
494 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
495 * function behaves like [newFromText]{@link mw.Title.newFromText} in that case.
497 * @name mw.Title.makeTitle
498 * @method
499 * @param {number} namespace Namespace to use for the title
500 * @param {string} title
501 * @return {mw.Title|null} A valid Title object or null if the title is invalid
503 Title.makeTitle = function ( namespace, title ) {
504 if ( !isKnownNamespace( namespace ) ) {
505 return null;
506 } else {
507 return mw.Title.newFromText( getNamespacePrefix( namespace ) + title );
512 * Constructor for Title objects from user input altering that input to
513 * produce a title that MediaWiki will accept as legal.
515 * @name mw.Title.newFromUserInput
516 * @method
517 * @param {string} title
518 * @param {number} [defaultNamespace=NS_MAIN]
519 * If given, will used as default namespace for the given title.
520 * @param {Object} [options] additional options
521 * @param {boolean} [options.forUploading=true]
522 * Makes sure that a file is uploadable under the title returned.
523 * There are pages in the file namespace under which file upload is impossible.
524 * Automatically assumed if the title is created in the Media namespace.
525 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
527 Title.newFromUserInput = function ( title, defaultNamespace, options ) {
528 let namespace = parseInt( defaultNamespace ) || NS_MAIN;
530 // merge options into defaults
531 options = Object.assign( {
532 forUploading: true
533 }, options );
535 // Normalise additional whitespace
536 title = title.replace( /\s/g, ' ' ).trim();
538 // Process initial colon
539 if ( title !== '' && title[ 0 ] === ':' ) {
540 // Initial colon means main namespace instead of specified default
541 namespace = NS_MAIN;
542 title = title
543 // Strip colon
544 .slice( 1 )
545 // Trim underscores
546 .replace( rUnderscoreTrim, '' );
549 // Process namespace prefix (if any)
550 const m = title.match( rSplit );
551 if ( m ) {
552 const id = getNsIdByName( m[ 1 ] );
553 if ( id !== false ) {
554 // Ordinary namespace
555 namespace = id;
556 title = m[ 2 ];
560 if (
561 namespace === NS_MEDIA ||
562 ( options.forUploading && ( namespace === NS_FILE ) )
564 title = sanitize( title, [ 'generalRule', 'fileRule' ] );
566 // Operate on the file extension
567 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
568 // operating systems hiding file extensions -> strip them later on
569 const lastDot = title.lastIndexOf( '.' );
571 // No or empty file extension
572 if ( lastDot === -1 || lastDot >= title.length - 1 ) {
573 return null;
576 // Get the last part, which is supposed to be the file extension
577 const ext = title.slice( lastDot + 1 );
579 // Remove whitespace of the name part (that without extension)
580 title = title.slice( 0, lastDot ).trim();
582 // Cut, if too long and append file extension
583 title = trimFileNameToByteLength( title, ext );
584 } else {
585 title = sanitize( title, [ 'generalRule' ] );
587 // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
588 // (size of underlying database field)
589 if ( namespace !== NS_SPECIAL ) {
590 title = trimToByteLength( title, TITLE_MAX_BYTES );
594 // Any remaining initial :s are illegal.
595 title = title.replace( /^:+/, '' );
597 return Title.newFromText( title, namespace );
601 * Sanitizes a file name as supplied by the user, originating in the user's file system
602 * so it is most likely a valid MediaWiki title and file name after processing.
603 * Returns null on fatal errors.
605 * @name mw.Title.newFromFileName
606 * @method
607 * @param {string} uncleanName The unclean file name including file extension but
608 * without namespace
609 * @return {mw.Title|null} A valid Title object or null if the title is invalid
611 Title.newFromFileName = function ( uncleanName ) {
612 return Title.newFromUserInput( 'File:' + uncleanName );
616 * Get the file title from an image element.
618 * @example
619 * const title = mw.Title.newFromImg( imageNode );
621 * @name mw.Title.newFromImg
622 * @method
623 * @param {HTMLElement|jQuery} img The image to use as a base
624 * @return {mw.Title|null} The file title or null if unsuccessful
626 Title.newFromImg = function ( img ) {
627 const src = img.jquery ? img[ 0 ].src : img.src,
628 data = mw.util.parseImageUrl( src );
630 return data ? mw.Title.newFromText( 'File:' + data.name ) : null;
634 * Check if a given namespace is a talk namespace.
636 * See NamespaceInfo::isTalk in PHP
638 * @name mw.Title.isTalkNamespace
639 * @method
640 * @param {number} namespaceId Namespace ID
641 * @return {boolean} Namespace is a talk namespace
643 Title.isTalkNamespace = function ( namespaceId ) {
644 return namespaceId > NS_MAIN && namespaceId % 2 === 1;
648 * Check if signature buttons should be shown in a given namespace.
650 * See NamespaceInfo::wantSignatures in PHP
652 * @name mw.Title.wantSignaturesNamespace
653 * @method
654 * @param {number} namespaceId Namespace ID
655 * @return {boolean} Namespace is a signature namespace
657 Title.wantSignaturesNamespace = function ( namespaceId ) {
658 return Title.isTalkNamespace( namespaceId ) ||
659 mw.config.get( 'wgExtraSignatureNamespaces' ).indexOf( namespaceId ) !== -1;
663 * Whether this title exists on the wiki.
665 * @name mw.Title.exists
666 * @method
667 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
668 * @return {boolean|null} Boolean if the information is available, otherwise null
669 * @throws {Error} If title is not a string or mw.Title
671 Title.exists = function ( title ) {
672 const obj = Title.exist.pages;
674 let match;
675 if ( typeof title === 'string' ) {
676 match = obj[ title ];
677 } else if ( title instanceof Title ) {
678 match = obj[ title.toString() ];
679 } else {
680 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
683 if ( typeof match !== 'boolean' ) {
684 return null;
687 return match;
691 * @typedef {Object} mw.Title~TitleExistenceStore
692 * @property {Object} pages Keyed by title. Boolean true value indicates page does exist.
694 * @property {Function} set The setter function. Returns a boolean.
696 * Example to declare existing titles:
697 * ```
698 * Title.exist.set( ['User:John_Doe', ...] );
699 * ```
701 * Example to declare titles nonexistent:
702 * ```
703 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
704 * ```
706 * @property {string|string[]} set.titles Title(s) in strict prefixedDb title form
707 * @property {boolean} [set.state=true] State of the given titles
711 * @name mw.Title.exist
712 * @type {mw.Title~TitleExistenceStore}
714 Title.exist = {
715 pages: {},
717 set: function ( titles, state ) {
718 const pages = this.pages;
720 titles = Array.isArray( titles ) ? titles : [ titles ];
721 state = state === undefined ? true : !!state;
723 for ( let i = 0, len = titles.length; i < len; i++ ) {
724 pages[ titles[ i ] ] = state;
726 return true;
731 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
732 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
733 * Keep in sync with File::normalizeExtension() in PHP.
735 * @name mw.Title.normalizeExtension
736 * @method
737 * @param {string} extension File extension (without the leading dot)
738 * @return {string} File extension in canonical form
740 Title.normalizeExtension = function ( extension ) {
741 const
742 lower = extension.toLowerCase(),
743 normalizations = {
744 htm: 'html',
745 jpeg: 'jpg',
746 mpeg: 'mpg',
747 tiff: 'tif',
748 ogv: 'ogg'
750 if ( Object.hasOwnProperty.call( normalizations, lower ) ) {
751 return normalizations[ lower ];
752 } else if ( /^[\da-z]+$/.test( lower ) ) {
753 return lower;
754 } else {
755 return '';
760 * PHP's strtoupper differs from String.toUpperCase in a number of cases (T147646).
762 * @name mw.Title.phpCharToUpper
763 * @method
764 * @param {string} chr Unicode character
765 * @return {string} Unicode character, in upper case, according to the same rules as in PHP
767 Title.phpCharToUpper = function ( chr ) {
768 if ( !toUpperMap ) {
769 toUpperMap = require( './phpCharToUpper.json' );
771 if ( toUpperMap[ chr ] === 0 ) {
772 // Optimisation: When the override is to keep the character unchanged,
773 // we use 0 in JSON. This reduces the data by 50%.
774 return chr;
776 return toUpperMap[ chr ] || chr.toUpperCase();
779 /* Public members */
780 Title.prototype = /** @lends mw.Title.prototype */ {
781 constructor: Title,
784 * Get the namespace number.
786 * Example: 6 for "File:Example_image.svg".
788 * @return {number}
790 getNamespaceId: function () {
791 return this.namespace;
795 * Get the namespace prefix (in the content language).
797 * Example: "File:" for "File:Example_image.svg".
798 * In `NS_MAIN` this is '', otherwise namespace name plus ':'
800 * @return {string}
802 getNamespacePrefix: function () {
803 return getNamespacePrefix( this.namespace );
807 * Get the page name as if it is a file name, without extension or namespace prefix,
808 * in the canonical form with underscores instead of spaces. For example, the title
809 * `File:Example_image.svg` will be returned as `Example_image`.
811 * Note that this method will work for non-file titles but probably give nonsensical results.
812 * A title like `User:Dr._J._Fail` will be returned as `Dr._J`! Use [getMain]{@link mw.Title#getMain} instead.
814 * @return {string}
816 getFileNameWithoutExtension: function () {
817 const ext = this.getExtension();
818 if ( ext === null ) {
819 return this.getMain();
821 return this.getMain().slice( 0, -ext.length - 1 );
825 * Get the page name as if it is a file name, without extension or namespace prefix,
826 * in the human-readable form with spaces instead of underscores. For example, the title
827 * `File:Example_image.svg` will be returned as "Example image".
829 * Note that this method will work for non-file titles but probably give nonsensical results.
830 * A title like `User:Dr._J._Fail` will be returned as `Dr. J`! Use [getMainText]{@link mw.Title#getMainText} instead.
832 * @return {string}
834 getFileNameTextWithoutExtension: function () {
835 return text( this.getFileNameWithoutExtension() );
839 * Get the page name as if it is a file name, without extension or namespace prefix. Warning,
840 * this is usually not what you want! A title like `User:Dr._J._Fail` will be returned as
841 * `Dr. J`! Use [getMain]{@link mw.Title#getMain} or [getMainText]{@link mw.Title#getMainText} for the actual page name.
843 * @return {string} File name without file extension, in the canonical form with underscores
844 * instead of spaces. For example, the title `File:Example_image.svg` will be returned as
845 * `Example_image`.
846 * @deprecated since 1.40, use [getFileNameWithoutExtension]{@link mw.Title#getFileNameWithoutExtension} instead
848 getName: function () {
849 return this.getFileNameWithoutExtension();
853 * Get the page name as if it is a file name, without extension or namespace prefix. Warning,
854 * this is usually not what you want! A title like `User:Dr._J._Fail` will be returned as
855 * `Dr. J`! Use [getMainText]{@link mw.Title#getMainText} for the actual page name.
857 * @return {string} File name without file extension, formatted with spaces instead of
858 * underscores. For example, the title `File:Example_image.svg` will be returned as
859 * `Example image`.
860 * @deprecated since 1.40, use [getFileNameTextWithoutExtension]{@link mw.Title#getFileNameTextWithoutExtension} instead
862 getNameText: function () {
863 return text( this.getFileNameTextWithoutExtension() );
867 * Get the extension of the page name (if any).
869 * @return {string|null} Name extension or null if there is none
871 getExtension: function () {
872 const lastDot = this.title.lastIndexOf( '.' );
873 if ( lastDot === -1 ) {
874 return null;
876 return this.title.slice( lastDot + 1 ) || null;
880 * Get the main page name.
882 * Example: `Example_image.svg` for `File:Example_image.svg`.
884 * @return {string}
886 getMain: function () {
887 if (
888 mw.config.get( 'wgCaseSensitiveNamespaces' ).indexOf( this.namespace ) !== -1 ||
889 !this.title.length
891 return this.title;
893 const firstChar = mwString.charAt( this.title, 0 );
894 return mw.Title.phpCharToUpper( firstChar ) + this.title.slice( firstChar.length );
898 * Get the main page name (transformed by text()).
900 * Example: `Example image.svg` for `File:Example_image.svg`.
902 * @return {string}
904 getMainText: function () {
905 return text( this.getMain() );
909 * Get the full page name.
911 * Example: `File:Example_image.svg`.
912 * Most useful for API calls, anything that must identify the "title".
914 * @return {string}
916 getPrefixedDb: function () {
917 return this.getNamespacePrefix() + this.getMain();
921 * Get the full page name (transformed by [text]{@link mw.Title#text}).
923 * Example: `File:Example image.svg` for `File:Example_image.svg`.
925 * @return {string}
927 getPrefixedText: function () {
928 return text( this.getPrefixedDb() );
932 * Get the page name relative to a namespace.
934 * Example:
936 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
937 * - "Bar" relative to any non-main namespace becomes ":Bar".
938 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
940 * @param {number} namespace The namespace to be relative to
941 * @return {string}
943 getRelativeText: function ( namespace ) {
944 if ( this.getNamespaceId() === namespace ) {
945 return this.getMainText();
946 } else if ( this.getNamespaceId() === NS_MAIN ) {
947 return ':' + this.getPrefixedText();
948 } else {
949 return this.getPrefixedText();
954 * Get the fragment (if any).
956 * Note that this method (by design) does not include the hash character and
957 * the value is not url encoded.
959 * @return {string|null}
961 getFragment: function () {
962 return this.fragment;
966 * Get the URL to this title.
968 * @see [mw.util.getUrl]{@link module:mediawiki.util.getUrl}
969 * @param {Object} [params] A mapping of query parameter names to values,
970 * e.g. `{ action: 'edit' }`.
971 * @return {string}
973 getUrl: function ( params ) {
974 const fragment = this.getFragment();
975 if ( fragment ) {
976 return mw.util.getUrl( this.toString() + '#' + fragment, params );
977 } else {
978 return mw.util.getUrl( this.toString(), params );
983 * Check if the title is in a talk namespace.
985 * @return {boolean} The title is in a talk namespace
987 isTalkPage: function () {
988 return Title.isTalkNamespace( this.getNamespaceId() );
992 * Get the title for the associated talk page.
994 * @return {mw.Title|null} The title for the associated talk page, null if not available
996 getTalkPage: function () {
997 if ( !this.canHaveTalkPage() ) {
998 return null;
1000 return this.isTalkPage() ?
1001 this :
1002 Title.makeTitle( this.getNamespaceId() + 1, this.getMainText() );
1006 * Get the title for the subject page of a talk page.
1008 * @return {mw.Title|null} The title for the subject page of a talk page, null if not available
1010 getSubjectPage: function () {
1011 return this.isTalkPage() ?
1012 Title.makeTitle( this.getNamespaceId() - 1, this.getMainText() ) :
1013 this;
1017 * Check the title can have an associated talk page.
1019 * @return {boolean} The title can have an associated talk page
1021 canHaveTalkPage: function () {
1022 return this.getNamespaceId() >= NS_MAIN;
1026 * Whether this title exists on the wiki.
1028 * @see mw.Title.exists
1029 * @return {boolean|null} Boolean if the information is available, otherwise null
1031 exists: function () {
1032 return Title.exists( this );
1037 * Alias of [getPrefixedDb]{@link mw.Title#getPrefixedDb}.
1039 * @name mw.Title.prototype.toString
1040 * @method
1042 Title.prototype.toString = Title.prototype.getPrefixedDb;
1045 * Alias of [getPrefixedText]{@link mw.Title#getPrefixedText}.
1047 * @name mw.Title.prototype.toText
1048 * @method
1050 Title.prototype.toText = Title.prototype.getPrefixedText;
1052 // Expose
1053 mw.Title = Title;