2 * @author Neil Kandalgaonkar, 2010
3 * @author Timo Tijhof, 2011-2013
7 /*jshint latedef:false */
10 * Parse titles into an object structure. Note that when using the constructor
11 * directly, passing invalid titles will result in an exception. Use #newFromText to use the
12 * logic directly and get null for invalid titles which is easier to work with.
17 * Note that in the constructor and #newFromText method, `namespace` is the **default** namespace
18 * only, and can be overridden by a namespace prefix in `title`. If you do not want this behavior,
19 * use #makeTitle. Compare:
21 * new mw.Title( 'Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
22 * mw.Title.newFromText( 'Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
23 * mw.Title.makeTitle( NS_TEMPLATE, 'Foo' ).getPrefixedText(); // => 'Template:Foo'
25 * new mw.Title( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
26 * mw.Title.newFromText( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
27 * mw.Title.makeTitle( NS_TEMPLATE, 'Category:Foo' ).getPrefixedText(); // => 'Template:Category:Foo'
29 * new mw.Title( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
30 * mw.Title.newFromText( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
31 * mw.Title.makeTitle( NS_TEMPLATE, 'Template:Foo' ).getPrefixedText(); // => 'Template:Template:Foo'
34 * @param {string} title Title of the page. If no second argument given,
35 * this will be searched for a namespace
36 * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
37 * @throws {Error} When the title is invalid
39 function Title( title
, namespace ) {
40 var parsed
= parse( title
, namespace );
42 throw new Error( 'Unable to parse title' );
45 this.namespace = parsed
.namespace;
46 this.title
= parsed
.title
;
47 this.ext
= parsed
.ext
;
48 this.fragment
= parsed
.fragment
;
57 namespaceIds
= mw
.config
.get( 'wgNamespaceIds' ),
64 NS_MAIN
= namespaceIds
[ '' ],
71 NS_TALK
= namespaceIds
.talk
,
76 * @property NS_SPECIAL
78 NS_SPECIAL
= namespaceIds
.special
,
85 NS_MEDIA
= namespaceIds
.media
,
92 NS_FILE
= namespaceIds
.file
,
97 * @property FILENAME_MAX_BYTES
99 FILENAME_MAX_BYTES
= 240,
104 * @property TITLE_MAX_BYTES
106 TITLE_MAX_BYTES
= 255,
109 * Get the namespace id from a namespace name (either from the localized, canonical or alias
112 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
117 * @method getNsIdByName
118 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
119 * @return {number|boolean} Namespace id or boolean false
121 getNsIdByName = function ( ns
) {
124 // Don't cast non-strings to strings, because null or undefined should not result in
125 // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
126 // Also, toLowerCase throws exception on null/undefined, because it is a String method.
127 if ( typeof ns
!== 'string' ) {
130 // TODO: Should just use local var namespaceIds here but it
131 // breaks test which modify the config
132 id
= mw
.config
.get( 'wgNamespaceIds' )[ ns
.toLowerCase() ];
133 if ( id
=== undefined ) {
141 * @method getNamespacePrefix_
142 * @param {number} namespace
145 getNamespacePrefix = function ( namespace ) {
146 return namespace === NS_MAIN
?
148 ( mw
.config
.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g
, '_' ) + ':' );
151 rUnderscoreTrim
= /^_+|_+$/g,
153 rSplit
= /^(.+?)_*:_*(.*)$/,
155 // See MediaWikiTitleCodec.php#getTitleInvalidRegex
156 rInvalid
= new RegExp(
157 '[^' + mw
.config
.get( 'wgLegalTitleChars' ) + ']' +
158 // URL percent encoding sequences interfere with the ability
159 // to round-trip titles -- you can't link to them consistently.
161 // XML/HTML character references produce similar issues.
162 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
167 // From MediaWikiTitleCodec.php#L225 @26fcab1f18c568a41
168 // "Clean up whitespace" in function MediaWikiTitleCodec::splitTitleString()
169 rWhitespace
= /[ _\u0009\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\s]+/g,
172 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
175 * @property sanitationRules
184 // Space, underscore, tab, NBSP and other unusual spaces
186 pattern
: rWhitespace
,
190 // unicode bidi override characters: Implicit, Embeds, Overrides
192 pattern
: /[\u200E\u200F\u202A-\u202E]/g,
196 // control characters
198 pattern
: /[\x00-\x1f\x7f]/g,
202 // URL encoding (possibly)
204 pattern
: /%([0-9A-Fa-f]{2})/g,
208 // HTML-character-entities
210 pattern
: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
214 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
216 pattern
: new RegExp( '[' + mw
.config
.get( 'wgIllegalFileChars', '' ) + ']', 'g' ),
220 // brackets, greater than
226 // brackets, lower than
232 // everything that wasn't covered yet
234 pattern
: new RegExp( rInvalid
.source
, 'g' ),
238 // directory structures
240 pattern
: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
247 * Internal helper for #constructor and #newFromText.
249 * Based on Title.php#secureAndSplit
254 * @param {string} title
255 * @param {number} [defaultNamespace=NS_MAIN]
256 * @return {Object|boolean}
258 parse = function ( title
, defaultNamespace
) {
259 var namespace, m
, id
, i
, fragment
, ext
;
261 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
264 // Normalise whitespace to underscores and remove duplicates
265 .replace( /[ _\s]+/g, '_' )
267 .replace( rUnderscoreTrim
, '' );
269 // Process initial colon
270 if ( title
!== '' && title
[ 0 ] === ':' ) {
271 // Initial colon means main namespace instead of specified default
277 .replace( rUnderscoreTrim
, '' );
280 if ( title
=== '' ) {
284 // Process namespace prefix (if any)
285 m
= title
.match( rSplit
);
287 id
= getNsIdByName( m
[ 1 ] );
288 if ( id
!== false ) {
289 // Ordinary namespace
293 // For Talk:X pages, make sure X has no "namespace" prefix
294 if ( namespace === NS_TALK
&& ( m
= title
.match( rSplit
) ) ) {
295 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
296 if ( getNsIdByName( m
[ 1 ] ) !== false ) {
304 i
= title
.indexOf( '#' );
309 // Get segment starting after the hash
312 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
313 .replace( /_
/g
, ' ' );
318 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
319 .replace( rUnderscoreTrim
, '' );
322 // Reject illegal characters
323 if ( title
.match( rInvalid
) ) {
327 // Disallow titles that browsers or servers might resolve as directory navigation
329 title
.indexOf( '.' ) !== -1 && (
330 title
=== '.' || title
=== '..' ||
331 title
.indexOf( './' ) === 0 ||
332 title
.indexOf( '../' ) === 0 ||
333 title
.indexOf( '/./' ) !== -1 ||
334 title
.indexOf( '/../' ) !== -1 ||
335 title
.slice( -2 ) === '/.' ||
336 title
.slice( -3 ) === '/..'
342 // Disallow magic tilde sequence
343 if ( title
.indexOf( '~~~' ) !== -1 ) {
347 // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
348 // Except for special pages, e.g. [[Special:Block/Long name]]
349 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
350 // be less than 512 bytes.
351 if ( namespace !== NS_SPECIAL
&& $.byteLength( title
) > TITLE_MAX_BYTES
) {
355 // Can't make a link to a namespace alone.
356 if ( title
=== '' && namespace !== NS_MAIN
) {
360 // Any remaining initial :s are illegal.
361 if ( title
[ 0 ] === ':' ) {
365 // For backwards-compatibility with old mw.Title, we separate the extension from the
366 // rest of the title.
367 i
= title
.lastIndexOf( '.' );
368 if ( i
=== -1 || title
.length
<= i
+ 1 ) {
369 // Extensions are the non-empty segment after the last dot
372 ext
= title
.slice( i
+ 1 );
373 title
= title
.slice( 0, i
);
377 namespace: namespace,
385 * Convert db-key to readable text.
393 text = function ( s
) {
394 if ( s
!== null && s
!== undefined ) {
395 return s
.replace( /_
/g
, ' ' );
402 * Sanitizes a string based on a rule set and a filter
408 * @param {Array} filter
411 sanitize = function ( s
, filter
) {
412 var i
, ruleLength
, rule
, m
, filterLength
,
413 rules
= sanitationRules
;
415 for ( i
= 0, ruleLength
= rules
.length
; i
< ruleLength
; ++i
) {
417 for ( m
= 0, filterLength
= filter
.length
; m
< filterLength
; ++m
) {
418 if ( rule
[ filter
[ m
] ] ) {
419 s
= s
.replace( rule
.pattern
, rule
.replace
);
427 * Cuts a string to a specific byte length, assuming UTF-8
428 * or less, if the last character is a multi-byte one
432 * @method trimToByteLength
434 * @param {number} length
437 trimToByteLength = function ( s
, length
) {
438 var byteLength
, chopOffChars
, chopOffBytes
;
440 // bytelength is always greater or equal to the length in characters
441 s
= s
.substr( 0, length
);
442 while ( ( byteLength
= $.byteLength( s
) ) > length
) {
443 // Calculate how many characters can be safely removed
444 // First, we need to know how many bytes the string exceeds the threshold
445 chopOffBytes
= byteLength
- length
;
446 // A character in UTF-8 is at most 4 bytes
447 // One character must be removed in any case because the
448 // string is too long
449 chopOffChars
= Math
.max( 1, Math
.floor( chopOffBytes
/ 4 ) );
450 s
= s
.substr( 0, s
.length
- chopOffChars
);
456 * Cuts a file name to a specific byte length
460 * @method trimFileNameToByteLength
461 * @param {string} name without extension
462 * @param {string} extension file extension
463 * @return {string} The full name, including extension
465 trimFileNameToByteLength = function ( name
, extension
) {
466 // There is a special byte limit for file names and ... remember the dot
467 return trimToByteLength( name
, FILENAME_MAX_BYTES
- extension
.length
- 1 ) + '.' + extension
;
470 // Polyfill for ES5 Object.create
471 createObject
= Object
.create
|| ( function () {
472 return function ( o
) {
474 if ( o
!== Object( o
) ) {
475 throw new Error( 'Cannot inherit from a non-object' );
485 * Constructor for Title objects with a null return instead of an exception for invalid titles.
487 * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
488 * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
492 * @param {string} title
493 * @param {number} [namespace=NS_MAIN] Default namespace
494 * @return {mw.Title|null} A valid Title object or null if the title is invalid
496 Title
.newFromText = function ( title
, namespace ) {
497 var t
, parsed
= parse( title
, namespace );
502 t
= createObject( Title
.prototype );
503 t
.namespace = parsed
.namespace;
504 t
.title
= parsed
.title
;
506 t
.fragment
= parsed
.fragment
;
512 * Constructor for Title objects with predefined namespace.
514 * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
515 * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
517 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
518 * function behaves like #newFromText in that case.
521 * @param {number} namespace Namespace to use for the title
522 * @param {string} title
523 * @return {mw.Title|null} A valid Title object or null if the title is invalid
525 Title
.makeTitle = function ( namespace, title
) {
526 return mw
.Title
.newFromText( getNamespacePrefix( namespace ) + title
);
530 * Constructor for Title objects from user input altering that input to
531 * produce a title that MediaWiki will accept as legal
534 * @param {string} title
535 * @param {number} [defaultNamespace=NS_MAIN]
536 * If given, will used as default namespace for the given title.
537 * @param {Object} [options] additional options
538 * @param {boolean} [options.forUploading=true]
539 * Makes sure that a file is uploadable under the title returned.
540 * There are pages in the file namespace under which file upload is impossible.
541 * Automatically assumed if the title is created in the Media namespace.
542 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
544 Title
.newFromUserInput = function ( title
, defaultNamespace
, options
) {
545 var namespace, m
, id
, ext
, parts
;
547 // defaultNamespace is optional; check whether options moves up
548 if ( arguments
.length
< 3 && $.type( defaultNamespace
) === 'object' ) {
549 options
= defaultNamespace
;
550 defaultNamespace
= undefined;
553 // merge options into defaults
554 options
= $.extend( {
558 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
560 // Normalise whitespace and remove duplicates
561 title
= $.trim( title
.replace( rWhitespace
, ' ' ) );
563 // Process initial colon
564 if ( title
!== '' && title
[ 0 ] === ':' ) {
565 // Initial colon means main namespace instead of specified default
571 .replace( rUnderscoreTrim
, '' );
574 // Process namespace prefix (if any)
575 m
= title
.match( rSplit
);
577 id
= getNsIdByName( m
[ 1 ] );
578 if ( id
!== false ) {
579 // Ordinary namespace
585 if ( namespace === NS_MEDIA
586 || ( options
.forUploading
&& ( namespace === NS_FILE
) )
589 title
= sanitize( title
, [ 'generalRule', 'fileRule' ] );
591 // Operate on the file extension
592 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
593 // operating systems hiding file extensions -> strip them later on
594 parts
= title
.split( '.' );
596 if ( parts
.length
> 1 ) {
598 // Get the last part, which is supposed to be the file extension
601 // Remove whitespace of the name part (that W/O extension)
602 title
= $.trim( parts
.join( '.' ) );
604 // Cut, if too long and append file extension
605 title
= trimFileNameToByteLength( title
, ext
);
609 // Missing file extension
610 title
= $.trim( parts
.join( '.' ) );
612 // Name has no file extension and a fallback wasn't provided either
617 title
= sanitize( title
, [ 'generalRule' ] );
619 // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
620 // (size of underlying database field)
621 if ( namespace !== NS_SPECIAL
) {
622 title
= trimToByteLength( title
, TITLE_MAX_BYTES
);
626 // Any remaining initial :s are illegal.
627 title
= title
.replace( /^\:+/, '' );
629 return Title
.newFromText( title
, namespace );
633 * Sanitizes a file name as supplied by the user, originating in the user's file system
634 * so it is most likely a valid MediaWiki title and file name after processing.
635 * Returns null on fatal errors.
638 * @param {string} uncleanName The unclean file name including file extension but
640 * @return {mw.Title|null} A valid Title object or null if the title is invalid
642 Title
.newFromFileName = function ( uncleanName
) {
644 return Title
.newFromUserInput( 'File:' + uncleanName
, {
650 * Get the file title from an image element
652 * var title = mw.Title.newFromImg( $( 'img:first' ) );
655 * @param {HTMLElement|jQuery} img The image to use as a base
656 * @return {mw.Title|null} The file title or null if unsuccessful
658 Title
.newFromImg = function ( img
) {
659 var matches
, i
, regex
, src
, decodedSrc
,
661 // thumb.php-generated thumbnails
662 thumbPhpRegex
= /thumb\.php/,
665 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[^\s\/]+-[^\s\/]*$/,
668 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
670 // Thumbnails in non-hashed upload directories
671 /\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
673 // Full-size images in non-hashed upload directories
677 recount
= regexes
.length
;
679 src
= img
.jquery
? img
[ 0 ].src
: img
.src
;
681 matches
= src
.match( thumbPhpRegex
);
684 return mw
.Title
.newFromText( 'File:' + mw
.util
.getParamValue( 'f', src
) );
687 decodedSrc
= decodeURIComponent( src
);
689 for ( i
= 0; i
< recount
; i
++ ) {
690 regex
= regexes
[ i
];
691 matches
= decodedSrc
.match( regex
);
693 if ( matches
&& matches
[ 1 ] ) {
694 return mw
.Title
.newFromText( 'File:' + matches
[ 1 ] );
702 * Whether this title exists on the wiki.
705 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
706 * @return {boolean|null} Boolean if the information is available, otherwise null
708 Title
.exists = function ( title
) {
710 type
= $.type( title
),
711 obj
= Title
.exist
.pages
;
713 if ( type
=== 'string' ) {
714 match
= obj
[ title
];
715 } else if ( type
=== 'object' && title
instanceof Title
) {
716 match
= obj
[ title
.toString() ];
718 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
721 if ( typeof match
=== 'boolean' ) {
729 * Store page existence
732 * @property {Object} exist
733 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
735 * @property {Function} exist.set The setter function.
737 * Example to declare existing titles:
739 * Title.exist.set( ['User:John_Doe', ...] );
741 * Example to declare titles nonexistent:
743 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
745 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
746 * @property {boolean} [exist.set.state=true] State of the given titles
752 set: function ( titles
, state
) {
753 titles
= $.isArray( titles
) ? titles
: [ titles
];
754 state
= state
=== undefined ? true : !!state
;
759 for ( i
= 0; i
< len
; i
++ ) {
760 pages
[ titles
[ i
] ] = state
;
767 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
768 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
769 * Keep in sync with File::normalizeExtension() in PHP.
771 * @param {string} extension File extension (without the leading dot)
772 * @return {string} File extension in canonical form
774 Title
.normalizeExtension = function ( extension
) {
776 lower
= extension
.toLowerCase(),
784 if ( squish
.hasOwnProperty( lower
) ) {
785 return squish
[ lower
];
786 } else if ( /^[0-9a-z]+$/.test( lower
) ) {
799 * Get the namespace number
801 * Example: 6 for "File:Example_image.svg".
805 getNamespaceId: function () {
806 return this.namespace;
810 * Get the namespace prefix (in the content language)
812 * Example: "File:" for "File:Example_image.svg".
813 * In #NS_MAIN this is '', otherwise namespace name plus ':'
817 getNamespacePrefix: function () {
818 return getNamespacePrefix( this.namespace );
822 * Get the page name without extension or namespace prefix
824 * Example: "Example_image" for "File:Example_image.svg".
826 * For the page title (full page name without namespace prefix), see #getMain.
830 getName: function () {
832 $.inArray( this.namespace, mw
.config
.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ||
837 return this.title
[ 0 ].toUpperCase() + this.title
.slice( 1 );
841 * Get the page name (transformed by #text)
843 * Example: "Example image" for "File:Example_image.svg".
845 * For the page title (full page name without namespace prefix), see #getMainText.
849 getNameText: function () {
850 return text( this.getName() );
854 * Get the extension of the page name (if any)
856 * @return {string|null} Name extension or null if there is none
858 getExtension: function () {
863 * Shortcut for appendable string to form the main page name.
865 * Returns a string like ".json", or "" if no extension.
869 getDotExtension: function () {
870 return this.ext
=== null ? '' : '.' + this.ext
;
874 * Get the main page name
876 * Example: "Example_image.svg" for "File:Example_image.svg".
880 getMain: function () {
881 return this.getName() + this.getDotExtension();
885 * Get the main page name (transformed by #text)
887 * Example: "Example image.svg" for "File:Example_image.svg".
891 getMainText: function () {
892 return text( this.getMain() );
896 * Get the full page name
898 * Example: "File:Example_image.svg".
899 * Most useful for API calls, anything that must identify the "title".
903 getPrefixedDb: function () {
904 return this.getNamespacePrefix() + this.getMain();
908 * Get the full page name (transformed by #text)
910 * Example: "File:Example image.svg" for "File:Example_image.svg".
914 getPrefixedText: function () {
915 return text( this.getPrefixedDb() );
919 * Get the page name relative to a namespace
923 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
924 * - "Bar" relative to any non-main namespace becomes ":Bar".
925 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
927 * @param {number} namespace The namespace to be relative to
930 getRelativeText: function ( namespace ) {
931 if ( this.getNamespaceId() === namespace ) {
932 return this.getMainText();
933 } else if ( this.getNamespaceId() === NS_MAIN
) {
934 return ':' + this.getPrefixedText();
936 return this.getPrefixedText();
941 * Get the fragment (if any).
943 * Note that this method (by design) does not include the hash character and
944 * the value is not url encoded.
946 * @return {string|null}
948 getFragment: function () {
949 return this.fragment
;
953 * Get the URL to this title
955 * @see mw.util#getUrl
956 * @param {Object} [params] A mapping of query parameter names to values,
957 * e.g. `{ action: 'edit' }`.
960 getUrl: function ( params
) {
961 var fragment
= this.getFragment();
963 return mw
.util
.getUrl( this.toString() + '#' + fragment
, params
);
965 return mw
.util
.getUrl( this.toString(), params
);
970 * Whether this title exists on the wiki.
972 * @see #static-method-exists
973 * @return {boolean|null} Boolean if the information is available, otherwise null
975 exists: function () {
976 return Title
.exists( this );
981 * @alias #getPrefixedDb
984 Title
.prototype.toString
= Title
.prototype.getPrefixedDb
;
987 * @alias #getPrefixedText
990 Title
.prototype.toText
= Title
.prototype.getPrefixedText
;
995 }( mediaWiki
, jQuery
) );