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