2 * @author Neil Kandalgaonkar, 2010
3 * @author Timo Tijhof, 2011-2013
11 * Parse titles into an object struture. Note that when using the constructor
12 * directly, passing invalid titles will result in an exception. Use
13 * #newFromText to use the logic directly and get null for invalid titles
14 * which is easier to work with.
17 * @param {string} title Title of the page. If no second argument given,
18 * this will be searched for a namespace
19 * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
20 * @throws {Error} When the title is invalid
22 function Title( title
, namespace ) {
23 var parsed
= parse( title
, namespace );
25 throw new Error( 'Unable to parse title' );
28 this.namespace = parsed
.namespace;
29 this.title
= parsed
.title
;
30 this.ext
= parsed
.ext
;
31 this.fragment
= parsed
.fragment
;
57 * @property NS_SPECIAL
62 * Get the namespace id from a namespace name (either from the localized, canonical or alias
65 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
70 * @method getNsIdByName
71 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
72 * @return {number|boolean} Namespace id or boolean false
74 getNsIdByName = function ( ns
) {
77 // Don't cast non-strings to strings, because null or undefined should not result in
78 // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
79 // Also, toLowerCase throws exception on null/undefined, because it is a String method.
80 if ( typeof ns
!== 'string' ) {
83 ns
= ns
.toLowerCase();
84 id
= mw
.config
.get( 'wgNamespaceIds' )[ns
];
85 if ( id
=== undefined ) {
91 rUnderscoreTrim
= /^_+|_+$/g,
93 rSplit
= /^(.+?)_*:_*(.*)$/,
95 // See Title.php#getTitleInvalidRegex
96 rInvalid
= new RegExp(
97 '[^' + mw
.config
.get( 'wgLegalTitleChars' ) + ']' +
98 // URL percent encoding sequences interfere with the ability
99 // to round-trip titles -- you can't link to them consistently.
101 // XML/HTML character references produce similar issues.
102 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
108 * Internal helper for #constructor and #newFromtext.
110 * Based on Title.php#secureAndSplit
115 * @param {string} title
116 * @param {number} [defaultNamespace=NS_MAIN]
117 * @return {Object|boolean}
119 parse = function ( title
, defaultNamespace
) {
120 var namespace, m
, id
, i
, fragment
, ext
;
122 namespace = defaultNamespace
=== undefined ? NS_MAIN
: defaultNamespace
;
125 // Normalise whitespace to underscores and remove duplicates
126 .replace( /[ _\s]+/g, '_' )
128 .replace( rUnderscoreTrim
, '' );
130 if ( title
=== '' ) {
134 // Process initial colon
135 if ( title
.charAt( 0 ) === ':' ) {
136 // Initial colon means main namespace instead of specified default
142 .replace( rUnderscoreTrim
, '' );
145 // Process namespace prefix (if any)
146 m
= title
.match( rSplit
);
148 id
= getNsIdByName( m
[1] );
149 if ( id
!== false ) {
150 // Ordinary namespace
154 // For Talk:X pages, make sure X has no "namespace" prefix
155 if ( namespace === NS_TALK
&& ( m
= title
.match( rSplit
) ) ) {
156 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
157 if ( getNsIdByName( m
[1] ) !== false ) {
165 i
= title
.indexOf( '#' );
170 // Get segment starting after the hash
173 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
174 .replace( /_
/g
, ' ' );
179 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
180 .replace( rUnderscoreTrim
, '' );
184 // Reject illegal characters
185 if ( title
.match( rInvalid
) ) {
189 // Disallow titles that browsers or servers might resolve as directory navigation
191 title
.indexOf( '.' ) !== -1 && (
192 title
=== '.' || title
=== '..' ||
193 title
.indexOf( './' ) === 0 ||
194 title
.indexOf( '../' ) === 0 ||
195 title
.indexOf( '/./' ) !== -1 ||
196 title
.indexOf( '/../' ) !== -1 ||
197 title
.substr( -2 ) === '/.' ||
198 title
.substr( -3 ) === '/..'
204 // Disallow magic tilde sequence
205 if ( title
.indexOf( '~~~' ) !== -1 ) {
209 // Disallow titles exceeding the 255 byte size limit (size of underlying database field)
210 // Except for special pages, e.g. [[Special:Block/Long name]]
211 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
212 // be less than 512 bytes.
213 if ( namespace !== NS_SPECIAL
&& $.byteLength( title
) > 255 ) {
217 // Can't make a link to a namespace alone.
218 if ( title
=== '' && namespace !== NS_MAIN
) {
222 // Any remaining initial :s are illegal.
223 if ( title
.charAt( 0 ) === ':' ) {
227 // For backwards-compatibility with old mw.Title, we separate the extension from the
228 // rest of the title.
229 i
= title
.lastIndexOf( '.' );
230 if ( i
=== -1 || title
.length
<= i
+ 1 ) {
231 // Extensions are the non-empty segment after the last dot
234 ext
= title
.substr( i
+ 1 );
235 title
= title
.substr( 0, i
);
239 namespace: namespace,
247 * Convert db-key to readable text.
255 text = function ( s
) {
256 if ( s
!== null && s
!== undefined ) {
257 return s
.replace( /_
/g
, ' ' );
263 // Polyfill for ES5 Object.create
264 createObject
= Object
.create
|| ( function () {
265 return function ( o
) {
267 if ( o
!== Object( o
) ) {
268 throw new Error( 'Cannot inherit from a non-object' );
279 * Constructor for Title objects with a null return instead of an exception for invalid titles.
283 * @param {string} title
284 * @param {number} [namespace=NS_MAIN] Default namespace
285 * @return {mw.Title|null} A valid Title object or null if the title is invalid
287 Title
.newFromText = function ( title
, namespace ) {
288 var t
, parsed
= parse( title
, namespace );
293 t
= createObject( Title
.prototype );
294 t
.namespace = parsed
.namespace;
295 t
.title
= parsed
.title
;
297 t
.fragment
= parsed
.fragment
;
303 * Whether this title exists on the wiki.
306 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
307 * @return {boolean|null} Boolean if the information is available, otherwise null
309 Title
.exists = function ( title
) {
311 type
= $.type( title
),
312 obj
= Title
.exist
.pages
;
314 if ( type
=== 'string' ) {
316 } else if ( type
=== 'object' && title
instanceof Title
) {
317 match
= obj
[title
.toString()];
319 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
322 if ( typeof match
=== 'boolean' ) {
331 * Boolean true value indicates page does exist.
334 * @property {Object} exist.pages Keyed by PrefixedDb title.
339 * Example to declare existing titles:
340 * Title.exist.set(['User:John_Doe', ...]);
341 * Eample to declare titles nonexistent:
342 * Title.exist.set(['File:Foo_bar.jpg', ...], false);
345 * @property exist.set
346 * @param {string|Array} titles Title(s) in strict prefixedDb title form
347 * @param {boolean} [state=true] State of the given titles
350 set: function ( titles
, state
) {
351 titles
= $.isArray( titles
) ? titles
: [titles
];
352 state
= state
=== undefined ? true : !!state
;
353 var pages
= this.pages
, i
, len
= titles
.length
;
354 for ( i
= 0; i
< len
; i
++ ) {
355 pages
[ titles
[i
] ] = state
;
367 * Get the namespace number
369 * Example: 6 for "File:Example_image.svg".
373 getNamespaceId: function () {
374 return this.namespace;
378 * Get the namespace prefix (in the content language)
380 * Example: "File:" for "File:Example_image.svg".
381 * In #NS_MAIN this is '', otherwise namespace name plus ':'
385 getNamespacePrefix: function () {
386 return this.namespace === NS_MAIN
?
388 ( mw
.config
.get( 'wgFormattedNamespaces' )[ this.namespace ].replace( / /g
, '_' ) + ':' );
392 * Get the page name without extension or namespace prefix
394 * Example: "Example_image" for "File:Example_image.svg".
396 * For the page title (full page name without namespace prefix), see #getMain.
400 getName: function () {
401 if ( $.inArray( this.namespace, mw
.config
.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ) {
404 return $.ucFirst( this.title
);
409 * Get the page name (transformed by #text)
411 * Example: "Example image" for "File:Example_image.svg".
413 * For the page title (full page name without namespace prefix), see #getMainText.
417 getNameText: function () {
418 return text( this.getName() );
422 * Get the extension of the page name (if any)
424 * @return {string|null} Name extension or null if there is none
426 getExtension: function () {
431 * Shortcut for appendable string to form the main page name.
433 * Returns a string like ".json", or "" if no extension.
437 getDotExtension: function () {
438 return this.ext
=== null ? '' : '.' + this.ext
;
442 * Get the main page name (transformed by #text)
444 * Example: "Example_image.svg" for "File:Example_image.svg".
448 getMain: function () {
449 return this.getName() + this.getDotExtension();
453 * Get the main page name (transformed by #text)
455 * Example: "Example image.svg" for "File:Example_image.svg".
459 getMainText: function () {
460 return text( this.getMain() );
464 * Get the full page name
466 * Eaxample: "File:Example_image.svg".
467 * Most useful for API calls, anything that must identify the "title".
471 getPrefixedDb: function () {
472 return this.getNamespacePrefix() + this.getMain();
476 * Get the full page name (transformed by #text)
478 * Example: "File:Example image.svg" for "File:Example_image.svg".
482 getPrefixedText: function () {
483 return text( this.getPrefixedDb() );
487 * Get the fragment (if any).
489 * Note that this method (by design) does not include the hash character and
490 * the value is not url encoded.
492 * @return {string|null}
494 getFragment: function () {
495 return this.fragment
;
499 * Get the URL to this title
501 * @see mw.util#wikiGetlink
504 getUrl: function () {
505 return mw
.util
.wikiGetlink( this.toString() );
509 * Whether this title exists on the wiki.
511 * @see #static-method-exists
512 * @return {boolean|null} Boolean if the information is available, otherwise null
514 exists: function () {
515 return Title
.exists( this );
520 * @alias #getPrefixedDb
523 Title
.prototype.toString
= Title
.prototype.getPrefixedDb
;
527 * @alias #getPrefixedText
530 Title
.prototype.toText
= Title
.prototype.getPrefixedText
;
535 }( mediaWiki
, jQuery
) );