2 * @author Neil Kandalgaonkar, 2010
3 * @author Timo Tijhof, 2011-2013
7 /*jshint latedef:false */
13 * Parse titles into an object structure. Note that when using the constructor
14 * directly, passing invalid titles will result in an exception. Use #newFromText to use the
15 * logic directly and get null for invalid titles which is easier to work with.
19 * Note that in the constructor amd #newFromText method, `namespace` is the **default** namespace
20 * only, and can be overridden by a namespace prefix in `title`. If you do not want this behavior,
21 * use #makeTitle. Compare:
23 * new mw.Title( 'Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
24 * mw.Title.newFromText( 'Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
25 * mw.Title.makeTitle( NS_TEMPLATE, 'Foo' ).getPrefixedText(); // => 'Template:Foo'
27 * new mw.Title( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
28 * mw.Title.newFromText( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
29 * mw.Title.makeTitle( NS_TEMPLATE, 'Category:Foo' ).getPrefixedText(); // => 'Template:Category:Foo'
31 * new mw.Title( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
32 * mw.Title.newFromText( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
33 * mw.Title.makeTitle( NS_TEMPLATE, 'Template:Foo' ).getPrefixedText(); // => 'Template:Template:Foo'
35 * @param {string} title Title of the page. If no second argument given,
36 * this will be searched for a namespace
37 * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
38 * @throws {Error} When the title is invalid
40 function Title( title
, namespace ) {
41 var parsed
= parse( title
, namespace );
43 throw new Error( 'Unable to parse title' );
46 this.namespace = parsed
.namespace;
47 this.title
= parsed
.title
;
48 this.ext
= parsed
.ext
;
49 this.fragment
= parsed
.fragment
;
76 * @property NS_SPECIAL
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 ns
= ns
.toLowerCase();
131 id
= mw
.config
.get( 'wgNamespaceIds' )[ ns
];
132 if ( id
=== undefined ) {
140 * @method getNamespacePrefix_
141 * @param {number} namespace
144 getNamespacePrefix = function ( namespace ) {
145 return namespace === NS_MAIN
?
147 ( mw
.config
.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g
, '_' ) + ':' );
150 rUnderscoreTrim
= /^_+|_+$/g,
152 rSplit
= /^(.+?)_*:_*(.*)$/,
154 // See MediaWikiTitleCodec.php#getTitleInvalidRegex
155 rInvalid
= new RegExp(
156 '[^' + mw
.config
.get( 'wgLegalTitleChars' ) + ']' +
157 // URL percent encoding sequences interfere with the ability
158 // to round-trip titles -- you can't link to them consistently.
160 // XML/HTML character references produce similar issues.
161 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
166 // From MediaWikiTitleCodec.php#L225 @26fcab1f18c568a41
167 // "Clean up whitespace" in function MediaWikiTitleCodec::splitTitleString()
168 rWhitespace
= /[ _\u0009\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\s]+/g,
171 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
174 * @property sanitationRules
183 // Space, underscore, tab, NBSP and other unusual spaces
185 pattern
: rWhitespace
,
189 // unicode bidi override characters: Implicit, Embeds, Overrides
191 pattern
: /[\u200E\u200F\u202A-\u202E]/g,
195 // control characters
197 pattern
: /[\x00-\x1f\x7f]/g,
201 // URL encoding (possibly)
203 pattern
: /%([0-9A-Fa-f]{2})/g,
207 // HTML-character-entities
209 pattern
: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
213 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
219 // brackets, greater than
225 // brackets, lower than
231 // everything that wasn't covered yet
233 pattern
: new RegExp( rInvalid
.source
, 'g' ),
237 // directory structures
239 pattern
: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
246 * Internal helper for #constructor and #newFromText.
248 * Based on Title.php#secureAndSplit
253 * @param {string} title
254 * @param {number} [defaultNamespace=NS_MAIN]
255 * @return {Object|boolean}
257 parse = function ( title
, defaultNamespace
) {
258 var namespace, m
, id
, i
, fragment
, ext
;
260 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
263 // Normalise whitespace to underscores and remove duplicates
264 .replace( /[ _\s]+/g, '_' )
266 .replace( rUnderscoreTrim
, '' );
268 // Process initial colon
269 if ( title
!== '' && title
[ 0 ] === ':' ) {
270 // Initial colon means main namespace instead of specified default
276 .replace( rUnderscoreTrim
, '' );
279 if ( title
=== '' ) {
283 // Process namespace prefix (if any)
284 m
= title
.match( rSplit
);
286 id
= getNsIdByName( m
[ 1 ] );
287 if ( id
!== false ) {
288 // Ordinary namespace
292 // For Talk:X pages, make sure X has no "namespace" prefix
293 if ( namespace === NS_TALK
&& ( m
= title
.match( rSplit
) ) ) {
294 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
295 if ( getNsIdByName( m
[ 1 ] ) !== false ) {
303 i
= title
.indexOf( '#' );
308 // Get segment starting after the hash
311 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
312 .replace( /_
/g
, ' ' );
317 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
318 .replace( rUnderscoreTrim
, '' );
321 // Reject illegal characters
322 if ( title
.match( rInvalid
) ) {
326 // Disallow titles that browsers or servers might resolve as directory navigation
328 title
.indexOf( '.' ) !== -1 && (
329 title
=== '.' || title
=== '..' ||
330 title
.indexOf( './' ) === 0 ||
331 title
.indexOf( '../' ) === 0 ||
332 title
.indexOf( '/./' ) !== -1 ||
333 title
.indexOf( '/../' ) !== -1 ||
334 title
.slice( -2 ) === '/.' ||
335 title
.slice( -3 ) === '/..'
341 // Disallow magic tilde sequence
342 if ( title
.indexOf( '~~~' ) !== -1 ) {
346 // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
347 // Except for special pages, e.g. [[Special:Block/Long name]]
348 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
349 // be less than 512 bytes.
350 if ( namespace !== NS_SPECIAL
&& $.byteLength( title
) > TITLE_MAX_BYTES
) {
354 // Can't make a link to a namespace alone.
355 if ( title
=== '' && namespace !== NS_MAIN
) {
359 // Any remaining initial :s are illegal.
360 if ( title
[ 0 ] === ':' ) {
364 // For backwards-compatibility with old mw.Title, we separate the extension from the
365 // rest of the title.
366 i
= title
.lastIndexOf( '.' );
367 if ( i
=== -1 || title
.length
<= i
+ 1 ) {
368 // Extensions are the non-empty segment after the last dot
371 ext
= title
.slice( i
+ 1 );
372 title
= title
.slice( 0, i
);
376 namespace: namespace,
384 * Convert db-key to readable text.
392 text = function ( s
) {
393 if ( s
!== null && s
!== undefined ) {
394 return s
.replace( /_
/g
, ' ' );
401 * Sanitizes a string based on a rule set and a filter
407 * @param {Array} filter
410 sanitize = function ( s
, filter
) {
411 var i
, ruleLength
, rule
, m
, filterLength
,
412 rules
= sanitationRules
;
414 for ( i
= 0, ruleLength
= rules
.length
; i
< ruleLength
; ++i
) {
416 for ( m
= 0, filterLength
= filter
.length
; m
< filterLength
; ++m
) {
417 if ( rule
[ filter
[ m
] ] ) {
418 s
= s
.replace( rule
.pattern
, rule
.replace
);
426 * Cuts a string to a specific byte length, assuming UTF-8
427 * or less, if the last character is a multi-byte one
431 * @method trimToByteLength
433 * @param {number} length
436 trimToByteLength = function ( s
, length
) {
437 var byteLength
, chopOffChars
, chopOffBytes
;
439 // bytelength is always greater or equal to the length in characters
440 s
= s
.substr( 0, length
);
441 while ( ( byteLength
= $.byteLength( s
) ) > length
) {
442 // Calculate how many characters can be safely removed
443 // First, we need to know how many bytes the string exceeds the threshold
444 chopOffBytes
= byteLength
- length
;
445 // A character in UTF-8 is at most 4 bytes
446 // One character must be removed in any case because the
447 // string is too long
448 chopOffChars
= Math
.max( 1, Math
.floor( chopOffBytes
/ 4 ) );
449 s
= s
.substr( 0, s
.length
- chopOffChars
);
455 * Cuts a file name to a specific byte length
459 * @method trimFileNameToByteLength
460 * @param {string} name without extension
461 * @param {string} extension file extension
462 * @return {string} The full name, including extension
464 trimFileNameToByteLength = function ( name
, extension
) {
465 // There is a special byte limit for file names and ... remember the dot
466 return trimToByteLength( name
, FILENAME_MAX_BYTES
- extension
.length
- 1 ) + '.' + extension
;
469 // Polyfill for ES5 Object.create
470 createObject
= Object
.create
|| ( function () {
471 return function ( o
) {
473 if ( o
!== Object( o
) ) {
474 throw new Error( 'Cannot inherit from a non-object' );
484 * Constructor for Title objects with a null return instead of an exception for invalid titles.
486 * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
487 * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
491 * @param {string} title
492 * @param {number} [namespace=NS_MAIN] Default namespace
493 * @return {mw.Title|null} A valid Title object or null if the title is invalid
495 Title
.newFromText = function ( title
, namespace ) {
496 var t
, parsed
= parse( title
, namespace );
501 t
= createObject( Title
.prototype );
502 t
.namespace = parsed
.namespace;
503 t
.title
= parsed
.title
;
505 t
.fragment
= parsed
.fragment
;
511 * Constructor for Title objects with predefined namespace.
513 * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
514 * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
516 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
517 * function behaves like #newFromText in that case.
520 * @param {number} namespace Namespace to use for the title
521 * @param {string} title
522 * @return {mw.Title|null} A valid Title object or null if the title is invalid
524 Title
.makeTitle = function ( namespace, title
) {
525 return mw
.Title
.newFromText( getNamespacePrefix( namespace ) + title
);
529 * Constructor for Title objects from user input altering that input to
530 * produce a title that MediaWiki will accept as legal
533 * @param {string} title
534 * @param {number} [defaultNamespace=NS_MAIN]
535 * If given, will used as default namespace for the given title.
536 * @param {Object} [options] additional options
537 * @param {boolean} [options.forUploading=true]
538 * Makes sure that a file is uploadable under the title returned.
539 * There are pages in the file namespace under which file upload is impossible.
540 * Automatically assumed if the title is created in the Media namespace.
541 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
543 Title
.newFromUserInput = function ( title
, defaultNamespace
, options
) {
544 var namespace, m
, id
, ext
, parts
;
546 // defaultNamespace is optional; check whether options moves up
547 if ( arguments
.length
< 3 && $.type( defaultNamespace
) === 'object' ) {
548 options
= defaultNamespace
;
549 defaultNamespace
= undefined;
552 // merge options into defaults
553 options
= $.extend( {
557 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
559 // Normalise whitespace and remove duplicates
560 title
= $.trim( title
.replace( rWhitespace
, ' ' ) );
562 // Process initial colon
563 if ( title
!== '' && title
[ 0 ] === ':' ) {
564 // Initial colon means main namespace instead of specified default
570 .replace( rUnderscoreTrim
, '' );
573 // Process namespace prefix (if any)
574 m
= title
.match( rSplit
);
576 id
= getNsIdByName( m
[ 1 ] );
577 if ( id
!== false ) {
578 // Ordinary namespace
584 if ( namespace === NS_MEDIA
585 || ( options
.forUploading
&& ( namespace === NS_FILE
) )
588 title
= sanitize( title
, [ 'generalRule', 'fileRule' ] );
590 // Operate on the file extension
591 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
592 // operating systems hiding file extensions -> strip them later on
593 parts
= title
.split( '.' );
595 if ( parts
.length
> 1 ) {
597 // Get the last part, which is supposed to be the file extension
600 // Remove whitespace of the name part (that W/O extension)
601 title
= $.trim( parts
.join( '.' ) );
603 // Cut, if too long and append file extension
604 title
= trimFileNameToByteLength( title
, ext
);
608 // Missing file extension
609 title
= $.trim( parts
.join( '.' ) );
611 // Name has no file extension and a fallback wasn't provided either
616 title
= sanitize( title
, [ 'generalRule' ] );
618 // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
619 // (size of underlying database field)
620 if ( namespace !== NS_SPECIAL
) {
621 title
= trimToByteLength( title
, TITLE_MAX_BYTES
);
625 // Any remaining initial :s are illegal.
626 title
= title
.replace( /^\:+/, '' );
628 return Title
.newFromText( title
, namespace );
632 * Sanitizes a file name as supplied by the user, originating in the user's file system
633 * so it is most likely a valid MediaWiki title and file name after processing.
634 * Returns null on fatal errors.
637 * @param {string} uncleanName The unclean file name including file extension but
639 * @return {mw.Title|null} A valid Title object or null if the title is invalid
641 Title
.newFromFileName = function ( uncleanName
) {
643 return Title
.newFromUserInput( 'File:' + uncleanName
, {
649 * Get the file title from an image element
651 * var title = mw.Title.newFromImg( $( 'img:first' ) );
654 * @param {HTMLElement|jQuery} img The image to use as a base
655 * @return {mw.Title|null} The file title or null if unsuccessful
657 Title
.newFromImg = function ( img
) {
658 var matches
, i
, regex
, src
, decodedSrc
,
660 // thumb.php-generated thumbnails
661 thumbPhpRegex
= /thumb\.php/,
664 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[^\s\/]+-[^\s\/]*$/,
666 // Thumbnails in non-hashed upload directories
667 /\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
670 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
672 // Full-size images in non-hashed upload directories
676 recount
= regexes
.length
;
678 src
= img
.jquery
? img
[ 0 ].src
: img
.src
;
680 matches
= src
.match( thumbPhpRegex
);
683 return mw
.Title
.newFromText( 'File:' + mw
.util
.getParamValue( 'f', src
) );
686 decodedSrc
= decodeURIComponent( src
);
688 for ( i
= 0; i
< recount
; i
++ ) {
689 regex
= regexes
[ i
];
690 matches
= decodedSrc
.match( regex
);
692 if ( matches
&& matches
[ 1 ] ) {
693 return mw
.Title
.newFromText( 'File:' + matches
[ 1 ] );
701 * Whether this title exists on the wiki.
704 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
705 * @return {boolean|null} Boolean if the information is available, otherwise null
707 Title
.exists = function ( title
) {
709 type
= $.type( title
),
710 obj
= Title
.exist
.pages
;
712 if ( type
=== 'string' ) {
713 match
= obj
[ title
];
714 } else if ( type
=== 'object' && title
instanceof Title
) {
715 match
= obj
[ title
.toString() ];
717 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
720 if ( typeof match
=== 'boolean' ) {
728 * Store page existence
731 * @property {Object} exist
732 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
734 * @property {Function} exist.set The setter function.
736 * Example to declare existing titles:
738 * Title.exist.set( ['User:John_Doe', ...] );
740 * Example to declare titles nonexistent:
742 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
744 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
745 * @property {boolean} [exist.set.state=true] State of the given titles
751 set: function ( titles
, state
) {
752 titles
= $.isArray( titles
) ? titles
: [ titles
];
753 state
= state
=== undefined ? true : !!state
;
758 for ( i
= 0; i
< len
; i
++ ) {
759 pages
[ titles
[ i
] ] = state
;
766 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
767 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
768 * Keep in sync with File::normalizeExtension() in PHP.
770 * @param {string} extension File extension (without the leading dot)
771 * @return {string} File extension in canonical form
773 Title
.normalizeExtension = function ( extension
) {
775 lower
= extension
.toLowerCase(),
783 if ( squish
.hasOwnProperty( lower
) ) {
784 return squish
[ lower
];
785 } else if ( /^[0-9a-z]+$/.test( lower
) ) {
798 * Get the namespace number
800 * Example: 6 for "File:Example_image.svg".
804 getNamespaceId: function () {
805 return this.namespace;
809 * Get the namespace prefix (in the content language)
811 * Example: "File:" for "File:Example_image.svg".
812 * In #NS_MAIN this is '', otherwise namespace name plus ':'
816 getNamespacePrefix: function () {
817 return getNamespacePrefix( this.namespace );
821 * Get the page name without extension or namespace prefix
823 * Example: "Example_image" for "File:Example_image.svg".
825 * For the page title (full page name without namespace prefix), see #getMain.
829 getName: function () {
831 $.inArray( this.namespace, mw
.config
.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ||
836 return this.title
[ 0 ].toUpperCase() + this.title
.slice( 1 );
840 * Get the page name (transformed by #text)
842 * Example: "Example image" for "File:Example_image.svg".
844 * For the page title (full page name without namespace prefix), see #getMainText.
848 getNameText: function () {
849 return text( this.getName() );
853 * Get the extension of the page name (if any)
855 * @return {string|null} Name extension or null if there is none
857 getExtension: function () {
862 * Shortcut for appendable string to form the main page name.
864 * Returns a string like ".json", or "" if no extension.
868 getDotExtension: function () {
869 return this.ext
=== null ? '' : '.' + this.ext
;
873 * Get the main page name
875 * Example: "Example_image.svg" for "File:Example_image.svg".
879 getMain: function () {
880 return this.getName() + this.getDotExtension();
884 * Get the main page name (transformed by #text)
886 * Example: "Example image.svg" for "File:Example_image.svg".
890 getMainText: function () {
891 return text( this.getMain() );
895 * Get the full page name
897 * Example: "File:Example_image.svg".
898 * Most useful for API calls, anything that must identify the "title".
902 getPrefixedDb: function () {
903 return this.getNamespacePrefix() + this.getMain();
907 * Get the full page name (transformed by #text)
909 * Example: "File:Example image.svg" for "File:Example_image.svg".
913 getPrefixedText: function () {
914 return text( this.getPrefixedDb() );
918 * Get the page name relative to a namespace
922 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
923 * - "Bar" relative to any non-main namespace becomes ":Bar".
924 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
926 * @param {number} namespace The namespace to be relative to
929 getRelativeText: function ( namespace ) {
930 if ( this.getNamespaceId() === namespace ) {
931 return this.getMainText();
932 } else if ( this.getNamespaceId() === NS_MAIN
) {
933 return ':' + this.getPrefixedText();
935 return this.getPrefixedText();
940 * Get the fragment (if any).
942 * Note that this method (by design) does not include the hash character and
943 * the value is not url encoded.
945 * @return {string|null}
947 getFragment: function () {
948 return this.fragment
;
952 * Get the URL to this title
954 * @see mw.util#getUrl
955 * @param {Object} [params] A mapping of query parameter names to values,
956 * e.g. `{ action: 'edit' }`.
959 getUrl: function ( params
) {
960 var fragment
= this.getFragment();
962 return mw
.util
.getUrl( this.toString() + '#' + this.getFragment(), params
);
964 return mw
.util
.getUrl( this.toString(), params
);
969 * Whether this title exists on the wiki.
971 * @see #static-method-exists
972 * @return {boolean|null} Boolean if the information is available, otherwise null
974 exists: function () {
975 return Title
.exists( this );
980 * @alias #getPrefixedDb
983 Title
.prototype.toString
= Title
.prototype.getPrefixedDb
;
986 * @alias #getPrefixedText
989 Title
.prototype.toText
= Title
.prototype.getPrefixedText
;
994 }( mediaWiki
, jQuery
) );