mediawiki.Title: Fix typo "add" in documentation
[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 * 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.
13 *
14 * @class mw.Title
15 */
16 /**
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:
20 *
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'
24 *
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'
28 *
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'
32 *
33 * @method constructor
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
38 */
39 function Title( title, namespace ) {
40 var parsed = parse( title, namespace );
41 if ( !parsed ) {
42 throw new Error( 'Unable to parse title' );
43 }
44
45 this.namespace = parsed.namespace;
46 this.title = parsed.title;
47 this.ext = parsed.ext;
48 this.fragment = parsed.fragment;
49
50 return this;
51 }
52
53 /* Private members */
54
55 var
56
57 /**
58 * @private
59 * @static
60 * @property NS_MAIN
61 */
62 NS_MAIN = 0,
63
64 /**
65 * @private
66 * @static
67 * @property NS_TALK
68 */
69 NS_TALK = 1,
70
71 /**
72 * @private
73 * @static
74 * @property NS_SPECIAL
75 */
76 NS_SPECIAL = -1,
77
78 /**
79 * @private
80 * @static
81 * @property NS_MEDIA
82 */
83 NS_MEDIA = -2,
84
85 /**
86 * @private
87 * @static
88 * @property NS_FILE
89 */
90 NS_FILE = 6,
91
92 /**
93 * @private
94 * @static
95 * @property FILENAME_MAX_BYTES
96 */
97 FILENAME_MAX_BYTES = 240,
98
99 /**
100 * @private
101 * @static
102 * @property TITLE_MAX_BYTES
103 */
104 TITLE_MAX_BYTES = 255,
105
106 /**
107 * Get the namespace id from a namespace name (either from the localized, canonical or alias
108 * name).
109 *
110 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
111 * even 'Bild'.
112 *
113 * @private
114 * @static
115 * @method getNsIdByName
116 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
117 * @return {number|boolean} Namespace id or boolean false
118 */
119 getNsIdByName = function ( ns ) {
120 var id;
121
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' ) {
126 return false;
127 }
128 ns = ns.toLowerCase();
129 id = mw.config.get( 'wgNamespaceIds' )[ ns ];
130 if ( id === undefined ) {
131 return false;
132 }
133 return id;
134 },
135
136 /**
137 * @private
138 * @method getNamespacePrefix_
139 * @param {number} namespace
140 * @return {string}
141 */
142 getNamespacePrefix = function ( namespace ) {
143 return namespace === NS_MAIN ?
144 '' :
145 ( mw.config.get( 'wgFormattedNamespaces' )[ namespace ].replace( / /g, '_' ) + ':' );
146 },
147
148 rUnderscoreTrim = /^_+|_+$/g,
149
150 rSplit = /^(.+?)_*:_*(.*)$/,
151
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.
157 '|%[0-9A-Fa-f]{2}' +
158 // XML/HTML character references produce similar issues.
159 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
160 '|&#[0-9]+;' +
161 '|&#x[0-9A-Fa-f]+;'
162 ),
163
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,
167
168 /**
169 * Slightly modified from Flinfo. Credit goes to Lupo and Flominator.
170 * @private
171 * @static
172 * @property sanitationRules
173 */
174 sanitationRules = [
175 // "signature"
176 {
177 pattern: /~{3}/g,
178 replace: '',
179 generalRule: true
180 },
181 // Space, underscore, tab, NBSP and other unusual spaces
182 {
183 pattern: rWhitespace,
184 replace: ' ',
185 generalRule: true
186 },
187 // unicode bidi override characters: Implicit, Embeds, Overrides
188 {
189 pattern: /[\u200E\u200F\u202A-\u202E]/g,
190 replace: '',
191 generalRule: true
192 },
193 // control characters
194 {
195 pattern: /[\x00-\x1f\x7f]/g,
196 replace: '',
197 generalRule: true
198 },
199 // URL encoding (possibly)
200 {
201 pattern: /%([0-9A-Fa-f]{2})/g,
202 replace: '% $1',
203 generalRule: true
204 },
205 // HTML-character-entities
206 {
207 pattern: /&(([A-Za-z0-9\x80-\xff]+|#[0-9]+|#x[0-9A-Fa-f]+);)/g,
208 replace: '& $1',
209 generalRule: true
210 },
211 // slash, colon (not supported by file systems like NTFS/Windows, Mac OS 9 [:], ext4 [/])
212 {
213 pattern: /[:\/#]/g,
214 replace: '-',
215 fileRule: true
216 },
217 // brackets, greater than
218 {
219 pattern: /[\]\}>]/g,
220 replace: ')',
221 generalRule: true
222 },
223 // brackets, lower than
224 {
225 pattern: /[\[\{<]/g,
226 replace: '(',
227 generalRule: true
228 },
229 // everything that wasn't covered yet
230 {
231 pattern: new RegExp( rInvalid.source, 'g' ),
232 replace: '-',
233 generalRule: true
234 },
235 // directory structures
236 {
237 pattern: /^(\.|\.\.|\.\/.*|\.\.\/.*|.*\/\.\/.*|.*\/\.\.\/.*|.*\/\.|.*\/\.\.)$/g,
238 replace: '',
239 generalRule: true
240 }
241 ],
242
243 /**
244 * Internal helper for #constructor and #newFromText.
245 *
246 * Based on Title.php#secureAndSplit
247 *
248 * @private
249 * @static
250 * @method parse
251 * @param {string} title
252 * @param {number} [defaultNamespace=NS_MAIN]
253 * @return {Object|boolean}
254 */
255 parse = function ( title, defaultNamespace ) {
256 var namespace, m, id, i, fragment, ext;
257
258 namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
259
260 title = title
261 // Normalise whitespace to underscores and remove duplicates
262 .replace( /[ _\s]+/g, '_' )
263 // Trim underscores
264 .replace( rUnderscoreTrim, '' );
265
266 // Process initial colon
267 if ( title !== '' && title[ 0 ] === ':' ) {
268 // Initial colon means main namespace instead of specified default
269 namespace = NS_MAIN;
270 title = title
271 // Strip colon
272 .slice( 1 )
273 // Trim underscores
274 .replace( rUnderscoreTrim, '' );
275 }
276
277 if ( title === '' ) {
278 return false;
279 }
280
281 // Process namespace prefix (if any)
282 m = title.match( rSplit );
283 if ( m ) {
284 id = getNsIdByName( m[ 1 ] );
285 if ( id !== false ) {
286 // Ordinary namespace
287 namespace = id;
288 title = m[ 2 ];
289
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 ) {
294 return false;
295 }
296 }
297 }
298 }
299
300 // Process fragment
301 i = title.indexOf( '#' );
302 if ( i === -1 ) {
303 fragment = null;
304 } else {
305 fragment = title
306 // Get segment starting after the hash
307 .slice( i + 1 )
308 // Convert to text
309 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
310 .replace( /_/g, ' ' );
311
312 title = title
313 // Strip hash
314 .slice( 0, i )
315 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
316 .replace( rUnderscoreTrim, '' );
317 }
318
319 // Reject illegal characters
320 if ( title.match( rInvalid ) ) {
321 return false;
322 }
323
324 // Disallow titles that browsers or servers might resolve as directory navigation
325 if (
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 ) === '/..'
334 )
335 ) {
336 return false;
337 }
338
339 // Disallow magic tilde sequence
340 if ( title.indexOf( '~~~' ) !== -1 ) {
341 return false;
342 }
343
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 ) {
349 return false;
350 }
351
352 // Can't make a link to a namespace alone.
353 if ( title === '' && namespace !== NS_MAIN ) {
354 return false;
355 }
356
357 // Any remaining initial :s are illegal.
358 if ( title[ 0 ] === ':' ) {
359 return false;
360 }
361
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
367 ext = null;
368 } else {
369 ext = title.slice( i + 1 );
370 title = title.slice( 0, i );
371 }
372
373 return {
374 namespace: namespace,
375 title: title,
376 ext: ext,
377 fragment: fragment
378 };
379 },
380
381 /**
382 * Convert db-key to readable text.
383 *
384 * @private
385 * @static
386 * @method text
387 * @param {string} s
388 * @return {string}
389 */
390 text = function ( s ) {
391 if ( s !== null && s !== undefined ) {
392 return s.replace( /_/g, ' ' );
393 } else {
394 return '';
395 }
396 },
397
398 /**
399 * Sanitizes a string based on a rule set and a filter
400 *
401 * @private
402 * @static
403 * @method sanitize
404 * @param {string} s
405 * @param {Array} filter
406 * @return {string}
407 */
408 sanitize = function ( s, filter ) {
409 var i, ruleLength, rule, m, filterLength,
410 rules = sanitationRules;
411
412 for ( i = 0, ruleLength = rules.length; i < ruleLength; ++i ) {
413 rule = rules[ i ];
414 for ( m = 0, filterLength = filter.length; m < filterLength; ++m ) {
415 if ( rule[ filter[ m ] ] ) {
416 s = s.replace( rule.pattern, rule.replace );
417 }
418 }
419 }
420 return s;
421 },
422
423 /**
424 * Cuts a string to a specific byte length, assuming UTF-8
425 * or less, if the last character is a multi-byte one
426 *
427 * @private
428 * @static
429 * @method trimToByteLength
430 * @param {string} s
431 * @param {number} length
432 * @return {string}
433 */
434 trimToByteLength = function ( s, length ) {
435 var byteLength, chopOffChars, chopOffBytes;
436
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 );
448 }
449 return s;
450 },
451
452 /**
453 * Cuts a file name to a specific byte length
454 *
455 * @private
456 * @static
457 * @method trimFileNameToByteLength
458 * @param {string} name without extension
459 * @param {string} extension file extension
460 * @return {string} The full name, including extension
461 */
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;
465 },
466
467 // Polyfill for ES5 Object.create
468 createObject = Object.create || ( function () {
469 return function ( o ) {
470 function Title() {}
471 if ( o !== Object( o ) ) {
472 throw new Error( 'Cannot inherit from a non-object' );
473 }
474 Title.prototype = o;
475 return new Title();
476 };
477 }() );
478
479 /* Static members */
480
481 /**
482 * Constructor for Title objects with a null return instead of an exception for invalid titles.
483 *
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
486 * details.
487 *
488 * @static
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
492 */
493 Title.newFromText = function ( title, namespace ) {
494 var t, parsed = parse( title, namespace );
495 if ( !parsed ) {
496 return null;
497 }
498
499 t = createObject( Title.prototype );
500 t.namespace = parsed.namespace;
501 t.title = parsed.title;
502 t.ext = parsed.ext;
503 t.fragment = parsed.fragment;
504
505 return t;
506 };
507
508 /**
509 * Constructor for Title objects with predefined namespace.
510 *
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.
513 *
514 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
515 * function behaves like #newFromText in that case.
516 *
517 * @static
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
521 */
522 Title.makeTitle = function ( namespace, title ) {
523 return mw.Title.newFromText( getNamespacePrefix( namespace ) + title );
524 };
525
526 /**
527 * Constructor for Title objects from user input altering that input to
528 * produce a title that MediaWiki will accept as legal
529 *
530 * @static
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
540 */
541 Title.newFromUserInput = function ( title, defaultNamespace, options ) {
542 var namespace, m, id, ext, parts;
543
544 // defaultNamespace is optional; check whether options moves up
545 if ( arguments.length < 3 && $.type( defaultNamespace ) === 'object' ) {
546 options = defaultNamespace;
547 defaultNamespace = undefined;
548 }
549
550 // merge options into defaults
551 options = $.extend( {
552 forUploading: true
553 }, options );
554
555 namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
556
557 // Normalise whitespace and remove duplicates
558 title = $.trim( title.replace( rWhitespace, ' ' ) );
559
560 // Process initial colon
561 if ( title !== '' && title[ 0 ] === ':' ) {
562 // Initial colon means main namespace instead of specified default
563 namespace = NS_MAIN;
564 title = title
565 // Strip colon
566 .substr( 1 )
567 // Trim underscores
568 .replace( rUnderscoreTrim, '' );
569 }
570
571 // Process namespace prefix (if any)
572 m = title.match( rSplit );
573 if ( m ) {
574 id = getNsIdByName( m[ 1 ] );
575 if ( id !== false ) {
576 // Ordinary namespace
577 namespace = id;
578 title = m[ 2 ];
579 }
580 }
581
582 if ( namespace === NS_MEDIA
583 || ( options.forUploading && ( namespace === NS_FILE ) )
584 ) {
585
586 title = sanitize( title, [ 'generalRule', 'fileRule' ] );
587
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( '.' );
592
593 if ( parts.length > 1 ) {
594
595 // Get the last part, which is supposed to be the file extension
596 ext = parts.pop();
597
598 // Remove whitespace of the name part (that W/O extension)
599 title = $.trim( parts.join( '.' ) );
600
601 // Cut, if too long and append file extension
602 title = trimFileNameToByteLength( title, ext );
603
604 } else {
605
606 // Missing file extension
607 title = $.trim( parts.join( '.' ) );
608
609 // Name has no file extension and a fallback wasn't provided either
610 return null;
611 }
612 } else {
613
614 title = sanitize( title, [ 'generalRule' ] );
615
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 );
620 }
621 }
622
623 // Any remaining initial :s are illegal.
624 title = title.replace( /^\:+/, '' );
625
626 return Title.newFromText( title, namespace );
627 };
628
629 /**
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.
633 *
634 * @static
635 * @param {string} uncleanName The unclean file name including file extension but
636 * without namespace
637 * @return {mw.Title|null} A valid Title object or null if the title is invalid
638 */
639 Title.newFromFileName = function ( uncleanName ) {
640
641 return Title.newFromUserInput( 'File:' + uncleanName, {
642 forUploading: true
643 } );
644 };
645
646 /**
647 * Get the file title from an image element
648 *
649 * var title = mw.Title.newFromImg( $( 'img:first' ) );
650 *
651 * @static
652 * @param {HTMLElement|jQuery} img The image to use as a base
653 * @return {mw.Title|null} The file title or null if unsuccessful
654 */
655 Title.newFromImg = function ( img ) {
656 var matches, i, regex, src, decodedSrc,
657
658 // thumb.php-generated thumbnails
659 thumbPhpRegex = /thumb\.php/,
660 regexes = [
661 // Thumbnails
662 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[^\s\/]+-[^\s\/]*$/,
663
664 // Thumbnails in non-hashed upload directories
665 /\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
666
667 // Full size images
668 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
669
670 // Full-size images in non-hashed upload directories
671 /\/([^\s\/]+)$/
672 ],
673
674 recount = regexes.length;
675
676 src = img.jquery ? img[ 0 ].src : img.src;
677
678 matches = src.match( thumbPhpRegex );
679
680 if ( matches ) {
681 return mw.Title.newFromText( 'File:' + mw.util.getParamValue( 'f', src ) );
682 }
683
684 decodedSrc = decodeURIComponent( src );
685
686 for ( i = 0; i < recount; i++ ) {
687 regex = regexes[ i ];
688 matches = decodedSrc.match( regex );
689
690 if ( matches && matches[ 1 ] ) {
691 return mw.Title.newFromText( 'File:' + matches[ 1 ] );
692 }
693 }
694
695 return null;
696 };
697
698 /**
699 * Whether this title exists on the wiki.
700 *
701 * @static
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
704 */
705 Title.exists = function ( title ) {
706 var match,
707 type = $.type( title ),
708 obj = Title.exist.pages;
709
710 if ( type === 'string' ) {
711 match = obj[ title ];
712 } else if ( type === 'object' && title instanceof Title ) {
713 match = obj[ title.toString() ];
714 } else {
715 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
716 }
717
718 if ( typeof match === 'boolean' ) {
719 return match;
720 }
721
722 return null;
723 };
724
725 /**
726 * Store page existence
727 *
728 * @static
729 * @property {Object} exist
730 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
731 *
732 * @property {Function} exist.set The setter function.
733 *
734 * Example to declare existing titles:
735 *
736 * Title.exist.set( ['User:John_Doe', ...] );
737 *
738 * Example to declare titles nonexistent:
739 *
740 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
741 *
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
744 * @return {boolean}
745 */
746 Title.exist = {
747 pages: {},
748
749 set: function ( titles, state ) {
750 titles = $.isArray( titles ) ? titles : [ titles ];
751 state = state === undefined ? true : !!state;
752 var i,
753 pages = this.pages,
754 len = titles.length;
755
756 for ( i = 0; i < len; i++ ) {
757 pages[ titles[ i ] ] = state;
758 }
759 return true;
760 }
761 };
762
763 /**
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.
767 *
768 * @param {string} extension File extension (without the leading dot)
769 * @return {string} File extension in canonical form
770 */
771 Title.normalizeExtension = function ( extension ) {
772 var
773 lower = extension.toLowerCase(),
774 squish = {
775 htm: 'html',
776 jpeg: 'jpg',
777 mpeg: 'mpg',
778 tiff: 'tif',
779 ogv: 'ogg'
780 };
781 if ( squish.hasOwnProperty( lower ) ) {
782 return squish[ lower ];
783 } else if ( /^[0-9a-z]+$/.test( lower ) ) {
784 return lower;
785 } else {
786 return '';
787 }
788 };
789
790 /* Public members */
791
792 Title.prototype = {
793 constructor: Title,
794
795 /**
796 * Get the namespace number
797 *
798 * Example: 6 for "File:Example_image.svg".
799 *
800 * @return {number}
801 */
802 getNamespaceId: function () {
803 return this.namespace;
804 },
805
806 /**
807 * Get the namespace prefix (in the content language)
808 *
809 * Example: "File:" for "File:Example_image.svg".
810 * In #NS_MAIN this is '', otherwise namespace name plus ':'
811 *
812 * @return {string}
813 */
814 getNamespacePrefix: function () {
815 return getNamespacePrefix( this.namespace );
816 },
817
818 /**
819 * Get the page name without extension or namespace prefix
820 *
821 * Example: "Example_image" for "File:Example_image.svg".
822 *
823 * For the page title (full page name without namespace prefix), see #getMain.
824 *
825 * @return {string}
826 */
827 getName: function () {
828 if (
829 $.inArray( this.namespace, mw.config.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ||
830 !this.title.length
831 ) {
832 return this.title;
833 }
834 return this.title[ 0 ].toUpperCase() + this.title.slice( 1 );
835 },
836
837 /**
838 * Get the page name (transformed by #text)
839 *
840 * Example: "Example image" for "File:Example_image.svg".
841 *
842 * For the page title (full page name without namespace prefix), see #getMainText.
843 *
844 * @return {string}
845 */
846 getNameText: function () {
847 return text( this.getName() );
848 },
849
850 /**
851 * Get the extension of the page name (if any)
852 *
853 * @return {string|null} Name extension or null if there is none
854 */
855 getExtension: function () {
856 return this.ext;
857 },
858
859 /**
860 * Shortcut for appendable string to form the main page name.
861 *
862 * Returns a string like ".json", or "" if no extension.
863 *
864 * @return {string}
865 */
866 getDotExtension: function () {
867 return this.ext === null ? '' : '.' + this.ext;
868 },
869
870 /**
871 * Get the main page name
872 *
873 * Example: "Example_image.svg" for "File:Example_image.svg".
874 *
875 * @return {string}
876 */
877 getMain: function () {
878 return this.getName() + this.getDotExtension();
879 },
880
881 /**
882 * Get the main page name (transformed by #text)
883 *
884 * Example: "Example image.svg" for "File:Example_image.svg".
885 *
886 * @return {string}
887 */
888 getMainText: function () {
889 return text( this.getMain() );
890 },
891
892 /**
893 * Get the full page name
894 *
895 * Example: "File:Example_image.svg".
896 * Most useful for API calls, anything that must identify the "title".
897 *
898 * @return {string}
899 */
900 getPrefixedDb: function () {
901 return this.getNamespacePrefix() + this.getMain();
902 },
903
904 /**
905 * Get the full page name (transformed by #text)
906 *
907 * Example: "File:Example image.svg" for "File:Example_image.svg".
908 *
909 * @return {string}
910 */
911 getPrefixedText: function () {
912 return text( this.getPrefixedDb() );
913 },
914
915 /**
916 * Get the page name relative to a namespace
917 *
918 * Example:
919 *
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".
923 *
924 * @param {number} namespace The namespace to be relative to
925 * @return {string}
926 */
927 getRelativeText: function ( namespace ) {
928 if ( this.getNamespaceId() === namespace ) {
929 return this.getMainText();
930 } else if ( this.getNamespaceId() === NS_MAIN ) {
931 return ':' + this.getPrefixedText();
932 } else {
933 return this.getPrefixedText();
934 }
935 },
936
937 /**
938 * Get the fragment (if any).
939 *
940 * Note that this method (by design) does not include the hash character and
941 * the value is not url encoded.
942 *
943 * @return {string|null}
944 */
945 getFragment: function () {
946 return this.fragment;
947 },
948
949 /**
950 * Get the URL to this title
951 *
952 * @see mw.util#getUrl
953 * @param {Object} [params] A mapping of query parameter names to values,
954 * e.g. `{ action: 'edit' }`.
955 * @return {string}
956 */
957 getUrl: function ( params ) {
958 var fragment = this.getFragment();
959 if ( fragment ) {
960 return mw.util.getUrl( this.toString() + '#' + this.getFragment(), params );
961 } else {
962 return mw.util.getUrl( this.toString(), params );
963 }
964 },
965
966 /**
967 * Whether this title exists on the wiki.
968 *
969 * @see #static-method-exists
970 * @return {boolean|null} Boolean if the information is available, otherwise null
971 */
972 exists: function () {
973 return Title.exists( this );
974 }
975 };
976
977 /**
978 * @alias #getPrefixedDb
979 * @method
980 */
981 Title.prototype.toString = Title.prototype.getPrefixedDb;
982
983 /**
984 * @alias #getPrefixedText
985 * @method
986 */
987 Title.prototype.toText = Title.prototype.getPrefixedText;
988
989 // Expose
990 mw.Title = Title;
991
992 }( mediaWiki, jQuery ) );