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