7f95b1c4d4f123503aa8caad65726c4999e78caf
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.Title.js
1 /*!
2 * @author Neil Kandalgaonkar, 2010
3 * @author Timo Tijhof, 2011-2013
4 * @since 1.18
5 */
6 ( function ( mw, $ ) {
7 /*jshint latedef:false */
8
9 /**
10 * @class mw.Title
11 *
12 * Parse titles into an object structure. Note that when using the constructor
13 * directly, passing invalid titles will result in an exception. Use #newFromText to use the
14 * logic directly and get null for invalid titles which is easier to work with.
15 *
16 * @constructor
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
21 */
22 function Title( title, namespace ) {
23 var parsed = parse( title, namespace );
24 if ( !parsed ) {
25 throw new Error( 'Unable to parse title' );
26 }
27
28 this.namespace = parsed.namespace;
29 this.title = parsed.title;
30 this.ext = parsed.ext;
31 this.fragment = parsed.fragment;
32
33 return this;
34 }
35
36 /* Private members */
37
38 var
39
40 /**
41 * @private
42 * @static
43 * @property NS_MAIN
44 */
45 NS_MAIN = 0,
46
47 /**
48 * @private
49 * @static
50 * @property NS_TALK
51 */
52 NS_TALK = 1,
53
54 /**
55 * @private
56 * @static
57 * @property NS_SPECIAL
58 */
59 NS_SPECIAL = -1,
60
61 /**
62 * @private
63 * @static
64 * @property NS_MEDIA
65 */
66 NS_MEDIA = -2,
67
68 /**
69 * @private
70 * @static
71 * @property NS_FILE
72 */
73 NS_FILE = 6,
74
75 /**
76 * @private
77 * @static
78 * @property FILENAME_MAX_BYTES
79 */
80 FILENAME_MAX_BYTES = 240,
81
82 /**
83 * @private
84 * @static
85 * @property TITLE_MAX_BYTES
86 */
87 TITLE_MAX_BYTES = 255,
88
89 /**
90 * Get the namespace id from a namespace name (either from the localized, canonical or alias
91 * name).
92 *
93 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
94 * even 'Bild'.
95 *
96 * @private
97 * @static
98 * @method getNsIdByName
99 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
100 * @return {number|boolean} Namespace id or boolean false
101 */
102 getNsIdByName = function ( ns ) {
103 var id;
104
105 // Don't cast non-strings to strings, because null or undefined should not result in
106 // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
107 // Also, toLowerCase throws exception on null/undefined, because it is a String method.
108 if ( typeof ns !== 'string' ) {
109 return false;
110 }
111 ns = ns.toLowerCase();
112 id = mw.config.get( 'wgNamespaceIds' )[ ns ];
113 if ( id === undefined ) {
114 return false;
115 }
116 return id;
117 },
118
119 rUnderscoreTrim = /^_+|_+$/g,
120
121 rSplit = /^(.+?)_*:_*(.*)$/,
122
123 // See MediaWikiTitleCodec.php#getTitleInvalidRegex
124 rInvalid = new RegExp(
125 '[^' + mw.config.get( 'wgLegalTitleChars' ) + ']' +
126 // URL percent encoding sequences interfere with the ability
127 // to round-trip titles -- you can't link to them consistently.
128 '|%[0-9A-Fa-f]{2}' +
129 // XML/HTML character references produce similar issues.
130 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
131 '|&#[0-9]+;' +
132 '|&#x[0-9A-Fa-f]+;'
133 ),
134
135 // From MediaWikiTitleCodec.php#L225 @26fcab1f18c568a41
136 // "Clean up whitespace" in function MediaWikiTitleCodec::splitTitleString()
137 rWhitespace = /[ _\u0009\u00A0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\s]+/g,
138
139 /**
140 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
141 * @private
142 * @static
143 * @property sanitationRules
144 */
145 sanitationRules = [
146 // "signature"
147 {
148 pattern: /~{3}/g,
149 replace: '',
150 generalRule: true
151 },
152 // Space, underscore, tab, NBSP and other unusual spaces
153 {
154 pattern: rWhitespace,
155 replace: ' ',
156 generalRule: true
157 },
158 // unicode bidi override characters: Implicit, Embeds, Overrides
159 {
160 pattern: /[\u200E\u200F\u202A-\u202E]/g,
161 replace: '',
162 generalRule: true
163 },
164 // control characters
165 {
166 pattern: /[\x00-\x1f\x7f]/g,
167 replace: '',
168 generalRule: true
169 },
170 // URL encoding (possibly)
171 {
172 pattern: /%([0-9A-Fa-f]{2})/g,
173 replace: '% $1',
174 generalRule: true
175 },
176 // HTML-character-entities
177 {
178 pattern: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
179 replace: '& $1',
180 generalRule: true
181 },
182 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
183 {
184 pattern: /[:\/#]/g,
185 replace: '-',
186 fileRule: true
187 },
188 // brackets, greater than
189 {
190 pattern: /[\]\}>]/g,
191 replace: ')',
192 generalRule: true
193 },
194 // brackets, lower than
195 {
196 pattern: /[\[\{<]/g,
197 replace: '(',
198 generalRule: true
199 },
200 // everything that wasn't covered yet
201 {
202 pattern: new RegExp( rInvalid.source, 'g' ),
203 replace: '-',
204 generalRule: true
205 },
206 // directory structures
207 {
208 pattern: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
209 replace: '',
210 generalRule: true
211 }
212 ],
213
214 /**
215 * Internal helper for #constructor and #newFromtext.
216 *
217 * Based on Title.php#secureAndSplit
218 *
219 * @private
220 * @static
221 * @method parse
222 * @param {string} title
223 * @param {number} [defaultNamespace=NS_MAIN]
224 * @return {Object|boolean}
225 */
226 parse = function ( title, defaultNamespace ) {
227 var namespace, m, id, i, fragment, ext;
228
229 namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
230
231 title = title
232 // Normalise whitespace to underscores and remove duplicates
233 .replace( /[ _\s]+/g, '_' )
234 // Trim underscores
235 .replace( rUnderscoreTrim, '' );
236
237 // Process initial colon
238 if ( title !== '' && title[ 0 ] === ':' ) {
239 // Initial colon means main namespace instead of specified default
240 namespace = NS_MAIN;
241 title = title
242 // Strip colon
243 .slice( 1 )
244 // Trim underscores
245 .replace( rUnderscoreTrim, '' );
246 }
247
248 if ( title === '' ) {
249 return false;
250 }
251
252 // Process namespace prefix (if any)
253 m = title.match( rSplit );
254 if ( m ) {
255 id = getNsIdByName( m[ 1 ] );
256 if ( id !== false ) {
257 // Ordinary namespace
258 namespace = id;
259 title = m[ 2 ];
260
261 // For Talk:X pages, make sure X has no "namespace" prefix
262 if ( namespace === NS_TALK && ( m = title.match( rSplit ) ) ) {
263 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
264 if ( getNsIdByName( m[ 1 ] ) !== false ) {
265 return false;
266 }
267 }
268 }
269 }
270
271 // Process fragment
272 i = title.indexOf( '#' );
273 if ( i === -1 ) {
274 fragment = null;
275 } else {
276 fragment = title
277 // Get segment starting after the hash
278 .slice( i + 1 )
279 // Convert to text
280 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
281 .replace( /_/g, ' ' );
282
283 title = title
284 // Strip hash
285 .slice( 0, i )
286 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
287 .replace( rUnderscoreTrim, '' );
288 }
289
290 // Reject illegal characters
291 if ( title.match( rInvalid ) ) {
292 return false;
293 }
294
295 // Disallow titles that browsers or servers might resolve as directory navigation
296 if (
297 title.indexOf( '.' ) !== -1 && (
298 title === '.' || title === '..' ||
299 title.indexOf( './' ) === 0 ||
300 title.indexOf( '../' ) === 0 ||
301 title.indexOf( '/./' ) !== -1 ||
302 title.indexOf( '/../' ) !== -1 ||
303 title.slice( -2 ) === '/.' ||
304 title.slice( -3 ) === '/..'
305 )
306 ) {
307 return false;
308 }
309
310 // Disallow magic tilde sequence
311 if ( title.indexOf( '~~~' ) !== -1 ) {
312 return false;
313 }
314
315 // Disallow titles exceeding the TITLE_MAX_BYTES byte size limit (size of underlying database field)
316 // Except for special pages, e.g. [[Special:Block/Long name]]
317 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
318 // be less than 512 bytes.
319 if ( namespace !== NS_SPECIAL && $.byteLength( title ) > TITLE_MAX_BYTES ) {
320 return false;
321 }
322
323 // Can't make a link to a namespace alone.
324 if ( title === '' && namespace !== NS_MAIN ) {
325 return false;
326 }
327
328 // Any remaining initial :s are illegal.
329 if ( title[ 0 ] === ':' ) {
330 return false;
331 }
332
333 // For backwards-compatibility with old mw.Title, we separate the extension from the
334 // rest of the title.
335 i = title.lastIndexOf( '.' );
336 if ( i === -1 || title.length <= i + 1 ) {
337 // Extensions are the non-empty segment after the last dot
338 ext = null;
339 } else {
340 ext = title.slice( i + 1 );
341 title = title.slice( 0, i );
342 }
343
344 return {
345 namespace: namespace,
346 title: title,
347 ext: ext,
348 fragment: fragment
349 };
350 },
351
352 /**
353 * Convert db-key to readable text.
354 *
355 * @private
356 * @static
357 * @method text
358 * @param {string} s
359 * @return {string}
360 */
361 text = function ( s ) {
362 if ( s !== null && s !== undefined ) {
363 return s.replace( /_/g, ' ' );
364 } else {
365 return '';
366 }
367 },
368
369 /**
370 * Sanitizes a string based on a rule set and a filter
371 *
372 * @private
373 * @static
374 * @method sanitize
375 * @param {string} s
376 * @param {Array} filter
377 * @return {string}
378 */
379 sanitize = function ( s, filter ) {
380 var i, ruleLength, rule, m, filterLength,
381 rules = sanitationRules;
382
383 for ( i = 0, ruleLength = rules.length; i < ruleLength; ++i ) {
384 rule = rules[ i ];
385 for ( m = 0, filterLength = filter.length; m < filterLength; ++m ) {
386 if ( rule[ filter[ m ] ] ) {
387 s = s.replace( rule.pattern, rule.replace );
388 }
389 }
390 }
391 return s;
392 },
393
394 /**
395 * Cuts a string to a specific byte length, assuming UTF-8
396 * or less, if the last character is a multi-byte one
397 *
398 * @private
399 * @static
400 * @method trimToByteLength
401 * @param {string} s
402 * @param {number} length
403 * @return {string}
404 */
405 trimToByteLength = function ( s, length ) {
406 var byteLength, chopOffChars, chopOffBytes;
407
408 // bytelength is always greater or equal to the length in characters
409 s = s.substr( 0, length );
410 while ( ( byteLength = $.byteLength( s ) ) > length ) {
411 // Calculate how many characters can be safely removed
412 // First, we need to know how many bytes the string exceeds the threshold
413 chopOffBytes = byteLength - length;
414 // A character in UTF-8 is at most 4 bytes
415 // One character must be removed in any case because the
416 // string is too long
417 chopOffChars = Math.max( 1, Math.floor( chopOffBytes / 4 ) );
418 s = s.substr( 0, s.length - chopOffChars );
419 }
420 return s;
421 },
422
423 /**
424 * Cuts a file name to a specific byte length
425 *
426 * @private
427 * @static
428 * @method trimFileNameToByteLength
429 * @param {string} name without extension
430 * @param {string} extension file extension
431 * @return {string} The full name, including extension
432 */
433 trimFileNameToByteLength = function ( name, extension ) {
434 // There is a special byte limit for file names and ... remember the dot
435 return trimToByteLength( name, FILENAME_MAX_BYTES - extension.length - 1 ) + '.' + extension;
436 },
437
438 // Polyfill for ES5 Object.create
439 createObject = Object.create || ( function () {
440 return function ( o ) {
441 function Title() {}
442 if ( o !== Object( o ) ) {
443 throw new Error( 'Cannot inherit from a non-object' );
444 }
445 Title.prototype = o;
446 return new Title();
447 };
448 }() );
449
450 /* Static members */
451
452 /**
453 * Constructor for Title objects with a null return instead of an exception for invalid titles.
454 *
455 * @static
456 * @param {string} title
457 * @param {number} [namespace=NS_MAIN] Default namespace
458 * @return {mw.Title|null} A valid Title object or null if the title is invalid
459 */
460 Title.newFromText = function ( title, namespace ) {
461 var t, parsed = parse( title, namespace );
462 if ( !parsed ) {
463 return null;
464 }
465
466 t = createObject( Title.prototype );
467 t.namespace = parsed.namespace;
468 t.title = parsed.title;
469 t.ext = parsed.ext;
470 t.fragment = parsed.fragment;
471
472 return t;
473 };
474
475 /**
476 * Constructor for Title objects from user input altering that input to
477 * produce a title that MediaWiki will accept as legal
478 *
479 * @static
480 * @param {string} title
481 * @param {number} [defaultNamespace=NS_MAIN]
482 * If given, will used as default namespace for the given title.
483 * @param {Object} [options] additional options
484 * If the title is about to be created for the Media or File namespace,
485 * ensures the resulting Title has the correct extension. Useful, for example
486 * on systems that predict the type by content-sniffing, not by file extension.
487 * If different from empty string, `forUploading` is assumed.
488 * @param {boolean} [options.forUploading=true]
489 * Makes sure that a file is uploadable under the title returned.
490 * There are pages in the file namespace under which file upload is impossible.
491 * Automatically assumed if the title is created in the Media namespace.
492 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
493 */
494 Title.newFromUserInput = function ( title, defaultNamespace, options ) {
495 var namespace, m, id, ext, parts;
496
497 // defaultNamespace is optional; check whether options moves up
498 if ( arguments.length < 3 && $.type( defaultNamespace ) === 'object' ) {
499 options = defaultNamespace;
500 defaultNamespace = undefined;
501 }
502
503 // merge options into defaults
504 options = $.extend( {
505 forUploading: true
506 }, options );
507
508 namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
509
510 // Normalise whitespace and remove duplicates
511 title = $.trim( title.replace( rWhitespace, ' ' ) );
512
513 // Process initial colon
514 if ( title !== '' && title[ 0 ] === ':' ) {
515 // Initial colon means main namespace instead of specified default
516 namespace = NS_MAIN;
517 title = title
518 // Strip colon
519 .substr( 1 )
520 // Trim underscores
521 .replace( rUnderscoreTrim, '' );
522 }
523
524 // Process namespace prefix (if any)
525 m = title.match( rSplit );
526 if ( m ) {
527 id = getNsIdByName( m[ 1 ] );
528 if ( id !== false ) {
529 // Ordinary namespace
530 namespace = id;
531 title = m[ 2 ];
532 }
533 }
534
535 if ( namespace === NS_MEDIA
536 || ( options.forUploading && ( namespace === NS_FILE ) )
537 ) {
538
539 title = sanitize( title, [ 'generalRule', 'fileRule' ] );
540
541 // Operate on the file extension
542 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
543 // operating systems hiding file extensions -> strip them later on
544 parts = title.split( '.' );
545
546 if ( parts.length > 1 ) {
547
548 // Get the last part, which is supposed to be the file extension
549 ext = parts.pop();
550
551 // Remove whitespace of the name part (that W/O extension)
552 title = $.trim( parts.join( '.' ) );
553
554 // Cut, if too long and append file extension
555 title = trimFileNameToByteLength( title, ext );
556
557 } else {
558
559 // Missing file extension
560 title = $.trim( parts.join( '.' ) );
561
562 // Name has no file extension and a fallback wasn't provided either
563 return null;
564 }
565 } else {
566
567 title = sanitize( title, [ 'generalRule' ] );
568
569 // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
570 // (size of underlying database field)
571 if ( namespace !== NS_SPECIAL ) {
572 title = trimToByteLength( title, TITLE_MAX_BYTES );
573 }
574 }
575
576 // Any remaining initial :s are illegal.
577 title = title.replace( /^\:+/, '' );
578
579 return Title.newFromText( title, namespace );
580 };
581
582 /**
583 * Sanitizes a file name as supplied by the user, originating in the user's file system
584 * so it is most likely a valid MediaWiki title and file name after processing.
585 * Returns null on fatal errors.
586 *
587 * @static
588 * @param {string} uncleanName The unclean file name including file extension but
589 * without namespace
590 * @return {mw.Title|null} A valid Title object or null if the title is invalid
591 */
592 Title.newFromFileName = function ( uncleanName ) {
593
594 return Title.newFromUserInput( 'File:' + uncleanName, {
595 forUploading: true
596 } );
597 };
598
599 /**
600 * Get the file title from an image element
601 *
602 * var title = mw.Title.newFromImg( $( 'img:first' ) );
603 *
604 * @static
605 * @param {HTMLElement|jQuery} img The image to use as a base
606 * @return {mw.Title|null} The file title or null if unsuccessful
607 */
608 Title.newFromImg = function ( img ) {
609 var matches, i, regex, src, decodedSrc,
610
611 // thumb.php-generated thumbnails
612 thumbPhpRegex = /thumb\.php/,
613 regexes = [
614 // Thumbnails
615 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
616
617 // Thumbnails in non-hashed upload directories
618 /\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
619
620 // Full size images
621 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
622
623 // Full-size images in non-hashed upload directories
624 /\/([^\s\/]+)$/
625 ],
626
627 recount = regexes.length;
628
629 src = img.jquery ? img[ 0 ].src : img.src;
630
631 matches = src.match( thumbPhpRegex );
632
633 if ( matches ) {
634 return mw.Title.newFromText( 'File:' + mw.util.getParamValue( 'f', src ) );
635 }
636
637 decodedSrc = decodeURIComponent( src );
638
639 for ( i = 0; i < recount; i++ ) {
640 regex = regexes[ i ];
641 matches = decodedSrc.match( regex );
642
643 if ( matches && matches[ 1 ] ) {
644 return mw.Title.newFromText( 'File:' + matches[ 1 ] );
645 }
646 }
647
648 return null;
649 };
650
651 /**
652 * Whether this title exists on the wiki.
653 *
654 * @static
655 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
656 * @return {boolean|null} Boolean if the information is available, otherwise null
657 */
658 Title.exists = function ( title ) {
659 var match,
660 type = $.type( title ),
661 obj = Title.exist.pages;
662
663 if ( type === 'string' ) {
664 match = obj[ title ];
665 } else if ( type === 'object' && title instanceof Title ) {
666 match = obj[ title.toString() ];
667 } else {
668 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
669 }
670
671 if ( typeof match === 'boolean' ) {
672 return match;
673 }
674
675 return null;
676 };
677
678 /**
679 * Store page existence
680 *
681 * @static
682 * @property {Object} exist
683 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
684 *
685 * @property {Function} exist.set The setter function.
686 *
687 * Example to declare existing titles:
688 *
689 * Title.exist.set( ['User:John_Doe', ...] );
690 *
691 * Example to declare titles nonexistent:
692 *
693 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
694 *
695 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
696 * @property {boolean} [exist.set.state=true] State of the given titles
697 * @return {boolean}
698 */
699 Title.exist = {
700 pages: {},
701
702 set: function ( titles, state ) {
703 titles = $.isArray( titles ) ? titles : [ titles ];
704 state = state === undefined ? true : !!state;
705 var i,
706 pages = this.pages,
707 len = titles.length;
708
709 for ( i = 0; i < len; i++ ) {
710 pages[ titles[ i ] ] = state;
711 }
712 return true;
713 }
714 };
715
716 /**
717 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
718 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
719 * Keep in sync with File::normalizeExtension() in PHP.
720 *
721 * @param {string} extension File extension (without the leading dot)
722 * @return {string} File extension in canonical form
723 */
724 Title.normalizeExtension = function ( extension ) {
725 var
726 lower = extension.toLowerCase(),
727 squish = {
728 htm: 'html',
729 jpeg: 'jpg',
730 mpeg: 'mpg',
731 tiff: 'tif',
732 ogv: 'ogg'
733 };
734 if ( squish.hasOwnProperty( lower ) ) {
735 return squish[ lower ];
736 } else if ( /^[0-9a-z]+$/.test( lower ) ) {
737 return lower;
738 } else {
739 return '';
740 }
741 };
742
743 /* Public members */
744
745 Title.prototype = {
746 constructor: Title,
747
748 /**
749 * Get the namespace number
750 *
751 * Example: 6 for "File:Example_image.svg".
752 *
753 * @return {number}
754 */
755 getNamespaceId: function () {
756 return this.namespace;
757 },
758
759 /**
760 * Get the namespace prefix (in the content language)
761 *
762 * Example: "File:" for "File:Example_image.svg".
763 * In #NS_MAIN this is '', otherwise namespace name plus ':'
764 *
765 * @return {string}
766 */
767 getNamespacePrefix: function () {
768 return this.namespace === NS_MAIN ?
769 '' :
770 ( mw.config.get( 'wgFormattedNamespaces' )[ this.namespace ].replace( / /g, '_' ) + ':' );
771 },
772
773 /**
774 * Get the page name without extension or namespace prefix
775 *
776 * Example: "Example_image" for "File:Example_image.svg".
777 *
778 * For the page title (full page name without namespace prefix), see #getMain.
779 *
780 * @return {string}
781 */
782 getName: function () {
783 if (
784 $.inArray( this.namespace, mw.config.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ||
785 !this.title.length
786 ) {
787 return this.title;
788 }
789 return this.title[ 0 ].toUpperCase() + this.title.slice( 1 );
790 },
791
792 /**
793 * Get the page name (transformed by #text)
794 *
795 * Example: "Example image" for "File:Example_image.svg".
796 *
797 * For the page title (full page name without namespace prefix), see #getMainText.
798 *
799 * @return {string}
800 */
801 getNameText: function () {
802 return text( this.getName() );
803 },
804
805 /**
806 * Get the extension of the page name (if any)
807 *
808 * @return {string|null} Name extension or null if there is none
809 */
810 getExtension: function () {
811 return this.ext;
812 },
813
814 /**
815 * Shortcut for appendable string to form the main page name.
816 *
817 * Returns a string like ".json", or "" if no extension.
818 *
819 * @return {string}
820 */
821 getDotExtension: function () {
822 return this.ext === null ? '' : '.' + this.ext;
823 },
824
825 /**
826 * Get the main page name
827 *
828 * Example: "Example_image.svg" for "File:Example_image.svg".
829 *
830 * @return {string}
831 */
832 getMain: function () {
833 return this.getName() + this.getDotExtension();
834 },
835
836 /**
837 * Get the main page name (transformed by #text)
838 *
839 * Example: "Example image.svg" for "File:Example_image.svg".
840 *
841 * @return {string}
842 */
843 getMainText: function () {
844 return text( this.getMain() );
845 },
846
847 /**
848 * Get the full page name
849 *
850 * Example: "File:Example_image.svg".
851 * Most useful for API calls, anything that must identify the "title".
852 *
853 * @return {string}
854 */
855 getPrefixedDb: function () {
856 return this.getNamespacePrefix() + this.getMain();
857 },
858
859 /**
860 * Get the full page name (transformed by #text)
861 *
862 * Example: "File:Example image.svg" for "File:Example_image.svg".
863 *
864 * @return {string}
865 */
866 getPrefixedText: function () {
867 return text( this.getPrefixedDb() );
868 },
869
870 /**
871 * Get the page name relative to a namespace
872 *
873 * Example:
874 *
875 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
876 * - "Bar" relative to any non-main namespace becomes ":Bar".
877 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
878 *
879 * @param {number} namespace The namespace to be relative to
880 * @return {string}
881 */
882 getRelativeText: function ( namespace ) {
883 if ( this.getNamespaceId() === namespace ) {
884 return this.getMainText();
885 } else if ( this.getNamespaceId() === NS_MAIN ) {
886 return ':' + this.getPrefixedText();
887 } else {
888 return this.getPrefixedText();
889 }
890 },
891
892 /**
893 * Get the fragment (if any).
894 *
895 * Note that this method (by design) does not include the hash character and
896 * the value is not url encoded.
897 *
898 * @return {string|null}
899 */
900 getFragment: function () {
901 return this.fragment;
902 },
903
904 /**
905 * Get the URL to this title
906 *
907 * @see mw.util#getUrl
908 * @param {Object} [params] A mapping of query parameter names to values,
909 * e.g. `{ action: 'edit' }`.
910 * @return {string}
911 */
912 getUrl: function ( params ) {
913 return mw.util.getUrl( this.toString(), params );
914 },
915
916 /**
917 * Whether this title exists on the wiki.
918 *
919 * @see #static-method-exists
920 * @return {boolean|null} Boolean if the information is available, otherwise null
921 */
922 exists: function () {
923 return Title.exists( this );
924 }
925 };
926
927 /**
928 * @alias #getPrefixedDb
929 * @method
930 */
931 Title.prototype.toString = Title.prototype.getPrefixedDb;
932
933 /**
934 * @alias #getPrefixedText
935 * @method
936 */
937 Title.prototype.toText = Title.prototype.getPrefixedText;
938
939 // Expose
940 mw.Title = Title;
941
942 }( mediaWiki, jQuery ) );