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
;
74 * @property NS_SPECIAL
95 * @property FILENAME_MAX_BYTES
97 FILENAME_MAX_BYTES
= 240,
102 * @property TITLE_MAX_BYTES
104 TITLE_MAX_BYTES
= 255,
107 * Get the namespace id from a namespace name (either from the localized, canonical or alias
110 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
115 * @method getNsIdByName
116 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
117 * @return {number|boolean} Namespace id or boolean false
119 getNsIdByName = function ( ns
) {
122 // Don't cast non-strings to strings, because null or undefined should not result in
123 // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
124 // Also, toLowerCase throws exception on null/undefined, because it is a String method.
125 if ( typeof ns
!== 'string' ) {
128 ns
= ns
.toLowerCase();
129 id
= mw
.config
.get( 'wgNamespaceIds' )[ ns
];
130 if ( id
=== undefined ) {
138 * @method getNamespacePrefix_
139 * @param {number} namespace
142 getNamespacePrefix = function ( namespace ) {
143 return namespace === NS_MAIN
?
145 ( mw
.config
.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g
, '_' ) + ':' );
148 rUnderscoreTrim
= /^_+|_+$/g,
150 rSplit
= /^(.+?)_*:_*(.*)$/,
152 // See MediaWikiTitleCodec.php#getTitleInvalidRegex
153 rInvalid
= new RegExp(
154 '[^' + mw
.config
.get( 'wgLegalTitleChars' ) + ']' +
155 // URL percent encoding sequences interfere with the ability
156 // to round-trip titles -- you can't link to them consistently.
158 // XML/HTML character references produce similar issues.
159 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
164 // From MediaWikiTitleCodec.php#L225 @26fcab1f18c568a41
165 // "Clean up whitespace" in function MediaWikiTitleCodec::splitTitleString()
166 rWhitespace
= /[ _\u0009\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\s]+/g,
169 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
172 * @property sanitationRules
181 // Space, underscore, tab, NBSP and other unusual spaces
183 pattern
: rWhitespace
,
187 // unicode bidi override characters: Implicit, Embeds, Overrides
189 pattern
: /[\u200E\u200F\u202A-\u202E]/g,
193 // control characters
195 pattern
: /[\x00-\x1f\x7f]/g,
199 // URL encoding (possibly)
201 pattern
: /%([0-9A-Fa-f]{2})/g,
205 // HTML-character-entities
207 pattern
: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
211 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
217 // brackets, greater than
223 // brackets, lower than
229 // everything that wasn't covered yet
231 pattern
: new RegExp( rInvalid
.source
, 'g' ),
235 // directory structures
237 pattern
: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
244 * Internal helper for #constructor and #newFromText.
246 * Based on Title.php#secureAndSplit
251 * @param {string} title
252 * @param {number} [defaultNamespace=NS_MAIN]
253 * @return {Object|boolean}
255 parse = function ( title
, defaultNamespace
) {
256 var namespace, m
, id
, i
, fragment
, ext
;
258 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
261 // Normalise whitespace to underscores and remove duplicates
262 .replace( /[ _\s]+/g, '_' )
264 .replace( rUnderscoreTrim
, '' );
266 // Process initial colon
267 if ( title
!== '' && title
[ 0 ] === ':' ) {
268 // Initial colon means main namespace instead of specified default
274 .replace( rUnderscoreTrim
, '' );
277 if ( title
=== '' ) {
281 // Process namespace prefix (if any)
282 m
= title
.match( rSplit
);
284 id
= getNsIdByName( m
[ 1 ] );
285 if ( id
!== false ) {
286 // Ordinary namespace
290 // For Talk:X pages, make sure X has no "namespace" prefix
291 if ( namespace === NS_TALK
&& ( m
= title
.match( rSplit
) ) ) {
292 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
293 if ( getNsIdByName( m
[ 1 ] ) !== false ) {
301 i
= title
.indexOf( '#' );
306 // Get segment starting after the hash
309 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
310 .replace( /_
/g
, ' ' );
315 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
316 .replace( rUnderscoreTrim
, '' );
319 // Reject illegal characters
320 if ( title
.match( rInvalid
) ) {
324 // Disallow titles that browsers or servers might resolve as directory navigation
326 title
.indexOf( '.' ) !== -1 && (
327 title
=== '.' || title
=== '..' ||
328 title
.indexOf( './' ) === 0 ||
329 title
.indexOf( '../' ) === 0 ||
330 title
.indexOf( '/./' ) !== -1 ||
331 title
.indexOf( '/../' ) !== -1 ||
332 title
.slice( -2 ) === '/.' ||
333 title
.slice( -3 ) === '/..'
339 // Disallow magic tilde sequence
340 if ( title
.indexOf( '~~~' ) !== -1 ) {
344 // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
345 // Except for special pages, e.g. [[Special:Block/Long name]]
346 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
347 // be less than 512 bytes.
348 if ( namespace !== NS_SPECIAL
&& $.byteLength( title
) > TITLE_MAX_BYTES
) {
352 // Can't make a link to a namespace alone.
353 if ( title
=== '' && namespace !== NS_MAIN
) {
357 // Any remaining initial :s are illegal.
358 if ( title
[ 0 ] === ':' ) {
362 // For backwards-compatibility with old mw.Title, we separate the extension from the
363 // rest of the title.
364 i
= title
.lastIndexOf( '.' );
365 if ( i
=== -1 || title
.length
<= i
+ 1 ) {
366 // Extensions are the non-empty segment after the last dot
369 ext
= title
.slice( i
+ 1 );
370 title
= title
.slice( 0, i
);
374 namespace: namespace,
382 * Convert db-key to readable text.
390 text = function ( s
) {
391 if ( s
!== null && s
!== undefined ) {
392 return s
.replace( /_
/g
, ' ' );
399 * Sanitizes a string based on a rule set and a filter
405 * @param {Array} filter
408 sanitize = function ( s
, filter
) {
409 var i
, ruleLength
, rule
, m
, filterLength
,
410 rules
= sanitationRules
;
412 for ( i
= 0, ruleLength
= rules
.length
; i
< ruleLength
; ++i
) {
414 for ( m
= 0, filterLength
= filter
.length
; m
< filterLength
; ++m
) {
415 if ( rule
[ filter
[ m
] ] ) {
416 s
= s
.replace( rule
.pattern
, rule
.replace
);
424 * Cuts a string to a specific byte length, assuming UTF-8
425 * or less, if the last character is a multi-byte one
429 * @method trimToByteLength
431 * @param {number} length
434 trimToByteLength = function ( s
, length
) {
435 var byteLength
, chopOffChars
, chopOffBytes
;
437 // bytelength is always greater or equal to the length in characters
438 s
= s
.substr( 0, length
);
439 while ( ( byteLength
= $.byteLength( s
) ) > length
) {
440 // Calculate how many characters can be safely removed
441 // First, we need to know how many bytes the string exceeds the threshold
442 chopOffBytes
= byteLength
- length
;
443 // A character in UTF-8 is at most 4 bytes
444 // One character must be removed in any case because the
445 // string is too long
446 chopOffChars
= Math
.max( 1, Math
.floor( chopOffBytes
/ 4 ) );
447 s
= s
.substr( 0, s
.length
- chopOffChars
);
453 * Cuts a file name to a specific byte length
457 * @method trimFileNameToByteLength
458 * @param {string} name without extension
459 * @param {string} extension file extension
460 * @return {string} The full name, including extension
462 trimFileNameToByteLength = function ( name
, extension
) {
463 // There is a special byte limit for file names and ... remember the dot
464 return trimToByteLength( name
, FILENAME_MAX_BYTES
- extension
.length
- 1 ) + '.' + extension
;
467 // Polyfill for ES5 Object.create
468 createObject
= Object
.create
|| ( function () {
469 return function ( o
) {
471 if ( o
!== Object( o
) ) {
472 throw new Error( 'Cannot inherit from a non-object' );
482 * Constructor for Title objects with a null return instead of an exception for invalid titles.
484 * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
485 * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
489 * @param {string} title
490 * @param {number} [namespace=NS_MAIN] Default namespace
491 * @return {mw.Title|null} A valid Title object or null if the title is invalid
493 Title
.newFromText = function ( title
, namespace ) {
494 var t
, parsed
= parse( title
, namespace );
499 t
= createObject( Title
.prototype );
500 t
.namespace = parsed
.namespace;
501 t
.title
= parsed
.title
;
503 t
.fragment
= parsed
.fragment
;
509 * Constructor for Title objects with predefined namespace.
511 * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
512 * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
514 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
515 * function behaves like #newFromText in that case.
518 * @param {number} namespace Namespace to use for the title
519 * @param {string} title
520 * @return {mw.Title|null} A valid Title object or null if the title is invalid
522 Title
.makeTitle = function ( namespace, title
) {
523 return mw
.Title
.newFromText( getNamespacePrefix( namespace ) + title
);
527 * Constructor for Title objects from user input altering that input to
528 * produce a title that MediaWiki will accept as legal
531 * @param {string} title
532 * @param {number} [defaultNamespace=NS_MAIN]
533 * If given, will used as default namespace for the given title.
534 * @param {Object} [options] additional options
535 * @param {boolean} [options.forUploading=true]
536 * Makes sure that a file is uploadable under the title returned.
537 * There are pages in the file namespace under which file upload is impossible.
538 * Automatically assumed if the title is created in the Media namespace.
539 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
541 Title
.newFromUserInput = function ( title
, defaultNamespace
, options
) {
542 var namespace, m
, id
, ext
, parts
;
544 // defaultNamespace is optional; check whether options moves up
545 if ( arguments
.length
< 3 && $.type( defaultNamespace
) === 'object' ) {
546 options
= defaultNamespace
;
547 defaultNamespace
= undefined;
550 // merge options into defaults
551 options
= $.extend( {
555 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
557 // Normalise whitespace and remove duplicates
558 title
= $.trim( title
.replace( rWhitespace
, ' ' ) );
560 // Process initial colon
561 if ( title
!== '' && title
[ 0 ] === ':' ) {
562 // Initial colon means main namespace instead of specified default
568 .replace( rUnderscoreTrim
, '' );
571 // Process namespace prefix (if any)
572 m
= title
.match( rSplit
);
574 id
= getNsIdByName( m
[ 1 ] );
575 if ( id
!== false ) {
576 // Ordinary namespace
582 if ( namespace === NS_MEDIA
583 || ( options
.forUploading
&& ( namespace === NS_FILE
) )
586 title
= sanitize( title
, [ 'generalRule', 'fileRule' ] );
588 // Operate on the file extension
589 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
590 // operating systems hiding file extensions -> strip them later on
591 parts
= title
.split( '.' );
593 if ( parts
.length
> 1 ) {
595 // Get the last part, which is supposed to be the file extension
598 // Remove whitespace of the name part (that W/O extension)
599 title
= $.trim( parts
.join( '.' ) );
601 // Cut, if too long and append file extension
602 title
= trimFileNameToByteLength( title
, ext
);
606 // Missing file extension
607 title
= $.trim( parts
.join( '.' ) );
609 // Name has no file extension and a fallback wasn't provided either
614 title
= sanitize( title
, [ 'generalRule' ] );
616 // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
617 // (size of underlying database field)
618 if ( namespace !== NS_SPECIAL
) {
619 title
= trimToByteLength( title
, TITLE_MAX_BYTES
);
623 // Any remaining initial :s are illegal.
624 title
= title
.replace( /^\:+/, '' );
626 return Title
.newFromText( title
, namespace );
630 * Sanitizes a file name as supplied by the user, originating in the user's file system
631 * so it is most likely a valid MediaWiki title and file name after processing.
632 * Returns null on fatal errors.
635 * @param {string} uncleanName The unclean file name including file extension but
637 * @return {mw.Title|null} A valid Title object or null if the title is invalid
639 Title
.newFromFileName = function ( uncleanName
) {
641 return Title
.newFromUserInput( 'File:' + uncleanName
, {
647 * Get the file title from an image element
649 * var title = mw.Title.newFromImg( $( 'img:first' ) );
652 * @param {HTMLElement|jQuery} img The image to use as a base
653 * @return {mw.Title|null} The file title or null if unsuccessful
655 Title
.newFromImg = function ( img
) {
656 var matches
, i
, regex
, src
, decodedSrc
,
658 // thumb.php-generated thumbnails
659 thumbPhpRegex
= /thumb\.php/,
662 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[^\s\/]+-[^\s\/]*$/,
664 // Thumbnails in non-hashed upload directories
665 /\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
668 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
670 // Full-size images in non-hashed upload directories
674 recount
= regexes
.length
;
676 src
= img
.jquery
? img
[ 0 ].src
: img
.src
;
678 matches
= src
.match( thumbPhpRegex
);
681 return mw
.Title
.newFromText( 'File:' + mw
.util
.getParamValue( 'f', src
) );
684 decodedSrc
= decodeURIComponent( src
);
686 for ( i
= 0; i
< recount
; i
++ ) {
687 regex
= regexes
[ i
];
688 matches
= decodedSrc
.match( regex
);
690 if ( matches
&& matches
[ 1 ] ) {
691 return mw
.Title
.newFromText( 'File:' + matches
[ 1 ] );
699 * Whether this title exists on the wiki.
702 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
703 * @return {boolean|null} Boolean if the information is available, otherwise null
705 Title
.exists = function ( title
) {
707 type
= $.type( title
),
708 obj
= Title
.exist
.pages
;
710 if ( type
=== 'string' ) {
711 match
= obj
[ title
];
712 } else if ( type
=== 'object' && title
instanceof Title
) {
713 match
= obj
[ title
.toString() ];
715 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
718 if ( typeof match
=== 'boolean' ) {
726 * Store page existence
729 * @property {Object} exist
730 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
732 * @property {Function} exist.set The setter function.
734 * Example to declare existing titles:
736 * Title.exist.set( ['User:John_Doe', ...] );
738 * Example to declare titles nonexistent:
740 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
742 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
743 * @property {boolean} [exist.set.state=true] State of the given titles
749 set: function ( titles
, state
) {
750 titles
= $.isArray( titles
) ? titles
: [ titles
];
751 state
= state
=== undefined ? true : !!state
;
756 for ( i
= 0; i
< len
; i
++ ) {
757 pages
[ titles
[ i
] ] = state
;
764 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
765 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
766 * Keep in sync with File::normalizeExtension() in PHP.
768 * @param {string} extension File extension (without the leading dot)
769 * @return {string} File extension in canonical form
771 Title
.normalizeExtension = function ( extension
) {
773 lower
= extension
.toLowerCase(),
781 if ( squish
.hasOwnProperty( lower
) ) {
782 return squish
[ lower
];
783 } else if ( /^[0-9a-z]+$/.test( lower
) ) {
796 * Get the namespace number
798 * Example: 6 for "File:Example_image.svg".
802 getNamespaceId: function () {
803 return this.namespace;
807 * Get the namespace prefix (in the content language)
809 * Example: "File:" for "File:Example_image.svg".
810 * In #NS_MAIN this is '', otherwise namespace name plus ':'
814 getNamespacePrefix: function () {
815 return getNamespacePrefix( this.namespace );
819 * Get the page name without extension or namespace prefix
821 * Example: "Example_image" for "File:Example_image.svg".
823 * For the page title (full page name without namespace prefix), see #getMain.
827 getName: function () {
829 $.inArray( this.namespace, mw
.config
.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ||
834 return this.title
[ 0 ].toUpperCase() + this.title
.slice( 1 );
838 * Get the page name (transformed by #text)
840 * Example: "Example image" for "File:Example_image.svg".
842 * For the page title (full page name without namespace prefix), see #getMainText.
846 getNameText: function () {
847 return text( this.getName() );
851 * Get the extension of the page name (if any)
853 * @return {string|null} Name extension or null if there is none
855 getExtension: function () {
860 * Shortcut for appendable string to form the main page name.
862 * Returns a string like ".json", or "" if no extension.
866 getDotExtension: function () {
867 return this.ext
=== null ? '' : '.' + this.ext
;
871 * Get the main page name
873 * Example: "Example_image.svg" for "File:Example_image.svg".
877 getMain: function () {
878 return this.getName() + this.getDotExtension();
882 * Get the main page name (transformed by #text)
884 * Example: "Example image.svg" for "File:Example_image.svg".
888 getMainText: function () {
889 return text( this.getMain() );
893 * Get the full page name
895 * Example: "File:Example_image.svg".
896 * Most useful for API calls, anything that must identify the "title".
900 getPrefixedDb: function () {
901 return this.getNamespacePrefix() + this.getMain();
905 * Get the full page name (transformed by #text)
907 * Example: "File:Example image.svg" for "File:Example_image.svg".
911 getPrefixedText: function () {
912 return text( this.getPrefixedDb() );
916 * Get the page name relative to a namespace
920 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
921 * - "Bar" relative to any non-main namespace becomes ":Bar".
922 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
924 * @param {number} namespace The namespace to be relative to
927 getRelativeText: function ( namespace ) {
928 if ( this.getNamespaceId() === namespace ) {
929 return this.getMainText();
930 } else if ( this.getNamespaceId() === NS_MAIN
) {
931 return ':' + this.getPrefixedText();
933 return this.getPrefixedText();
938 * Get the fragment (if any).
940 * Note that this method (by design) does not include the hash character and
941 * the value is not url encoded.
943 * @return {string|null}
945 getFragment: function () {
946 return this.fragment
;
950 * Get the URL to this title
952 * @see mw.util#getUrl
953 * @param {Object} [params] A mapping of query parameter names to values,
954 * e.g. `{ action: 'edit' }`.
957 getUrl: function ( params
) {
958 var fragment
= this.getFragment();
960 return mw
.util
.getUrl( this.toString() + '#' + this.getFragment(), params
);
962 return mw
.util
.getUrl( this.toString(), params
);
967 * Whether this title exists on the wiki.
969 * @see #static-method-exists
970 * @return {boolean|null} Boolean if the information is available, otherwise null
972 exists: function () {
973 return Title
.exists( this );
978 * @alias #getPrefixedDb
981 Title
.prototype.toString
= Title
.prototype.getPrefixedDb
;
984 * @alias #getPrefixedText
987 Title
.prototype.toText
= Title
.prototype.getPrefixedText
;
992 }( mediaWiki
, jQuery
) );