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