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 * Get the file title from an image element
305 * var title = mw.Title.newFromImg( $( 'img:first' ) );
308 * @param {HTMLImageElement|jQuery} img The image to use as a base.
309 * @return {mw.Title|null} The file title - null if unsuccessful.
311 Title
.newFromImg = function ( img
) {
312 var matches
, i
, regex
, src
, decodedSrc
,
314 // thumb.php-generated thumbnails
315 thumbPhpRegex
= /thumb\.php/,
319 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[0-9]+px-\1[^\s\/]*$/,
321 // Thumbnails in non-hashed upload directories
322 /\/([^\s\/]+)\/[0-9]+px-\1[^\s\/]*$/,
325 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
327 // Full-size images in non-hashed upload directories
331 recount
= regexes
.length
;
333 img
= img
.jquery
? img
.get( 0 ) : img
;
337 matches
= src
.match( thumbPhpRegex
);
340 return mw
.Title
.newFromText( 'File:' + mw
.util
.getParamValue( 'f', src
) );
343 decodedSrc
= decodeURIComponent( src
);
345 for ( i
= 0; i
< recount
; i
++ ) {
347 matches
= decodedSrc
.match( regex
);
349 if ( matches
&& matches
[1] ) {
350 return mw
.Title
.newFromText( 'File:' + matches
[1] );
358 * Whether this title exists on the wiki.
361 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
362 * @return {boolean|null} Boolean if the information is available, otherwise null
364 Title
.exists = function ( title
) {
366 type
= $.type( title
),
367 obj
= Title
.exist
.pages
;
369 if ( type
=== 'string' ) {
371 } else if ( type
=== 'object' && title
instanceof Title
) {
372 match
= obj
[title
.toString()];
374 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
377 if ( typeof match
=== 'boolean' ) {
386 * Boolean true value indicates page does exist.
389 * @property {Object} exist.pages Keyed by PrefixedDb title.
394 * Example to declare existing titles:
395 * Title.exist.set(['User:John_Doe', ...]);
396 * Eample to declare titles nonexistent:
397 * Title.exist.set(['File:Foo_bar.jpg', ...], false);
400 * @property exist.set
401 * @param {string|Array} titles Title(s) in strict prefixedDb title form
402 * @param {boolean} [state=true] State of the given titles
405 set: function ( titles
, state
) {
406 titles
= $.isArray( titles
) ? titles
: [titles
];
407 state
= state
=== undefined ? true : !!state
;
408 var pages
= this.pages
, i
, len
= titles
.length
;
409 for ( i
= 0; i
< len
; i
++ ) {
410 pages
[ titles
[i
] ] = state
;
422 * Get the namespace number
424 * Example: 6 for "File:Example_image.svg".
428 getNamespaceId: function () {
429 return this.namespace;
433 * Get the namespace prefix (in the content language)
435 * Example: "File:" for "File:Example_image.svg".
436 * In #NS_MAIN this is '', otherwise namespace name plus ':'
440 getNamespacePrefix: function () {
441 return this.namespace === NS_MAIN
?
443 ( mw
.config
.get( 'wgFormattedNamespaces' )[ this.namespace ].replace( / /g
, '_' ) + ':' );
447 * Get the page name without extension or namespace prefix
449 * Example: "Example_image" for "File:Example_image.svg".
451 * For the page title (full page name without namespace prefix), see #getMain.
455 getName: function () {
456 if ( $.inArray( this.namespace, mw
.config
.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ) {
459 return $.ucFirst( this.title
);
464 * Get the page name (transformed by #text)
466 * Example: "Example image" for "File:Example_image.svg".
468 * For the page title (full page name without namespace prefix), see #getMainText.
472 getNameText: function () {
473 return text( this.getName() );
477 * Get the extension of the page name (if any)
479 * @return {string|null} Name extension or null if there is none
481 getExtension: function () {
486 * Shortcut for appendable string to form the main page name.
488 * Returns a string like ".json", or "" if no extension.
492 getDotExtension: function () {
493 return this.ext
=== null ? '' : '.' + this.ext
;
497 * Get the main page name (transformed by #text)
499 * Example: "Example_image.svg" for "File:Example_image.svg".
503 getMain: function () {
504 return this.getName() + this.getDotExtension();
508 * Get the main page name (transformed by #text)
510 * Example: "Example image.svg" for "File:Example_image.svg".
514 getMainText: function () {
515 return text( this.getMain() );
519 * Get the full page name
521 * Eaxample: "File:Example_image.svg".
522 * Most useful for API calls, anything that must identify the "title".
526 getPrefixedDb: function () {
527 return this.getNamespacePrefix() + this.getMain();
531 * Get the full page name (transformed by #text)
533 * Example: "File:Example image.svg" for "File:Example_image.svg".
537 getPrefixedText: function () {
538 return text( this.getPrefixedDb() );
542 * Get the fragment (if any).
544 * Note that this method (by design) does not include the hash character and
545 * the value is not url encoded.
547 * @return {string|null}
549 getFragment: function () {
550 return this.fragment
;
554 * Get the URL to this title
556 * @see mw.util#wikiGetlink
559 getUrl: function () {
560 return mw
.util
.wikiGetlink( this.toString() );
564 * Whether this title exists on the wiki.
566 * @see #static-method-exists
567 * @return {boolean|null} Boolean if the information is available, otherwise null
569 exists: function () {
570 return Title
.exists( this );
575 * @alias #getPrefixedDb
578 Title
.prototype.toString
= Title
.prototype.getPrefixedDb
;
582 * @alias #getPrefixedText
585 Title
.prototype.toText
= Title
.prototype.getPrefixedText
;
590 }( mediaWiki
, jQuery
) );