Merge "selenium: invoke jobs to enforce eventual consistency"
[lhc/web/wiklou.git] / resources / src / mediawiki.Title / Title.js
1 /*!
2 * @author Neil Kandalgaonkar, 2010
3 * @author Timo Tijhof
4 * @since 1.18
5 */
6
7 ( function () {
8 /**
9 * Parse titles into an object structure. Note that when using the constructor
10 * directly, passing invalid titles will result in an exception. Use #newFromText to use the
11 * logic directly and get null for invalid titles which is easier to work with.
12 *
13 * Note that in the constructor and #newFromText method, `namespace` is the **default** namespace
14 * only, and can be overridden by a namespace prefix in `title`. If you do not want this behavior,
15 * use #makeTitle. Compare:
16 *
17 * new mw.Title( 'Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
18 * mw.Title.newFromText( 'Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
19 * mw.Title.makeTitle( NS_TEMPLATE, 'Foo' ).getPrefixedText(); // => 'Template:Foo'
20 *
21 * new mw.Title( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
22 * mw.Title.newFromText( 'Category:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Category:Foo'
23 * mw.Title.makeTitle( NS_TEMPLATE, 'Category:Foo' ).getPrefixedText(); // => 'Template:Category:Foo'
24 *
25 * new mw.Title( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
26 * mw.Title.newFromText( 'Template:Foo', NS_TEMPLATE ).getPrefixedText(); // => 'Template:Foo'
27 * mw.Title.makeTitle( NS_TEMPLATE, 'Template:Foo' ).getPrefixedText(); // => 'Template:Template:Foo'
28 *
29 * @class mw.Title
30 */
31
32 /* Private members */
33
34 var
35 mwString = require( 'mediawiki.String' ),
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, ext;
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 // For backwards-compatibility with old mw.Title, we separate the extension from the
340 // rest of the title.
341 i = title.lastIndexOf( '.' );
342 if ( i === -1 || title.length <= i + 1 ) {
343 // Extensions are the non-empty segment after the last dot
344 ext = null;
345 } else {
346 ext = title.slice( i + 1 );
347 title = title.slice( 0, i );
348 }
349
350 return {
351 namespace: namespace,
352 title: title,
353 ext: ext,
354 fragment: fragment
355 };
356 },
357
358 /**
359 * Convert db-key to readable text.
360 *
361 * @private
362 * @static
363 * @method text
364 * @param {string} s
365 * @return {string}
366 */
367 text = function ( s ) {
368 return s.replace( /_/g, ' ' );
369 },
370
371 /**
372 * Sanitizes a string based on a rule set and a filter
373 *
374 * @private
375 * @static
376 * @method sanitize
377 * @param {string} s
378 * @param {Array} filter
379 * @return {string}
380 */
381 sanitize = function ( s, filter ) {
382 var i, ruleLength, rule, m, filterLength,
383 rules = sanitationRules;
384
385 for ( i = 0, ruleLength = rules.length; i < ruleLength; ++i ) {
386 rule = rules[ i ];
387 for ( m = 0, filterLength = filter.length; m < filterLength; ++m ) {
388 if ( rule[ filter[ m ] ] ) {
389 s = s.replace( rule.pattern, rule.replace );
390 }
391 }
392 }
393 return s;
394 },
395
396 /**
397 * Cuts a string to a specific byte length, assuming UTF-8
398 * or less, if the last character is a multi-byte one
399 *
400 * @private
401 * @static
402 * @method trimToByteLength
403 * @param {string} s
404 * @param {number} length
405 * @return {string}
406 */
407 trimToByteLength = function ( s, length ) {
408 return mwString.trimByteLength( '', s, length ).newVal;
409 },
410
411 /**
412 * Cuts a file name to a specific byte length
413 *
414 * @private
415 * @static
416 * @method trimFileNameToByteLength
417 * @param {string} name without extension
418 * @param {string} extension file extension
419 * @return {string} The full name, including extension
420 */
421 trimFileNameToByteLength = function ( name, extension ) {
422 // There is a special byte limit for file names and ... remember the dot
423 return trimToByteLength( name, FILENAME_MAX_BYTES - extension.length - 1 ) + '.' + extension;
424 };
425
426 /**
427 * @method constructor
428 * @param {string} title Title of the page. If no second argument given,
429 * this will be searched for a namespace
430 * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
431 * @throws {Error} When the title is invalid
432 */
433 function Title( title, namespace ) {
434 var parsed = parse( title, namespace );
435 if ( !parsed ) {
436 throw new Error( 'Unable to parse title' );
437 }
438
439 this.namespace = parsed.namespace;
440 this.title = parsed.title;
441 this.ext = parsed.ext;
442 this.fragment = parsed.fragment;
443 }
444
445 /* Static members */
446
447 /**
448 * Constructor for Title objects with a null return instead of an exception for invalid titles.
449 *
450 * Note that `namespace` is the **default** namespace only, and can be overridden by a namespace
451 * prefix in `title`. If you do not want this behavior, use #makeTitle. See #constructor for
452 * details.
453 *
454 * @static
455 * @param {string} title
456 * @param {number} [namespace=NS_MAIN] Default namespace
457 * @return {mw.Title|null} A valid Title object or null if the title is invalid
458 */
459 Title.newFromText = function ( title, namespace ) {
460 var t, parsed = parse( title, namespace );
461 if ( !parsed ) {
462 return null;
463 }
464
465 t = Object.create( Title.prototype );
466 t.namespace = parsed.namespace;
467 t.title = parsed.title;
468 t.ext = parsed.ext;
469 t.fragment = parsed.fragment;
470
471 return t;
472 };
473
474 /**
475 * Constructor for Title objects with predefined namespace.
476 *
477 * Unlike #newFromText or #constructor, this function doesn't allow the given `namespace` to be
478 * overridden by a namespace prefix in `title`. See #constructor for details about this behavior.
479 *
480 * The single exception to this is when `namespace` is 0, indicating the main namespace. The
481 * function behaves like #newFromText in that case.
482 *
483 * @static
484 * @param {number} namespace Namespace to use for the title
485 * @param {string} title
486 * @return {mw.Title|null} A valid Title object or null if the title is invalid
487 */
488 Title.makeTitle = function ( namespace, title ) {
489 return mw.Title.newFromText( getNamespacePrefix( namespace ) + title );
490 };
491
492 /**
493 * Constructor for Title objects from user input altering that input to
494 * produce a title that MediaWiki will accept as legal
495 *
496 * @static
497 * @param {string} title
498 * @param {number} [defaultNamespace=NS_MAIN]
499 * If given, will used as default namespace for the given title.
500 * @param {Object} [options] additional options
501 * @param {boolean} [options.forUploading=true]
502 * Makes sure that a file is uploadable under the title returned.
503 * There are pages in the file namespace under which file upload is impossible.
504 * Automatically assumed if the title is created in the Media namespace.
505 * @return {mw.Title|null} A valid Title object or null if the input cannot be turned into a valid title
506 */
507 Title.newFromUserInput = function ( title, defaultNamespace, options ) {
508 var namespace, m, id, ext, parts;
509
510 // defaultNamespace is optional; check whether options moves up
511 if ( arguments.length < 3 && $.type( defaultNamespace ) === 'object' ) {
512 options = defaultNamespace;
513 defaultNamespace = undefined;
514 }
515
516 // merge options into defaults
517 options = $.extend( {
518 forUploading: true
519 }, options );
520
521 namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
522
523 // Normalise additional whitespace
524 title = title.replace( /\s/g, ' ' ).trim();
525
526 // Process initial colon
527 if ( title !== '' && title[ 0 ] === ':' ) {
528 // Initial colon means main namespace instead of specified default
529 namespace = NS_MAIN;
530 title = title
531 // Strip colon
532 .substr( 1 )
533 // Trim underscores
534 .replace( rUnderscoreTrim, '' );
535 }
536
537 // Process namespace prefix (if any)
538 m = title.match( rSplit );
539 if ( m ) {
540 id = getNsIdByName( m[ 1 ] );
541 if ( id !== false ) {
542 // Ordinary namespace
543 namespace = id;
544 title = m[ 2 ];
545 }
546 }
547
548 if (
549 namespace === NS_MEDIA ||
550 ( options.forUploading && ( namespace === NS_FILE ) )
551 ) {
552
553 title = sanitize( title, [ 'generalRule', 'fileRule' ] );
554
555 // Operate on the file extension
556 // Although it is possible having spaces between the name and the ".ext" this isn't nice for
557 // operating systems hiding file extensions -> strip them later on
558 parts = title.split( '.' );
559
560 if ( parts.length > 1 ) {
561
562 // Get the last part, which is supposed to be the file extension
563 ext = parts.pop();
564
565 // Remove whitespace of the name part (that W/O extension)
566 title = parts.join( '.' ).trim();
567
568 // Cut, if too long and append file extension
569 title = trimFileNameToByteLength( title, ext );
570
571 } else {
572
573 // Missing file extension
574 title = parts.join( '.' ).trim();
575
576 // Name has no file extension and a fallback wasn't provided either
577 return null;
578 }
579 } else {
580
581 title = sanitize( title, [ 'generalRule' ] );
582
583 // Cut titles exceeding the TITLE_MAX_BYTES byte size limit
584 // (size of underlying database field)
585 if ( namespace !== NS_SPECIAL ) {
586 title = trimToByteLength( title, TITLE_MAX_BYTES );
587 }
588 }
589
590 // Any remaining initial :s are illegal.
591 title = title.replace( /^:+/, '' );
592
593 return Title.newFromText( title, namespace );
594 };
595
596 /**
597 * Sanitizes a file name as supplied by the user, originating in the user's file system
598 * so it is most likely a valid MediaWiki title and file name after processing.
599 * Returns null on fatal errors.
600 *
601 * @static
602 * @param {string} uncleanName The unclean file name including file extension but
603 * without namespace
604 * @return {mw.Title|null} A valid Title object or null if the title is invalid
605 */
606 Title.newFromFileName = function ( uncleanName ) {
607
608 return Title.newFromUserInput( 'File:' + uncleanName, {
609 forUploading: true
610 } );
611 };
612
613 /**
614 * Get the file title from an image element
615 *
616 * var title = mw.Title.newFromImg( $( 'img:first' ) );
617 *
618 * @static
619 * @param {HTMLElement|jQuery} img The image to use as a base
620 * @return {mw.Title|null} The file title or null if unsuccessful
621 */
622 Title.newFromImg = function ( img ) {
623 var matches, i, regex, src, decodedSrc,
624
625 // thumb.php-generated thumbnails
626 thumbPhpRegex = /thumb\.php/,
627 regexes = [
628 // Thumbnails
629 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)\/[^\s/]+-[^\s/]*$/,
630
631 // Full size images
632 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s/]+)$/,
633
634 // Thumbnails in non-hashed upload directories
635 /\/([^\s/]+)\/[^\s/]+-(?:\1|thumbnail)[^\s/]*$/,
636
637 // Full-size images in non-hashed upload directories
638 /\/([^\s/]+)$/
639 ],
640
641 recount = regexes.length;
642
643 src = img.jquery ? img[ 0 ].src : img.src;
644
645 matches = src.match( thumbPhpRegex );
646
647 if ( matches ) {
648 return mw.Title.newFromText( 'File:' + mw.util.getParamValue( 'f', src ) );
649 }
650
651 decodedSrc = decodeURIComponent( src );
652
653 for ( i = 0; i < recount; i++ ) {
654 regex = regexes[ i ];
655 matches = decodedSrc.match( regex );
656
657 if ( matches && matches[ 1 ] ) {
658 return mw.Title.newFromText( 'File:' + matches[ 1 ] );
659 }
660 }
661
662 return null;
663 };
664
665 /**
666 * Check if a given namespace is a talk namespace
667 * @param {number} namespaceId Namespace ID
668 * @return {boolean} Namespace is a talk namespace
669 */
670 Title.isTalkNamespace = function ( namespaceId ) {
671 return !!( namespaceId > NS_MAIN && namespaceId % 2 );
672 };
673
674 /**
675 * Whether this title exists on the wiki.
676 *
677 * @static
678 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
679 * @return {boolean|null} Boolean if the information is available, otherwise null
680 * @throws {Error} If title is not a string or mw.Title
681 */
682 Title.exists = function ( title ) {
683 var match,
684 obj = Title.exist.pages;
685
686 if ( typeof title === 'string' ) {
687 match = obj[ title ];
688 } else if ( title instanceof Title ) {
689 match = obj[ title.toString() ];
690 } else {
691 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
692 }
693
694 if ( typeof match !== 'boolean' ) {
695 return null;
696 }
697
698 return match;
699 };
700
701 /**
702 * Store page existence
703 *
704 * @static
705 * @property {Object} exist
706 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
707 *
708 * @property {Function} exist.set The setter function.
709 *
710 * Example to declare existing titles:
711 *
712 * Title.exist.set( ['User:John_Doe', ...] );
713 *
714 * Example to declare titles nonexistent:
715 *
716 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
717 *
718 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
719 * @property {boolean} [exist.set.state=true] State of the given titles
720 * @return {boolean}
721 */
722 Title.exist = {
723 pages: {},
724
725 set: function ( titles, state ) {
726 var i, len,
727 pages = this.pages;
728
729 titles = Array.isArray( titles ) ? titles : [ titles ];
730 state = state === undefined ? true : !!state;
731
732 for ( i = 0, len = titles.length; i < len; i++ ) {
733 pages[ titles[ i ] ] = state;
734 }
735 return true;
736 }
737 };
738
739 /**
740 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
741 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
742 * Keep in sync with File::normalizeExtension() in PHP.
743 *
744 * @param {string} extension File extension (without the leading dot)
745 * @return {string} File extension in canonical form
746 */
747 Title.normalizeExtension = function ( extension ) {
748 var
749 lower = extension.toLowerCase(),
750 squish = {
751 htm: 'html',
752 jpeg: 'jpg',
753 mpeg: 'mpg',
754 tiff: 'tif',
755 ogv: 'ogg'
756 };
757 if ( Object.prototype.hasOwnProperty.call( squish, lower ) ) {
758 return squish[ lower ];
759 } else if ( /^[0-9a-z]+$/.test( lower ) ) {
760 return lower;
761 } else {
762 return '';
763 }
764 };
765
766 /* Public members */
767
768 Title.prototype = {
769 constructor: Title,
770
771 /**
772 * Get the namespace number
773 *
774 * Example: 6 for "File:Example_image.svg".
775 *
776 * @return {number}
777 */
778 getNamespaceId: function () {
779 return this.namespace;
780 },
781
782 /**
783 * Get the namespace prefix (in the content language)
784 *
785 * Example: "File:" for "File:Example_image.svg".
786 * In #NS_MAIN this is '', otherwise namespace name plus ':'
787 *
788 * @return {string}
789 */
790 getNamespacePrefix: function () {
791 return getNamespacePrefix( this.namespace );
792 },
793
794 /**
795 * Get the page name without extension or namespace prefix
796 *
797 * Example: "Example_image" for "File:Example_image.svg".
798 *
799 * For the page title (full page name without namespace prefix), see #getMain.
800 *
801 * @return {string}
802 */
803 getName: function () {
804 if (
805 mw.config.get( 'wgCaseSensitiveNamespaces' ).indexOf( this.namespace ) !== -1 ||
806 !this.title.length
807 ) {
808 return this.title;
809 }
810 // PHP's strtoupper differs from String.toUpperCase in a number of cases
811 // Bug: T147646
812 return mw.Title.phpCharToUpper( this.title[ 0 ] ) + this.title.slice( 1 );
813 },
814
815 /**
816 * Get the page name (transformed by #text)
817 *
818 * Example: "Example image" for "File:Example_image.svg".
819 *
820 * For the page title (full page name without namespace prefix), see #getMainText.
821 *
822 * @return {string}
823 */
824 getNameText: function () {
825 return text( this.getName() );
826 },
827
828 /**
829 * Get the extension of the page name (if any)
830 *
831 * @return {string|null} Name extension or null if there is none
832 */
833 getExtension: function () {
834 return this.ext;
835 },
836
837 /**
838 * Shortcut for appendable string to form the main page name.
839 *
840 * Returns a string like ".json", or "" if no extension.
841 *
842 * @return {string}
843 */
844 getDotExtension: function () {
845 return this.ext === null ? '' : '.' + this.ext;
846 },
847
848 /**
849 * Get the main page name
850 *
851 * Example: "Example_image.svg" for "File:Example_image.svg".
852 *
853 * @return {string}
854 */
855 getMain: function () {
856 return this.getName() + this.getDotExtension();
857 },
858
859 /**
860 * Get the main page name (transformed by #text)
861 *
862 * Example: "Example image.svg" for "File:Example_image.svg".
863 *
864 * @return {string}
865 */
866 getMainText: function () {
867 return text( this.getMain() );
868 },
869
870 /**
871 * Get the full page name
872 *
873 * Example: "File:Example_image.svg".
874 * Most useful for API calls, anything that must identify the "title".
875 *
876 * @return {string}
877 */
878 getPrefixedDb: function () {
879 return this.getNamespacePrefix() + this.getMain();
880 },
881
882 /**
883 * Get the full page name (transformed by #text)
884 *
885 * Example: "File:Example image.svg" for "File:Example_image.svg".
886 *
887 * @return {string}
888 */
889 getPrefixedText: function () {
890 return text( this.getPrefixedDb() );
891 },
892
893 /**
894 * Get the page name relative to a namespace
895 *
896 * Example:
897 *
898 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
899 * - "Bar" relative to any non-main namespace becomes ":Bar".
900 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
901 *
902 * @param {number} namespace The namespace to be relative to
903 * @return {string}
904 */
905 getRelativeText: function ( namespace ) {
906 if ( this.getNamespaceId() === namespace ) {
907 return this.getMainText();
908 } else if ( this.getNamespaceId() === NS_MAIN ) {
909 return ':' + this.getPrefixedText();
910 } else {
911 return this.getPrefixedText();
912 }
913 },
914
915 /**
916 * Get the fragment (if any).
917 *
918 * Note that this method (by design) does not include the hash character and
919 * the value is not url encoded.
920 *
921 * @return {string|null}
922 */
923 getFragment: function () {
924 return this.fragment;
925 },
926
927 /**
928 * Get the URL to this title
929 *
930 * @see mw.util#getUrl
931 * @param {Object} [params] A mapping of query parameter names to values,
932 * e.g. `{ action: 'edit' }`.
933 * @return {string}
934 */
935 getUrl: function ( params ) {
936 var fragment = this.getFragment();
937 if ( fragment ) {
938 return mw.util.getUrl( this.toString() + '#' + fragment, params );
939 } else {
940 return mw.util.getUrl( this.toString(), params );
941 }
942 },
943
944 /**
945 * Check if the title is in a talk namespace
946 *
947 * @return {boolean} The title is in a talk namespace
948 */
949 isTalkPage: function () {
950 return Title.isTalkNamespace( this.getNamespaceId() );
951 },
952
953 /**
954 * Get the title for the associated talk page
955 *
956 * @return {mw.Title|null} The title for the associated talk page, null if not available
957 */
958 getTalkPage: function () {
959 if ( !this.canHaveTalkPage() ) {
960 return null;
961 }
962 return this.isTalkPage() ?
963 this :
964 Title.makeTitle( this.getNamespaceId() + 1, this.getMainText() );
965 },
966
967 /**
968 * Get the title for the subject page of a talk page
969 *
970 * @return {mw.Title|null} The title for the subject page of a talk page, null if not available
971 */
972 getSubjectPage: function () {
973 return this.isTalkPage() ?
974 Title.makeTitle( this.getNamespaceId() - 1, this.getMainText() ) :
975 this;
976 },
977
978 /**
979 * Check the the title can have an associated talk page
980 *
981 * @return {boolean} The title can have an associated talk page
982 */
983 canHaveTalkPage: function () {
984 return this.getNamespaceId() >= NS_MAIN;
985 },
986
987 /**
988 * Whether this title exists on the wiki.
989 *
990 * @see #static-method-exists
991 * @return {boolean|null} Boolean if the information is available, otherwise null
992 */
993 exists: function () {
994 return Title.exists( this );
995 }
996 };
997
998 /**
999 * @alias #getPrefixedDb
1000 * @method
1001 */
1002 Title.prototype.toString = Title.prototype.getPrefixedDb;
1003
1004 /**
1005 * @alias #getPrefixedText
1006 * @method
1007 */
1008 Title.prototype.toText = Title.prototype.getPrefixedText;
1009
1010 // Expose
1011 mw.Title = Title;
1012
1013 }() );