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