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::splitTitleString() in PHP
168 // Note that this is not equivalent to /\s/, e.g. underscore is included, tab is not included.
169 rWhitespace
= /[ _\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/g,
171 // From MediaWikiTitleCodec::splitTitleString() in PHP
172 rUnicodeBidi
= /[\u200E\u200F\u202A-\u202E]/g,
175 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
178 * @property sanitationRules
187 // control characters
189 pattern
: /[\x00-\x1f\x7f]/g,
193 // URL encoding (possibly)
195 pattern
: /%([0-9A-Fa-f]{2})/g,
199 // HTML-character-entities
201 pattern
: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
205 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
207 pattern
: new RegExp( '[' + mw
.config
.get( 'wgIllegalFileChars', '' ) + ']', 'g' ),
211 // brackets, greater than
217 // brackets, lower than
223 // everything that wasn't covered yet
225 pattern
: new RegExp( rInvalid
.source
, 'g' ),
229 // directory structures
231 pattern
: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
238 * Internal helper for #constructor and #newFromText.
240 * Based on Title.php#secureAndSplit
245 * @param {string} title
246 * @param {number} [defaultNamespace=NS_MAIN]
247 * @return {Object|boolean}
249 parse = function ( title
, defaultNamespace
) {
250 var namespace, m
, id
, i
, fragment
, ext
;
252 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
255 // Strip Unicode bidi override characters
256 .replace( rUnicodeBidi
, '' )
257 // Normalise whitespace to underscores and remove duplicates
258 .replace( rWhitespace
, '_' )
260 .replace( rUnderscoreTrim
, '' );
262 // Process initial colon
263 if ( title
!== '' && title
[ 0 ] === ':' ) {
264 // Initial colon means main namespace instead of specified default
270 .replace( rUnderscoreTrim
, '' );
273 if ( title
=== '' ) {
277 // Process namespace prefix (if any)
278 m
= title
.match( rSplit
);
280 id
= getNsIdByName( m
[ 1 ] );
281 if ( id
!== false ) {
282 // Ordinary namespace
286 // For Talk:X pages, make sure X has no "namespace" prefix
287 if ( namespace === NS_TALK
&& ( m
= title
.match( rSplit
) ) ) {
288 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
289 if ( getNsIdByName( m
[ 1 ] ) !== false ) {
297 i
= title
.indexOf( '#' );
302 // Get segment starting after the hash
305 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
306 .replace( /_
/g
, ' ' );
311 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
312 .replace( rUnderscoreTrim
, '' );
315 // Reject illegal characters
316 if ( title
.match( rInvalid
) ) {
320 // Disallow titles that browsers or servers might resolve as directory navigation
322 title
.indexOf( '.' ) !== -1 && (
323 title
=== '.' || title
=== '..' ||
324 title
.indexOf( './' ) === 0 ||
325 title
.indexOf( '../' ) === 0 ||
326 title
.indexOf( '/./' ) !== -1 ||
327 title
.indexOf( '/../' ) !== -1 ||
328 title
.slice( -2 ) === '/.' ||
329 title
.slice( -3 ) === '/..'
335 // Disallow magic tilde sequence
336 if ( title
.indexOf( '~~~' ) !== -1 ) {
340 // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
341 // Except for special pages, e.g. [[Special:Block/Long name]]
342 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
343 // be less than 512 bytes.
344 if ( namespace !== NS_SPECIAL
&& $.byteLength( title
) > TITLE_MAX_BYTES
) {
348 // Can't make a link to a namespace alone.
349 if ( title
=== '' && namespace !== NS_MAIN
) {
353 // Any remaining initial :s are illegal.
354 if ( title
[ 0 ] === ':' ) {
358 // For backwards-compatibility with old mw.Title, we separate the extension from the
359 // rest of the title.
360 i
= title
.lastIndexOf( '.' );
361 if ( i
=== -1 || title
.length
<= i
+ 1 ) {
362 // Extensions are the non-empty segment after the last dot
365 ext
= title
.slice( i
+ 1 );
366 title
= title
.slice( 0, i
);
370 namespace: namespace,
378 * Convert db-key to readable text.
386 text = function ( s
) {
387 if ( s
!== null && s
!== undefined ) {
388 return s
.replace( /_
/g
, ' ' );
395 * Sanitizes a string based on a rule set and a filter
401 * @param {Array} filter
404 sanitize = function ( s
, filter
) {
405 var i
, ruleLength
, rule
, m
, filterLength
,
406 rules
= sanitationRules
;
408 for ( i
= 0, ruleLength
= rules
.length
; i
< ruleLength
; ++i
) {
410 for ( m
= 0, filterLength
= filter
.length
; m
< filterLength
; ++m
) {
411 if ( rule
[ filter
[ m
] ] ) {
412 s
= s
.replace( rule
.pattern
, rule
.replace
);
420 * Cuts a string to a specific byte length, assuming UTF-8
421 * or less, if the last character is a multi-byte one
425 * @method trimToByteLength
427 * @param {number} length
430 trimToByteLength = function ( s
, length
) {
431 var byteLength
, chopOffChars
, chopOffBytes
;
433 // bytelength is always greater or equal to the length in characters
434 s
= s
.substr( 0, length
);
435 while ( ( byteLength
= $.byteLength( s
) ) > length
) {
436 // Calculate how many characters can be safely removed
437 // First, we need to know how many bytes the string exceeds the threshold
438 chopOffBytes
= byteLength
- length
;
439 // A character in UTF-8 is at most 4 bytes
440 // One character must be removed in any case because the
441 // string is too long
442 chopOffChars
= Math
.max( 1, Math
.floor( chopOffBytes
/ 4 ) );
443 s
= s
.substr( 0, s
.length
- chopOffChars
);
449 * Cuts a file name to a specific byte length
453 * @method trimFileNameToByteLength
454 * @param {string} name without extension
455 * @param {string} extension file extension
456 * @return {string} The full name, including extension
458 trimFileNameToByteLength = function ( name
, extension
) {
459 // There is a special byte limit for file names and ... remember the dot
460 return trimToByteLength( name
, FILENAME_MAX_BYTES
- extension
.length
- 1 ) + '.' + extension
;
463 // Polyfill for ES5 Object.create
464 createObject
= Object
.create
|| ( function () {
465 return function ( o
) {
467 if ( o
!== Object( o
) ) {
468 throw new Error( 'Cannot inherit from a non-object' );
478 * Constructor for Title objects with a null return instead of an exception for invalid titles.
480 * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
481 * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
485 * @param {string} title
486 * @param {number} [namespace=NS_MAIN] Default namespace
487 * @return {mw.Title|null} A valid Title object or null if the title is invalid
489 Title
.newFromText = function ( title
, namespace ) {
490 var t
, parsed
= parse( title
, namespace );
495 t
= createObject( Title
.prototype );
496 t
.namespace = parsed
.namespace;
497 t
.title
= parsed
.title
;
499 t
.fragment
= parsed
.fragment
;
505 * Constructor for Title objects with predefined namespace.
507 * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
508 * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
510 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
511 * function behaves like #newFromText in that case.
514 * @param {number} namespace Namespace to use for the title
515 * @param {string} title
516 * @return {mw.Title|null} A valid Title object or null if the title is invalid
518 Title
.makeTitle = function ( namespace, title
) {
519 return mw
.Title
.newFromText( getNamespacePrefix( namespace ) + title
);
523 * Constructor for Title objects from user input altering that input to
524 * produce a title that MediaWiki will accept as legal
527 * @param {string} title
528 * @param {number} [defaultNamespace=NS_MAIN]
529 * If given, will used as default namespace for the given title.
530 * @param {Object} [options] additional options
531 * @param {boolean} [options.forUploading=true]
532 * Makes sure that a file is uploadable under the title returned.
533 * There are pages in the file namespace under which file upload is impossible.
534 * Automatically assumed if the title is created in the Media namespace.
535 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
537 Title
.newFromUserInput = function ( title
, defaultNamespace
, options
) {
538 var namespace, m
, id
, ext
, parts
;
540 // defaultNamespace is optional; check whether options moves up
541 if ( arguments
.length
< 3 && $.type( defaultNamespace
) === 'object' ) {
542 options
= defaultNamespace
;
543 defaultNamespace
= undefined;
546 // merge options into defaults
547 options
= $.extend( {
551 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
553 // Normalise additional whitespace
554 title
= $.trim( title
.replace( /\s/g, ' ' ) );
556 // Process initial colon
557 if ( title
!== '' && title
[ 0 ] === ':' ) {
558 // Initial colon means main namespace instead of specified default
564 .replace( rUnderscoreTrim
, '' );
567 // Process namespace prefix (if any)
568 m
= title
.match( rSplit
);
570 id
= getNsIdByName( m
[ 1 ] );
571 if ( id
!== false ) {
572 // Ordinary namespace
578 if ( namespace === NS_MEDIA
579 || ( options
.forUploading
&& ( namespace === NS_FILE
) )
582 title
= sanitize( title
, [ 'generalRule', 'fileRule' ] );
584 // Operate on the file extension
585 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
586 // operating systems hiding file extensions -> strip them later on
587 parts
= title
.split( '.' );
589 if ( parts
.length
> 1 ) {
591 // Get the last part, which is supposed to be the file extension
594 // Remove whitespace of the name part (that W/O extension)
595 title
= $.trim( parts
.join( '.' ) );
597 // Cut, if too long and append file extension
598 title
= trimFileNameToByteLength( title
, ext
);
602 // Missing file extension
603 title
= $.trim( parts
.join( '.' ) );
605 // Name has no file extension and a fallback wasn't provided either
610 title
= sanitize( title
, [ 'generalRule' ] );
612 // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
613 // (size of underlying database field)
614 if ( namespace !== NS_SPECIAL
) {
615 title
= trimToByteLength( title
, TITLE_MAX_BYTES
);
619 // Any remaining initial :s are illegal.
620 title
= title
.replace( /^\:+/, '' );
622 return Title
.newFromText( title
, namespace );
626 * Sanitizes a file name as supplied by the user, originating in the user's file system
627 * so it is most likely a valid MediaWiki title and file name after processing.
628 * Returns null on fatal errors.
631 * @param {string} uncleanName The unclean file name including file extension but
633 * @return {mw.Title|null} A valid Title object or null if the title is invalid
635 Title
.newFromFileName = function ( uncleanName
) {
637 return Title
.newFromUserInput( 'File:' + uncleanName
, {
643 * Get the file title from an image element
645 * var title = mw.Title.newFromImg( $( 'img:first' ) );
648 * @param {HTMLElement|jQuery} img The image to use as a base
649 * @return {mw.Title|null} The file title or null if unsuccessful
651 Title
.newFromImg = function ( img
) {
652 var matches
, i
, regex
, src
, decodedSrc
,
654 // thumb.php-generated thumbnails
655 thumbPhpRegex
= /thumb\.php/,
658 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[^\s\/]+-[^\s\/]*$/,
661 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
663 // Thumbnails in non-hashed upload directories
664 /\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
666 // Full-size images in non-hashed upload directories
670 recount
= regexes
.length
;
672 src
= img
.jquery
? img
[ 0 ].src
: img
.src
;
674 matches
= src
.match( thumbPhpRegex
);
677 return mw
.Title
.newFromText( 'File:' + mw
.util
.getParamValue( 'f', src
) );
680 decodedSrc
= decodeURIComponent( src
);
682 for ( i
= 0; i
< recount
; i
++ ) {
683 regex
= regexes
[ i
];
684 matches
= decodedSrc
.match( regex
);
686 if ( matches
&& matches
[ 1 ] ) {
687 return mw
.Title
.newFromText( 'File:' + matches
[ 1 ] );
695 * Whether this title exists on the wiki.
698 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
699 * @return {boolean|null} Boolean if the information is available, otherwise null
701 Title
.exists = function ( title
) {
703 type
= $.type( title
),
704 obj
= Title
.exist
.pages
;
706 if ( type
=== 'string' ) {
707 match
= obj
[ title
];
708 } else if ( type
=== 'object' && title
instanceof Title
) {
709 match
= obj
[ title
.toString() ];
711 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
714 if ( typeof match
=== 'boolean' ) {
722 * Store page existence
725 * @property {Object} exist
726 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
728 * @property {Function} exist.set The setter function.
730 * Example to declare existing titles:
732 * Title.exist.set( ['User:John_Doe', ...] );
734 * Example to declare titles nonexistent:
736 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
738 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
739 * @property {boolean} [exist.set.state=true] State of the given titles
745 set: function ( titles
, state
) {
746 titles
= $.isArray( titles
) ? titles
: [ titles
];
747 state
= state
=== undefined ? true : !!state
;
752 for ( i
= 0; i
< len
; i
++ ) {
753 pages
[ titles
[ i
] ] = state
;
760 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
761 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
762 * Keep in sync with File::normalizeExtension() in PHP.
764 * @param {string} extension File extension (without the leading dot)
765 * @return {string} File extension in canonical form
767 Title
.normalizeExtension = function ( extension
) {
769 lower
= extension
.toLowerCase(),
777 if ( squish
.hasOwnProperty( lower
) ) {
778 return squish
[ lower
];
779 } else if ( /^[0-9a-z]+$/.test( lower
) ) {
792 * Get the namespace number
794 * Example: 6 for "File:Example_image.svg".
798 getNamespaceId: function () {
799 return this.namespace;
803 * Get the namespace prefix (in the content language)
805 * Example: "File:" for "File:Example_image.svg".
806 * In #NS_MAIN this is '', otherwise namespace name plus ':'
810 getNamespacePrefix: function () {
811 return getNamespacePrefix( this.namespace );
815 * Get the page name without extension or namespace prefix
817 * Example: "Example_image" for "File:Example_image.svg".
819 * For the page title (full page name without namespace prefix), see #getMain.
823 getName: function () {
825 $.inArray( this.namespace, mw
.config
.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ||
830 return this.title
[ 0 ].toUpperCase() + this.title
.slice( 1 );
834 * Get the page name (transformed by #text)
836 * Example: "Example image" for "File:Example_image.svg".
838 * For the page title (full page name without namespace prefix), see #getMainText.
842 getNameText: function () {
843 return text( this.getName() );
847 * Get the extension of the page name (if any)
849 * @return {string|null} Name extension or null if there is none
851 getExtension: function () {
856 * Shortcut for appendable string to form the main page name.
858 * Returns a string like ".json", or "" if no extension.
862 getDotExtension: function () {
863 return this.ext
=== null ? '' : '.' + this.ext
;
867 * Get the main page name
869 * Example: "Example_image.svg" for "File:Example_image.svg".
873 getMain: function () {
874 return this.getName() + this.getDotExtension();
878 * Get the main page name (transformed by #text)
880 * Example: "Example image.svg" for "File:Example_image.svg".
884 getMainText: function () {
885 return text( this.getMain() );
889 * Get the full page name
891 * Example: "File:Example_image.svg".
892 * Most useful for API calls, anything that must identify the "title".
896 getPrefixedDb: function () {
897 return this.getNamespacePrefix() + this.getMain();
901 * Get the full page name (transformed by #text)
903 * Example: "File:Example image.svg" for "File:Example_image.svg".
907 getPrefixedText: function () {
908 return text( this.getPrefixedDb() );
912 * Get the page name relative to a namespace
916 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
917 * - "Bar" relative to any non-main namespace becomes ":Bar".
918 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
920 * @param {number} namespace The namespace to be relative to
923 getRelativeText: function ( namespace ) {
924 if ( this.getNamespaceId() === namespace ) {
925 return this.getMainText();
926 } else if ( this.getNamespaceId() === NS_MAIN
) {
927 return ':' + this.getPrefixedText();
929 return this.getPrefixedText();
934 * Get the fragment (if any).
936 * Note that this method (by design) does not include the hash character and
937 * the value is not url encoded.
939 * @return {string|null}
941 getFragment: function () {
942 return this.fragment
;
946 * Get the URL to this title
948 * @see mw.util#getUrl
949 * @param {Object} [params] A mapping of query parameter names to values,
950 * e.g. `{ action: 'edit' }`.
953 getUrl: function ( params
) {
954 var fragment
= this.getFragment();
956 return mw
.util
.getUrl( this.toString() + '#' + fragment
, params
);
958 return mw
.util
.getUrl( this.toString(), params
);
963 * Whether this title exists on the wiki.
965 * @see #static-method-exists
966 * @return {boolean|null} Boolean if the information is available, otherwise null
968 exists: function () {
969 return Title
.exists( this );
974 * @alias #getPrefixedDb
977 Title
.prototype.toString
= Title
.prototype.getPrefixedDb
;
980 * @alias #getPrefixedText
983 Title
.prototype.toText
= Title
.prototype.getPrefixedText
;
988 }( mediaWiki
, jQuery
) );