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