851f06c2d11db7e96c852a04ba8ddea1a89db22d
2 * @author Neil Kandalgaonkar, 2010
9 * Parse titles into an object structure. Note that when using the constructor
10 * directly, passing invalid titles will result in an exception. Use #newFromText to use the
11 * logic directly and get null for invalid titles which is easier to work with.
13 * Note that in the constructor and #newFromText method, `namespace` is the **default** namespace
14 * only, and can be overridden by a namespace prefix in `title`. If you do not want this behavior,
15 * use #makeTitle. Compare:
17 * new mw.Title( 'Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
18 * mw.Title.newFromText( 'Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
19 * mw.Title.makeTitle( NS_TEMPLATE, 'Foo' ).getPrefixedText(); // => 'Template:Foo'
21 * new mw.Title( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
22 * mw.Title.newFromText( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
23 * mw.Title.makeTitle( NS_TEMPLATE, 'Category:Foo' ).getPrefixedText(); // => 'Template:Category:Foo'
25 * new mw.Title( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
26 * mw.Title.newFromText( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
27 * mw.Title.makeTitle( NS_TEMPLATE, 'Template:Foo' ).getPrefixedText(); // => 'Template:Template:Foo'
35 namespaceIds
= mw
.config
.get( 'wgNamespaceIds' ),
42 NS_MAIN
= namespaceIds
[ '' ],
49 NS_TALK
= namespaceIds
.talk
,
54 * @property NS_SPECIAL
56 NS_SPECIAL
= namespaceIds
.special
,
63 NS_MEDIA
= namespaceIds
.media
,
70 NS_FILE
= namespaceIds
.file
,
75 * @property FILENAME_MAX_BYTES
77 FILENAME_MAX_BYTES
= 240,
82 * @property TITLE_MAX_BYTES
84 TITLE_MAX_BYTES
= 255,
87 * Get the namespace id from a namespace name (either from the localized, canonical or alias
90 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
95 * @method getNsIdByName
96 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
97 * @return {number|boolean} Namespace id or boolean false
99 getNsIdByName = function ( ns
) {
102 // Don't cast non-strings to strings, because null or undefined should not result in
103 // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
104 // Also, toLowerCase throws exception on null/undefined, because it is a String method.
105 if ( typeof ns
!== 'string' ) {
108 // TODO: Should just use local var namespaceIds here but it
109 // breaks test which modify the config
110 id
= mw
.config
.get( 'wgNamespaceIds' )[ ns
.toLowerCase() ];
111 if ( id
=== undefined ) {
119 * @method getNamespacePrefix_
120 * @param {number} namespace
123 getNamespacePrefix = function ( namespace ) {
124 return namespace === NS_MAIN
?
126 ( mw
.config
.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g
, '_' ) + ':' );
129 rUnderscoreTrim
= /^_+|_+$/g,
131 rSplit
= /^(.+?)_*:_*(.*)$/,
133 // See MediaWikiTitleCodec.php#getTitleInvalidRegex
134 rInvalid
= new RegExp(
135 '[^' + mw
.config
.get( 'wgLegalTitleChars' ) + ']' +
136 // URL percent encoding sequences interfere with the ability
137 // to round-trip titles -- you can't link to them consistently.
139 // XML/HTML character references produce similar issues.
140 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
145 // From MediaWikiTitleCodec::splitTitleString() in PHP
146 // Note that this is not equivalent to /\s/, e.g. underscore is included, tab is not included.
147 rWhitespace
= /[ _\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/g,
149 // From MediaWikiTitleCodec::splitTitleString() in PHP
150 rUnicodeBidi
= /[\u200E\u200F\u202A-\u202E]/g,
153 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
156 * @property sanitationRules
165 // control characters
167 // eslint-disable-next-line no-control-regex
168 pattern
: /[\x00-\x1f\x7f]/g,
172 // URL encoding (possibly)
174 pattern
: /%([0-9A-Fa-f]{2})/g,
178 // HTML-character-entities
180 pattern
: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
184 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
186 pattern
: new RegExp( '[' + mw
.config
.get( 'wgIllegalFileChars', '' ) + ']', 'g' ),
190 // brackets, greater than
196 // brackets, lower than
202 // everything that wasn't covered yet
204 pattern
: new RegExp( rInvalid
.source
, 'g' ),
208 // directory structures
210 pattern
: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
217 * Internal helper for #constructor and #newFromText.
219 * Based on Title.php#secureAndSplit
224 * @param {string} title
225 * @param {number} [defaultNamespace=NS_MAIN]
226 * @return {Object|boolean}
228 parse = function ( title
, defaultNamespace
) {
229 var namespace, m
, id
, i
, fragment
, ext
;
231 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
234 // Strip Unicode bidi override characters
235 .replace( rUnicodeBidi
, '' )
236 // Normalise whitespace to underscores and remove duplicates
237 .replace( rWhitespace
, '_' )
239 .replace( rUnderscoreTrim
, '' );
241 // Process initial colon
242 if ( title
!== '' && title
[ 0 ] === ':' ) {
243 // Initial colon means main namespace instead of specified default
249 .replace( rUnderscoreTrim
, '' );
252 if ( title
=== '' ) {
256 // Process namespace prefix (if any)
257 m
= title
.match( rSplit
);
259 id
= getNsIdByName( m
[ 1 ] );
260 if ( id
!== false ) {
261 // Ordinary namespace
265 // For Talk:X pages, make sure X has no "namespace" prefix
266 if ( namespace === NS_TALK
&& ( m
= title
.match( rSplit
) ) ) {
267 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
268 if ( getNsIdByName( m
[ 1 ] ) !== false ) {
276 i
= title
.indexOf( '#' );
281 // Get segment starting after the hash
284 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
285 .replace( /_
/g
, ' ' );
290 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
291 .replace( rUnderscoreTrim
, '' );
294 // Reject illegal characters
295 if ( title
.match( rInvalid
) ) {
299 // Disallow titles that browsers or servers might resolve as directory navigation
301 title
.indexOf( '.' ) !== -1 && (
302 title
=== '.' || title
=== '..' ||
303 title
.indexOf( './' ) === 0 ||
304 title
.indexOf( '../' ) === 0 ||
305 title
.indexOf( '/./' ) !== -1 ||
306 title
.indexOf( '/../' ) !== -1 ||
307 title
.slice( -2 ) === '/.' ||
308 title
.slice( -3 ) === '/..'
314 // Disallow magic tilde sequence
315 if ( title
.indexOf( '~~~' ) !== -1 ) {
319 // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
320 // Except for special pages, e.g. [[Special:Block/Long name]]
321 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
322 // be less than 512 bytes.
323 if ( namespace !== NS_SPECIAL
&& $.byteLength( title
) > TITLE_MAX_BYTES
) {
327 // Can't make a link to a namespace alone.
328 if ( title
=== '' && namespace !== NS_MAIN
) {
332 // Any remaining initial :s are illegal.
333 if ( title
[ 0 ] === ':' ) {
337 // For backwards-compatibility with old mw.Title, we separate the extension from the
338 // rest of the title.
339 i
= title
.lastIndexOf( '.' );
340 if ( i
=== -1 || title
.length
<= i
+ 1 ) {
341 // Extensions are the non-empty segment after the last dot
344 ext
= title
.slice( i
+ 1 );
345 title
= title
.slice( 0, i
);
349 namespace: namespace,
357 * Convert db-key to readable text.
365 text = function ( s
) {
366 if ( s
!== null && s
!== undefined ) {
367 return s
.replace( /_
/g
, ' ' );
374 * Sanitizes a string based on a rule set and a filter
380 * @param {Array} filter
383 sanitize = function ( s
, filter
) {
384 var i
, ruleLength
, rule
, m
, filterLength
,
385 rules
= sanitationRules
;
387 for ( i
= 0, ruleLength
= rules
.length
; i
< ruleLength
; ++i
) {
389 for ( m
= 0, filterLength
= filter
.length
; m
< filterLength
; ++m
) {
390 if ( rule
[ filter
[ m
] ] ) {
391 s
= s
.replace( rule
.pattern
, rule
.replace
);
399 * Cuts a string to a specific byte length, assuming UTF-8
400 * or less, if the last character is a multi-byte one
404 * @method trimToByteLength
406 * @param {number} length
409 trimToByteLength = function ( s
, length
) {
410 var byteLength
, chopOffChars
, chopOffBytes
;
412 // bytelength is always greater or equal to the length in characters
413 s
= s
.substr( 0, length
);
414 while ( ( byteLength
= $.byteLength( s
) ) > length
) {
415 // Calculate how many characters can be safely removed
416 // First, we need to know how many bytes the string exceeds the threshold
417 chopOffBytes
= byteLength
- length
;
418 // A character in UTF-8 is at most 4 bytes
419 // One character must be removed in any case because the
420 // string is too long
421 chopOffChars
= Math
.max( 1, Math
.floor( chopOffBytes
/ 4 ) );
422 s
= s
.substr( 0, s
.length
- chopOffChars
);
428 * Cuts a file name to a specific byte length
432 * @method trimFileNameToByteLength
433 * @param {string} name without extension
434 * @param {string} extension file extension
435 * @return {string} The full name, including extension
437 trimFileNameToByteLength = function ( name
, extension
) {
438 // There is a special byte limit for file names and ... remember the dot
439 return trimToByteLength( name
, FILENAME_MAX_BYTES
- extension
.length
- 1 ) + '.' + extension
;
443 * @method constructor
444 * @param {string} title Title of the page. If no second argument given,
445 * this will be searched for a namespace
446 * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
447 * @throws {Error} When the title is invalid
449 function Title( title
, namespace ) {
450 var parsed
= parse( title
, namespace );
452 throw new Error( 'Unable to parse title' );
455 this.namespace = parsed
.namespace;
456 this.title
= parsed
.title
;
457 this.ext
= parsed
.ext
;
458 this.fragment
= parsed
.fragment
;
464 * Constructor for Title objects with a null return instead of an exception for invalid titles.
466 * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
467 * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
471 * @param {string} title
472 * @param {number} [namespace=NS_MAIN] Default namespace
473 * @return {mw.Title|null} A valid Title object or null if the title is invalid
475 Title
.newFromText = function ( title
, namespace ) {
476 var t
, parsed
= parse( title
, namespace );
481 t
= Object
.create( Title
.prototype );
482 t
.namespace = parsed
.namespace;
483 t
.title
= parsed
.title
;
485 t
.fragment
= parsed
.fragment
;
491 * Constructor for Title objects with predefined namespace.
493 * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
494 * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
496 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
497 * function behaves like #newFromText in that case.
500 * @param {number} namespace Namespace to use for the title
501 * @param {string} title
502 * @return {mw.Title|null} A valid Title object or null if the title is invalid
504 Title
.makeTitle = function ( namespace, title
) {
505 return mw
.Title
.newFromText( getNamespacePrefix( namespace ) + title
);
509 * Constructor for Title objects from user input altering that input to
510 * produce a title that MediaWiki will accept as legal
513 * @param {string} title
514 * @param {number} [defaultNamespace=NS_MAIN]
515 * If given, will used as default namespace for the given title.
516 * @param {Object} [options] additional options
517 * @param {boolean} [options.forUploading=true]
518 * Makes sure that a file is uploadable under the title returned.
519 * There are pages in the file namespace under which file upload is impossible.
520 * Automatically assumed if the title is created in the Media namespace.
521 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
523 Title
.newFromUserInput = function ( title
, defaultNamespace
, options
) {
524 var namespace, m
, id
, ext
, parts
;
526 // defaultNamespace is optional; check whether options moves up
527 if ( arguments
.length
< 3 && $.type( defaultNamespace
) === 'object' ) {
528 options
= defaultNamespace
;
529 defaultNamespace
= undefined;
532 // merge options into defaults
533 options
= $.extend( {
537 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
539 // Normalise additional whitespace
540 title
= title
.replace( /\s/g, ' ' ).trim();
542 // Process initial colon
543 if ( title
!== '' && title
[ 0 ] === ':' ) {
544 // Initial colon means main namespace instead of specified default
550 .replace( rUnderscoreTrim
, '' );
553 // Process namespace prefix (if any)
554 m
= title
.match( rSplit
);
556 id
= getNsIdByName( m
[ 1 ] );
557 if ( id
!== false ) {
558 // Ordinary namespace
565 namespace === NS_MEDIA
||
566 ( options
.forUploading
&& ( namespace === NS_FILE
) )
569 title
= sanitize( title
, [ 'generalRule', 'fileRule' ] );
571 // Operate on the file extension
572 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
573 // operating systems hiding file extensions -> strip them later on
574 parts
= title
.split( '.' );
576 if ( parts
.length
> 1 ) {
578 // Get the last part, which is supposed to be the file extension
581 // Remove whitespace of the name part (that W/O extension)
582 title
= parts
.join( '.' ).trim();
584 // Cut, if too long and append file extension
585 title
= trimFileNameToByteLength( title
, ext
);
589 // Missing file extension
590 title
= parts
.join( '.' ).trim();
592 // Name has no file extension and a fallback wasn't provided either
597 title
= sanitize( title
, [ 'generalRule' ] );
599 // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
600 // (size of underlying database field)
601 if ( namespace !== NS_SPECIAL
) {
602 title
= trimToByteLength( title
, TITLE_MAX_BYTES
);
606 // Any remaining initial :s are illegal.
607 title
= title
.replace( /^:+/, '' );
609 return Title
.newFromText( title
, namespace );
613 * Sanitizes a file name as supplied by the user, originating in the user's file system
614 * so it is most likely a valid MediaWiki title and file name after processing.
615 * Returns null on fatal errors.
618 * @param {string} uncleanName The unclean file name including file extension but
620 * @return {mw.Title|null} A valid Title object or null if the title is invalid
622 Title
.newFromFileName = function ( uncleanName
) {
624 return Title
.newFromUserInput( 'File:' + uncleanName
, {
630 * Get the file title from an image element
632 * var title = mw.Title.newFromImg( $( 'img:first' ) );
635 * @param {HTMLElement|jQuery} img The image to use as a base
636 * @return {mw.Title|null} The file title or null if unsuccessful
638 Title
.newFromImg = function ( img
) {
639 var matches
, i
, regex
, src
, decodedSrc
,
641 // thumb.php-generated thumbnails
642 thumbPhpRegex
= /thumb\.php/,
645 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)\/[^\s/]+-[^\s
/]*$/,
648 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)$/,
650 // Thumbnails in non-hashed upload directories
651 /\/([^\s/]+)\/[^\s/]+-(?:\1|thumbnail
)[^\s
/]*$/,
653 // Full-size images in non-hashed upload directories
657 recount
= regexes
.length
;
659 src
= img
.jquery
? img
[ 0 ].src
: img
.src
;
661 matches
= src
.match( thumbPhpRegex
);
664 return mw
.Title
.newFromText( 'File:' + mw
.util
.getParamValue( 'f', src
) );
667 decodedSrc
= decodeURIComponent( src
);
669 for ( i
= 0; i
< recount
; i
++ ) {
670 regex
= regexes
[ i
];
671 matches
= decodedSrc
.match( regex
);
673 if ( matches
&& matches
[ 1 ] ) {
674 return mw
.Title
.newFromText( 'File:' + matches
[ 1 ] );
682 * Whether this title exists on the wiki.
685 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
686 * @return {boolean|null} Boolean if the information is available, otherwise null
688 Title
.exists = function ( title
) {
690 obj
= Title
.exist
.pages
;
692 if ( typeof title
=== 'string' ) {
693 match
= obj
[ title
];
694 } else if ( title
instanceof Title
) {
695 match
= obj
[ title
.toString() ];
697 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
700 if ( typeof match
!== 'boolean' ) {
708 * Store page existence
711 * @property {Object} exist
712 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
714 * @property {Function} exist.set The setter function.
716 * Example to declare existing titles:
718 * Title.exist.set( ['User:John_Doe', ...] );
720 * Example to declare titles nonexistent:
722 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
724 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
725 * @property {boolean} [exist.set.state=true] State of the given titles
731 set: function ( titles
, state
) {
735 titles
= Array
.isArray( titles
) ? titles
: [ titles
];
736 state
= state
=== undefined ? true : !!state
;
738 for ( i
= 0, len
= titles
.length
; i
< len
; i
++ ) {
739 pages
[ titles
[ i
] ] = state
;
746 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
747 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
748 * Keep in sync with File::normalizeExtension() in PHP.
750 * @param {string} extension File extension (without the leading dot)
751 * @return {string} File extension in canonical form
753 Title
.normalizeExtension = function ( extension
) {
755 lower
= extension
.toLowerCase(),
763 if ( squish
.hasOwnProperty( lower
) ) {
764 return squish
[ lower
];
765 } else if ( /^[0-9a-z]+$/.test( lower
) ) {
778 * Get the namespace number
780 * Example: 6 for "File:Example_image.svg".
784 getNamespaceId: function () {
785 return this.namespace;
789 * Get the namespace prefix (in the content language)
791 * Example: "File:" for "File:Example_image.svg".
792 * In #NS_MAIN this is '', otherwise namespace name plus ':'
796 getNamespacePrefix: function () {
797 return getNamespacePrefix( this.namespace );
801 * Get the page name without extension or namespace prefix
803 * Example: "Example_image" for "File:Example_image.svg".
805 * For the page title (full page name without namespace prefix), see #getMain.
809 getName: function () {
811 $.inArray( this.namespace, mw
.config
.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ||
816 // PHP's strtoupper differs from String.toUpperCase in a number of cases
818 return mw
.Title
.phpCharToUpper( this.title
[ 0 ] ) + this.title
.slice( 1 );
822 * Get the page name (transformed by #text)
824 * Example: "Example image" for "File:Example_image.svg".
826 * For the page title (full page name without namespace prefix), see #getMainText.
830 getNameText: function () {
831 return text( this.getName() );
835 * Get the extension of the page name (if any)
837 * @return {string|null} Name extension or null if there is none
839 getExtension: function () {
844 * Shortcut for appendable string to form the main page name.
846 * Returns a string like ".json", or "" if no extension.
850 getDotExtension: function () {
851 return this.ext
=== null ? '' : '.' + this.ext
;
855 * Get the main page name
857 * Example: "Example_image.svg" for "File:Example_image.svg".
861 getMain: function () {
862 return this.getName() + this.getDotExtension();
866 * Get the main page name (transformed by #text)
868 * Example: "Example image.svg" for "File:Example_image.svg".
872 getMainText: function () {
873 return text( this.getMain() );
877 * Get the full page name
879 * Example: "File:Example_image.svg".
880 * Most useful for API calls, anything that must identify the "title".
884 getPrefixedDb: function () {
885 return this.getNamespacePrefix() + this.getMain();
889 * Get the full page name (transformed by #text)
891 * Example: "File:Example image.svg" for "File:Example_image.svg".
895 getPrefixedText: function () {
896 return text( this.getPrefixedDb() );
900 * Get the page name relative to a namespace
904 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
905 * - "Bar" relative to any non-main namespace becomes ":Bar".
906 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
908 * @param {number} namespace The namespace to be relative to
911 getRelativeText: function ( namespace ) {
912 if ( this.getNamespaceId() === namespace ) {
913 return this.getMainText();
914 } else if ( this.getNamespaceId() === NS_MAIN
) {
915 return ':' + this.getPrefixedText();
917 return this.getPrefixedText();
922 * Get the fragment (if any).
924 * Note that this method (by design) does not include the hash character and
925 * the value is not url encoded.
927 * @return {string|null}
929 getFragment: function () {
930 return this.fragment
;
934 * Get the URL to this title
936 * @see mw.util#getUrl
937 * @param {Object} [params] A mapping of query parameter names to values,
938 * e.g. `{ action: 'edit' }`.
941 getUrl: function ( params
) {
942 var fragment
= this.getFragment();
944 return mw
.util
.getUrl( this.toString() + '#' + fragment
, params
);
946 return mw
.util
.getUrl( this.toString(), params
);
951 * Whether this title exists on the wiki.
953 * @see #static-method-exists
954 * @return {boolean|null} Boolean if the information is available, otherwise null
956 exists: function () {
957 return Title
.exists( this );
962 * @alias #getPrefixedDb
965 Title
.prototype.toString
= Title
.prototype.getPrefixedDb
;
968 * @alias #getPrefixedText
971 Title
.prototype.toText
= Title
.prototype.getPrefixedText
;
976 }( mediaWiki
, jQuery
) );