2b76187359e5ab44d04780d74ec95c3dc8a20494
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 mwString
= require( 'mediawiki.String' ),
37 namespaceIds
= mw
.config
.get( 'wgNamespaceIds' ),
44 NS_MAIN
= namespaceIds
[ '' ],
51 NS_TALK
= namespaceIds
.talk
,
56 * @property NS_SPECIAL
58 NS_SPECIAL
= namespaceIds
.special
,
65 NS_MEDIA
= namespaceIds
.media
,
72 NS_FILE
= namespaceIds
.file
,
77 * @property FILENAME_MAX_BYTES
79 FILENAME_MAX_BYTES
= 240,
84 * @property TITLE_MAX_BYTES
86 TITLE_MAX_BYTES
= 255,
89 * Get the namespace id from a namespace name (either from the localized, canonical or alias
92 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
97 * @method getNsIdByName
98 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
99 * @return {number|boolean} Namespace id or boolean false
101 getNsIdByName = function ( ns
) {
104 // Don't cast non-strings to strings, because null or undefined should not result in
105 // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
106 // Also, toLowerCase throws exception on null/undefined, because it is a String method.
107 if ( typeof ns
!== 'string' ) {
110 // TODO: Should just use local var namespaceIds here but it
111 // breaks test which modify the config
112 id
= mw
.config
.get( 'wgNamespaceIds' )[ ns
.toLowerCase() ];
113 if ( id
=== undefined ) {
121 * @method getNamespacePrefix_
122 * @param {number} namespace
125 getNamespacePrefix = function ( namespace ) {
126 return namespace === NS_MAIN
?
128 ( mw
.config
.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g
, '_' ) + ':' );
131 rUnderscoreTrim
= /^_+|_+$/g,
133 rSplit
= /^(.+?)_*:_*(.*)$/,
135 // See MediaWikiTitleCodec.php#getTitleInvalidRegex
136 rInvalid
= new RegExp(
137 '[^' + mw
.config
.get( 'wgLegalTitleChars' ) + ']' +
138 // URL percent encoding sequences interfere with the ability
139 // to round-trip titles -- you can't link to them consistently.
141 // XML/HTML character references produce similar issues.
142 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
147 // From MediaWikiTitleCodec::splitTitleString() in PHP
148 // Note that this is not equivalent to /\s/, e.g. underscore is included, tab is not included.
149 rWhitespace
= /[ _\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/g,
151 // From MediaWikiTitleCodec::splitTitleString() in PHP
152 rUnicodeBidi
= /[\u200E\u200F\u202A-\u202E]/g,
155 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
158 * @property sanitationRules
167 // control characters
169 // eslint-disable-next-line no-control-regex
170 pattern
: /[\x00-\x1f\x7f]/g,
174 // URL encoding (possibly)
176 pattern
: /%([0-9A-Fa-f]{2})/g,
180 // HTML-character-entities
182 pattern
: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
186 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
188 pattern
: new RegExp( '[' + mw
.config
.get( 'wgIllegalFileChars', '' ) + ']', 'g' ),
192 // brackets, greater than
198 // brackets, lower than
204 // everything that wasn't covered yet
206 pattern
: new RegExp( rInvalid
.source
, 'g' ),
210 // directory structures
212 pattern
: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
219 * Internal helper for #constructor and #newFromText.
221 * Based on Title.php#secureAndSplit
226 * @param {string} title
227 * @param {number} [defaultNamespace=NS_MAIN]
228 * @return {Object|boolean}
230 parse = function ( title
, defaultNamespace
) {
231 var namespace, m
, id
, i
, fragment
, ext
;
233 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
236 // Strip Unicode bidi override characters
237 .replace( rUnicodeBidi
, '' )
238 // Normalise whitespace to underscores and remove duplicates
239 .replace( rWhitespace
, '_' )
241 .replace( rUnderscoreTrim
, '' );
243 // Process initial colon
244 if ( title
!== '' && title
[ 0 ] === ':' ) {
245 // Initial colon means main namespace instead of specified default
251 .replace( rUnderscoreTrim
, '' );
254 if ( title
=== '' ) {
258 // Process namespace prefix (if any)
259 m
= title
.match( rSplit
);
261 id
= getNsIdByName( m
[ 1 ] );
262 if ( id
!== false ) {
263 // Ordinary namespace
267 // For Talk:X pages, make sure X has no "namespace" prefix
268 if ( namespace === NS_TALK
&& ( m
= title
.match( rSplit
) ) ) {
269 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
270 if ( getNsIdByName( m
[ 1 ] ) !== false ) {
278 i
= title
.indexOf( '#' );
283 // Get segment starting after the hash
286 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
287 .replace( /_
/g
, ' ' );
292 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
293 .replace( rUnderscoreTrim
, '' );
296 // Reject illegal characters
297 if ( title
.match( rInvalid
) ) {
301 // Disallow titles that browsers or servers might resolve as directory navigation
303 title
.indexOf( '.' ) !== -1 && (
304 title
=== '.' || title
=== '..' ||
305 title
.indexOf( './' ) === 0 ||
306 title
.indexOf( '../' ) === 0 ||
307 title
.indexOf( '/./' ) !== -1 ||
308 title
.indexOf( '/../' ) !== -1 ||
309 title
.slice( -2 ) === '/.' ||
310 title
.slice( -3 ) === '/..'
316 // Disallow magic tilde sequence
317 if ( title
.indexOf( '~~~' ) !== -1 ) {
321 // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
322 // Except for special pages, e.g. [[Special:Block/Long name]]
323 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
324 // be less than 512 bytes.
325 if ( namespace !== NS_SPECIAL
&& mwString
.byteLength( title
) > TITLE_MAX_BYTES
) {
329 // Can't make a link to a namespace alone.
330 if ( title
=== '' && namespace !== NS_MAIN
) {
334 // Any remaining initial :s are illegal.
335 if ( title
[ 0 ] === ':' ) {
339 // For backwards-compatibility with old mw.Title, we separate the extension from the
340 // rest of the title.
341 i
= title
.lastIndexOf( '.' );
342 if ( i
=== -1 || title
.length
<= i
+ 1 ) {
343 // Extensions are the non-empty segment after the last dot
346 ext
= title
.slice( i
+ 1 );
347 title
= title
.slice( 0, i
);
351 namespace: namespace,
359 * Convert db-key to readable text.
367 text = function ( s
) {
368 if ( s
!== null && s
!== undefined ) {
369 return s
.replace( /_
/g
, ' ' );
376 * Sanitizes a string based on a rule set and a filter
382 * @param {Array} filter
385 sanitize = function ( s
, filter
) {
386 var i
, ruleLength
, rule
, m
, filterLength
,
387 rules
= sanitationRules
;
389 for ( i
= 0, ruleLength
= rules
.length
; i
< ruleLength
; ++i
) {
391 for ( m
= 0, filterLength
= filter
.length
; m
< filterLength
; ++m
) {
392 if ( rule
[ filter
[ m
] ] ) {
393 s
= s
.replace( rule
.pattern
, rule
.replace
);
401 * Cuts a string to a specific byte length, assuming UTF-8
402 * or less, if the last character is a multi-byte one
406 * @method trimToByteLength
408 * @param {number} length
411 trimToByteLength = function ( s
, length
) {
412 return mwString
.trimByteLength( '', s
, length
).newVal
;
416 * Cuts a file name to a specific byte length
420 * @method trimFileNameToByteLength
421 * @param {string} name without extension
422 * @param {string} extension file extension
423 * @return {string} The full name, including extension
425 trimFileNameToByteLength = function ( name
, extension
) {
426 // There is a special byte limit for file names and ... remember the dot
427 return trimToByteLength( name
, FILENAME_MAX_BYTES
- extension
.length
- 1 ) + '.' + extension
;
431 * @method constructor
432 * @param {string} title Title of the page. If no second argument given,
433 * this will be searched for a namespace
434 * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
435 * @throws {Error} When the title is invalid
437 function Title( title
, namespace ) {
438 var parsed
= parse( title
, namespace );
440 throw new Error( 'Unable to parse title' );
443 this.namespace = parsed
.namespace;
444 this.title
= parsed
.title
;
445 this.ext
= parsed
.ext
;
446 this.fragment
= parsed
.fragment
;
452 * Constructor for Title objects with a null return instead of an exception for invalid titles.
454 * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
455 * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
459 * @param {string} title
460 * @param {number} [namespace=NS_MAIN] Default namespace
461 * @return {mw.Title|null} A valid Title object or null if the title is invalid
463 Title
.newFromText = function ( title
, namespace ) {
464 var t
, parsed
= parse( title
, namespace );
469 t
= Object
.create( Title
.prototype );
470 t
.namespace = parsed
.namespace;
471 t
.title
= parsed
.title
;
473 t
.fragment
= parsed
.fragment
;
479 * Constructor for Title objects with predefined namespace.
481 * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
482 * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
484 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
485 * function behaves like #newFromText in that case.
488 * @param {number} namespace Namespace to use for the title
489 * @param {string} title
490 * @return {mw.Title|null} A valid Title object or null if the title is invalid
492 Title
.makeTitle = function ( namespace, title
) {
493 return mw
.Title
.newFromText( getNamespacePrefix( namespace ) + title
);
497 * Constructor for Title objects from user input altering that input to
498 * produce a title that MediaWiki will accept as legal
501 * @param {string} title
502 * @param {number} [defaultNamespace=NS_MAIN]
503 * If given, will used as default namespace for the given title.
504 * @param {Object} [options] additional options
505 * @param {boolean} [options.forUploading=true]
506 * Makes sure that a file is uploadable under the title returned.
507 * There are pages in the file namespace under which file upload is impossible.
508 * Automatically assumed if the title is created in the Media namespace.
509 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
511 Title
.newFromUserInput = function ( title
, defaultNamespace
, options
) {
512 var namespace, m
, id
, ext
, parts
;
514 // defaultNamespace is optional; check whether options moves up
515 if ( arguments
.length
< 3 && $.type( defaultNamespace
) === 'object' ) {
516 options
= defaultNamespace
;
517 defaultNamespace
= undefined;
520 // merge options into defaults
521 options
= $.extend( {
525 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
527 // Normalise additional whitespace
528 title
= title
.replace( /\s/g, ' ' ).trim();
530 // Process initial colon
531 if ( title
!== '' && title
[ 0 ] === ':' ) {
532 // Initial colon means main namespace instead of specified default
538 .replace( rUnderscoreTrim
, '' );
541 // Process namespace prefix (if any)
542 m
= title
.match( rSplit
);
544 id
= getNsIdByName( m
[ 1 ] );
545 if ( id
!== false ) {
546 // Ordinary namespace
553 namespace === NS_MEDIA
||
554 ( options
.forUploading
&& ( namespace === NS_FILE
) )
557 title
= sanitize( title
, [ 'generalRule', 'fileRule' ] );
559 // Operate on the file extension
560 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
561 // operating systems hiding file extensions -> strip them later on
562 parts
= title
.split( '.' );
564 if ( parts
.length
> 1 ) {
566 // Get the last part, which is supposed to be the file extension
569 // Remove whitespace of the name part (that W/O extension)
570 title
= parts
.join( '.' ).trim();
572 // Cut, if too long and append file extension
573 title
= trimFileNameToByteLength( title
, ext
);
577 // Missing file extension
578 title
= parts
.join( '.' ).trim();
580 // Name has no file extension and a fallback wasn't provided either
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.
606 * @param {string} uncleanName The unclean file name including file extension but
608 * @return {mw.Title|null} A valid Title object or null if the title is invalid
610 Title
.newFromFileName = function ( uncleanName
) {
612 return Title
.newFromUserInput( 'File:' + uncleanName
, {
618 * Get the file title from an image element
620 * var title = mw.Title.newFromImg( $( 'img:first' ) );
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 var matches
, i
, regex
, src
, decodedSrc
,
629 // thumb.php-generated thumbnails
630 thumbPhpRegex
= /thumb\.php/,
633 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)\/[^\s/]+-[^\s
/]*$/,
636 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)$/,
638 // Thumbnails in non-hashed upload directories
639 /\/([^\s/]+)\/[^\s/]+-(?:\1|thumbnail
)[^\s
/]*$/,
641 // Full-size images in non-hashed upload directories
645 recount
= regexes
.length
;
647 src
= img
.jquery
? img
[ 0 ].src
: img
.src
;
649 matches
= src
.match( thumbPhpRegex
);
652 return mw
.Title
.newFromText( 'File:' + mw
.util
.getParamValue( 'f', src
) );
655 decodedSrc
= decodeURIComponent( src
);
657 for ( i
= 0; i
< recount
; i
++ ) {
658 regex
= regexes
[ i
];
659 matches
= decodedSrc
.match( regex
);
661 if ( matches
&& matches
[ 1 ] ) {
662 return mw
.Title
.newFromText( 'File:' + matches
[ 1 ] );
670 * Whether this title exists on the wiki.
673 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
674 * @return {boolean|null} Boolean if the information is available, otherwise null
676 Title
.exists = function ( title
) {
678 obj
= Title
.exist
.pages
;
680 if ( typeof title
=== 'string' ) {
681 match
= obj
[ title
];
682 } else if ( title
instanceof Title
) {
683 match
= obj
[ title
.toString() ];
685 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
688 if ( typeof match
!== 'boolean' ) {
696 * Store page existence
699 * @property {Object} exist
700 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
702 * @property {Function} exist.set The setter function.
704 * Example to declare existing titles:
706 * Title.exist.set( ['User:John_Doe', ...] );
708 * Example to declare titles nonexistent:
710 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
712 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
713 * @property {boolean} [exist.set.state=true] State of the given titles
719 set: function ( titles
, state
) {
723 titles
= Array
.isArray( titles
) ? titles
: [ titles
];
724 state
= state
=== undefined ? true : !!state
;
726 for ( i
= 0, len
= titles
.length
; i
< len
; i
++ ) {
727 pages
[ titles
[ i
] ] = state
;
734 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
735 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
736 * Keep in sync with File::normalizeExtension() in PHP.
738 * @param {string} extension File extension (without the leading dot)
739 * @return {string} File extension in canonical form
741 Title
.normalizeExtension = function ( extension
) {
743 lower
= extension
.toLowerCase(),
751 if ( squish
.hasOwnProperty( lower
) ) {
752 return squish
[ lower
];
753 } else if ( /^[0-9a-z]+$/.test( lower
) ) {
766 * Get the namespace number
768 * Example: 6 for "File:Example_image.svg".
772 getNamespaceId: function () {
773 return this.namespace;
777 * Get the namespace prefix (in the content language)
779 * Example: "File:" for "File:Example_image.svg".
780 * In #NS_MAIN this is '', otherwise namespace name plus ':'
784 getNamespacePrefix: function () {
785 return getNamespacePrefix( this.namespace );
789 * Get the page name without extension or namespace prefix
791 * Example: "Example_image" for "File:Example_image.svg".
793 * For the page title (full page name without namespace prefix), see #getMain.
797 getName: function () {
799 $.inArray( this.namespace, mw
.config
.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ||
804 // PHP's strtoupper differs from String.toUpperCase in a number of cases
806 return mw
.Title
.phpCharToUpper( this.title
[ 0 ] ) + this.title
.slice( 1 );
810 * Get the page name (transformed by #text)
812 * Example: "Example image" for "File:Example_image.svg".
814 * For the page title (full page name without namespace prefix), see #getMainText.
818 getNameText: function () {
819 return text( this.getName() );
823 * Get the extension of the page name (if any)
825 * @return {string|null} Name extension or null if there is none
827 getExtension: function () {
832 * Shortcut for appendable string to form the main page name.
834 * Returns a string like ".json", or "" if no extension.
838 getDotExtension: function () {
839 return this.ext
=== null ? '' : '.' + this.ext
;
843 * Get the main page name
845 * Example: "Example_image.svg" for "File:Example_image.svg".
849 getMain: function () {
850 return this.getName() + this.getDotExtension();
854 * Get the main page name (transformed by #text)
856 * Example: "Example image.svg" for "File:Example_image.svg".
860 getMainText: function () {
861 return text( this.getMain() );
865 * Get the full page name
867 * Example: "File:Example_image.svg".
868 * Most useful for API calls, anything that must identify the "title".
872 getPrefixedDb: function () {
873 return this.getNamespacePrefix() + this.getMain();
877 * Get the full page name (transformed by #text)
879 * Example: "File:Example image.svg" for "File:Example_image.svg".
883 getPrefixedText: function () {
884 return text( this.getPrefixedDb() );
888 * Get the page name relative to a namespace
892 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
893 * - "Bar" relative to any non-main namespace becomes ":Bar".
894 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
896 * @param {number} namespace The namespace to be relative to
899 getRelativeText: function ( namespace ) {
900 if ( this.getNamespaceId() === namespace ) {
901 return this.getMainText();
902 } else if ( this.getNamespaceId() === NS_MAIN
) {
903 return ':' + this.getPrefixedText();
905 return this.getPrefixedText();
910 * Get the fragment (if any).
912 * Note that this method (by design) does not include the hash character and
913 * the value is not url encoded.
915 * @return {string|null}
917 getFragment: function () {
918 return this.fragment
;
922 * Get the URL to this title
924 * @see mw.util#getUrl
925 * @param {Object} [params] A mapping of query parameter names to values,
926 * e.g. `{ action: 'edit' }`.
929 getUrl: function ( params
) {
930 var fragment
= this.getFragment();
932 return mw
.util
.getUrl( this.toString() + '#' + fragment
, params
);
934 return mw
.util
.getUrl( this.toString(), params
);
939 * Whether this title exists on the wiki.
941 * @see #static-method-exists
942 * @return {boolean|null} Boolean if the information is available, otherwise null
944 exists: function () {
945 return Title
.exists( this );
950 * @alias #getPrefixedDb
953 Title
.prototype.toString
= Title
.prototype.getPrefixedDb
;
956 * @alias #getPrefixedText
959 Title
.prototype.toText
= Title
.prototype.getPrefixedText
;
964 }( mediaWiki
, jQuery
) );