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