mw.Title: Add method to get title relative to an arbitrary namespace
[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 ( function ( mw, $ ) {
7
8 /**
9 * @class mw.Title
10 *
11 * Parse titles into an object struture. 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 * @constructor
16 * @param {string} title Title of the page. If no second argument given,
17 * this will be searched for a namespace
18 * @param {number} [namespace=NS_MAIN] If given, will used as default namespace for the given title
19 * @throws {Error} When the title is invalid
20 */
21 function Title( title, namespace ) {
22 var parsed = parse( title, namespace );
23 if ( !parsed ) {
24 throw new Error( 'Unable to parse title' );
25 }
26
27 this.namespace = parsed.namespace;
28 this.title = parsed.title;
29 this.ext = parsed.ext;
30 this.fragment = parsed.fragment;
31
32 return this;
33 }
34
35 /* Private members */
36
37 var
38
39 /**
40 * @private
41 * @static
42 * @property NS_MAIN
43 */
44 NS_MAIN = 0,
45
46 /**
47 * @private
48 * @static
49 * @property NS_TALK
50 */
51 NS_TALK = 1,
52
53 /**
54 * @private
55 * @static
56 * @property NS_SPECIAL
57 */
58 NS_SPECIAL = -1,
59
60 /**
61 * Get the namespace id from a namespace name (either from the localized, canonical or alias
62 * name).
63 *
64 * Example: On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or
65 * even 'Bild'.
66 *
67 * @private
68 * @static
69 * @method getNsIdByName
70 * @param {string} ns Namespace name (case insensitive, leading/trailing space ignored)
71 * @return {number|boolean} Namespace id or boolean false
72 */
73 getNsIdByName = function ( ns ) {
74 var id;
75
76 // Don't cast non-strings to strings, because null or undefined should not result in
77 // returning the id of a potential namespace called "Null:" (e.g. on null.example.org/wiki)
78 // Also, toLowerCase throws exception on null/undefined, because it is a String method.
79 if ( typeof ns !== 'string' ) {
80 return false;
81 }
82 ns = ns.toLowerCase();
83 id = mw.config.get( 'wgNamespaceIds' )[ns];
84 if ( id === undefined ) {
85 return false;
86 }
87 return id;
88 },
89
90 rUnderscoreTrim = /^_+|_+$/g,
91
92 rSplit = /^(.+?)_*:_*(.*)$/,
93
94 // See Title.php#getTitleInvalidRegex
95 rInvalid = new RegExp(
96 '[^' + mw.config.get( 'wgLegalTitleChars' ) + ']' +
97 // URL percent encoding sequences interfere with the ability
98 // to round-trip titles -- you can't link to them consistently.
99 '|%[0-9A-Fa-f]{2}' +
100 // XML/HTML character references produce similar issues.
101 '|&[A-Za-z0-9\u0080-\uFFFF]+;' +
102 '|&#[0-9]+;' +
103 '|&#x[0-9A-Fa-f]+;'
104 ),
105
106 /**
107 * Internal helper for #constructor and #newFromtext.
108 *
109 * Based on Title.php#secureAndSplit
110 *
111 * @private
112 * @static
113 * @method parse
114 * @param {string} title
115 * @param {number} [defaultNamespace=NS_MAIN]
116 * @return {Object|boolean}
117 */
118 parse = function ( title, defaultNamespace ) {
119 var namespace, m, id, i, fragment, ext;
120
121 namespace = defaultNamespace === undefined ? NS_MAIN : defaultNamespace;
122
123 title = title
124 // Normalise whitespace to underscores and remove duplicates
125 .replace( /[ _\s]+/g, '_' )
126 // Trim underscores
127 .replace( rUnderscoreTrim, '' );
128
129 // Process initial colon
130 if ( title !== '' && title.charAt( 0 ) === ':' ) {
131 // Initial colon means main namespace instead of specified default
132 namespace = NS_MAIN;
133 title = title
134 // Strip colon
135 .slice( 1 )
136 // Trim underscores
137 .replace( rUnderscoreTrim, '' );
138 }
139
140 if ( title === '' ) {
141 return false;
142 }
143
144 // Process namespace prefix (if any)
145 m = title.match( rSplit );
146 if ( m ) {
147 id = getNsIdByName( m[1] );
148 if ( id !== false ) {
149 // Ordinary namespace
150 namespace = id;
151 title = m[2];
152
153 // For Talk:X pages, make sure X has no "namespace" prefix
154 if ( namespace === NS_TALK && ( m = title.match( rSplit ) ) ) {
155 // Disallow titles like Talk:File:x (subject should roundtrip: talk:file:x -> file:x -> file_talk:x)
156 if ( getNsIdByName( m[1] ) !== false ) {
157 return false;
158 }
159 }
160 }
161 }
162
163 // Process fragment
164 i = title.indexOf( '#' );
165 if ( i === -1 ) {
166 fragment = null;
167 } else {
168 fragment = title
169 // Get segment starting after the hash
170 .slice( i + 1 )
171 // Convert to text
172 // NB: Must not be trimmed ("Example#_foo" is not the same as "Example#foo")
173 .replace( /_/g, ' ' );
174
175 title = title
176 // Strip hash
177 .slice( 0, i )
178 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
179 .replace( rUnderscoreTrim, '' );
180 }
181
182 // Reject illegal characters
183 if ( title.match( rInvalid ) ) {
184 return false;
185 }
186
187 // Disallow titles that browsers or servers might resolve as directory navigation
188 if (
189 title.indexOf( '.' ) !== -1 && (
190 title === '.' || title === '..' ||
191 title.indexOf( './' ) === 0 ||
192 title.indexOf( '../' ) === 0 ||
193 title.indexOf( '/./' ) !== -1 ||
194 title.indexOf( '/../' ) !== -1 ||
195 title.slice( -2 ) === '/.' ||
196 title.slice( -3 ) === '/..'
197 )
198 ) {
199 return false;
200 }
201
202 // Disallow magic tilde sequence
203 if ( title.indexOf( '~~~' ) !== -1 ) {
204 return false;
205 }
206
207 // Disallow titles exceeding the 255 byte size limit (size of underlying database field)
208 // Except for special pages, e.g. [[Special:Block/Long name]]
209 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
210 // be less than 512 bytes.
211 if ( namespace !== NS_SPECIAL && $.byteLength( title ) > 255 ) {
212 return false;
213 }
214
215 // Can't make a link to a namespace alone.
216 if ( title === '' && namespace !== NS_MAIN ) {
217 return false;
218 }
219
220 // Any remaining initial :s are illegal.
221 if ( title.charAt( 0 ) === ':' ) {
222 return false;
223 }
224
225 // For backwards-compatibility with old mw.Title, we separate the extension from the
226 // rest of the title.
227 i = title.lastIndexOf( '.' );
228 if ( i === -1 || title.length <= i + 1 ) {
229 // Extensions are the non-empty segment after the last dot
230 ext = null;
231 } else {
232 ext = title.slice( i + 1 );
233 title = title.slice( 0, i );
234 }
235
236 return {
237 namespace: namespace,
238 title: title,
239 ext: ext,
240 fragment: fragment
241 };
242 },
243
244 /**
245 * Convert db-key to readable text.
246 *
247 * @private
248 * @static
249 * @method text
250 * @param {string} s
251 * @return {string}
252 */
253 text = function ( s ) {
254 if ( s !== null && s !== undefined ) {
255 return s.replace( /_/g, ' ' );
256 } else {
257 return '';
258 }
259 },
260
261 // Polyfill for ES5 Object.create
262 createObject = Object.create || ( function () {
263 return function ( o ) {
264 function Title() {}
265 if ( o !== Object( o ) ) {
266 throw new Error( 'Cannot inherit from a non-object' );
267 }
268 Title.prototype = o;
269 return new Title();
270 };
271 }() );
272
273 /* Static members */
274
275 /**
276 * Constructor for Title objects with a null return instead of an exception for invalid titles.
277 *
278 * @static
279 * @method
280 * @param {string} title
281 * @param {number} [namespace=NS_MAIN] Default namespace
282 * @return {mw.Title|null} A valid Title object or null if the title is invalid
283 */
284 Title.newFromText = function ( title, namespace ) {
285 var t, parsed = parse( title, namespace );
286 if ( !parsed ) {
287 return null;
288 }
289
290 t = createObject( Title.prototype );
291 t.namespace = parsed.namespace;
292 t.title = parsed.title;
293 t.ext = parsed.ext;
294 t.fragment = parsed.fragment;
295
296 return t;
297 };
298
299 /**
300 * Get the file title from an image element
301 *
302 * var title = mw.Title.newFromImg( $( 'img:first' ) );
303 *
304 * @static
305 * @param {HTMLElement|jQuery} img The image to use as a base
306 * @return {mw.Title|null} The file title or null if unsuccessful
307 */
308 Title.newFromImg = function ( img ) {
309 var matches, i, regex, src, decodedSrc,
310
311 // thumb.php-generated thumbnails
312 thumbPhpRegex = /thumb\.php/,
313 regexes = [
314 // Thumbnails
315 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
316
317 // Thumbnails in non-hashed upload directories
318 /\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
319
320 // Full size images
321 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
322
323 // Full-size images in non-hashed upload directories
324 /\/([^\s\/]+)$/
325 ],
326
327 recount = regexes.length;
328
329 src = img.jquery ? img[0].src : img.src;
330
331 matches = src.match( thumbPhpRegex );
332
333 if ( matches ) {
334 return mw.Title.newFromText( 'File:' + mw.util.getParamValue( 'f', src ) );
335 }
336
337 decodedSrc = decodeURIComponent( src );
338
339 for ( i = 0; i < recount; i++ ) {
340 regex = regexes[i];
341 matches = decodedSrc.match( regex );
342
343 if ( matches && matches[1] ) {
344 return mw.Title.newFromText( 'File:' + matches[1] );
345 }
346 }
347
348 return null;
349 };
350
351 /**
352 * Whether this title exists on the wiki.
353 *
354 * @static
355 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
356 * @return {boolean|null} Boolean if the information is available, otherwise null
357 */
358 Title.exists = function ( title ) {
359 var match,
360 type = $.type( title ),
361 obj = Title.exist.pages;
362
363 if ( type === 'string' ) {
364 match = obj[title];
365 } else if ( type === 'object' && title instanceof Title ) {
366 match = obj[title.toString()];
367 } else {
368 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
369 }
370
371 if ( typeof match === 'boolean' ) {
372 return match;
373 }
374
375 return null;
376 };
377
378 /**
379 * Store page existence
380 *
381 * @static
382 * @property {Object} exist
383 * @property {Object} exist.pages Keyed by title. Boolean true value indicates page does exist.
384 *
385 * @property {Function} exist.set The setter function.
386 *
387 * Example to declare existing titles:
388 *
389 * Title.exist.set( ['User:John_Doe', ...] );
390 *
391 * Example to declare titles nonexistent:
392 *
393 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
394 *
395 * @property {string|Array} exist.set.titles Title(s) in strict prefixedDb title form
396 * @property {boolean} [exist.set.state=true] State of the given titles
397 * @return {boolean}
398 */
399 Title.exist = {
400 pages: {},
401
402 set: function ( titles, state ) {
403 titles = $.isArray( titles ) ? titles : [titles];
404 state = state === undefined ? true : !!state;
405 var pages = this.pages, i, len = titles.length;
406 for ( i = 0; i < len; i++ ) {
407 pages[ titles[i] ] = state;
408 }
409 return true;
410 }
411 };
412
413 /* Public members */
414
415 Title.prototype = {
416 constructor: Title,
417
418 /**
419 * Get the namespace number
420 *
421 * Example: 6 for "File:Example_image.svg".
422 *
423 * @return {number}
424 */
425 getNamespaceId: function () {
426 return this.namespace;
427 },
428
429 /**
430 * Get the namespace prefix (in the content language)
431 *
432 * Example: "File:" for "File:Example_image.svg".
433 * In #NS_MAIN this is '', otherwise namespace name plus ':'
434 *
435 * @return {string}
436 */
437 getNamespacePrefix: function () {
438 return this.namespace === NS_MAIN ?
439 '' :
440 ( mw.config.get( 'wgFormattedNamespaces' )[ this.namespace ].replace( / /g, '_' ) + ':' );
441 },
442
443 /**
444 * Get the page name without extension or namespace prefix
445 *
446 * Example: "Example_image" for "File:Example_image.svg".
447 *
448 * For the page title (full page name without namespace prefix), see #getMain.
449 *
450 * @return {string}
451 */
452 getName: function () {
453 if ( $.inArray( this.namespace, mw.config.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ) {
454 return this.title;
455 } else {
456 return $.ucFirst( this.title );
457 }
458 },
459
460 /**
461 * Get the page name (transformed by #text)
462 *
463 * Example: "Example image" for "File:Example_image.svg".
464 *
465 * For the page title (full page name without namespace prefix), see #getMainText.
466 *
467 * @return {string}
468 */
469 getNameText: function () {
470 return text( this.getName() );
471 },
472
473 /**
474 * Get the extension of the page name (if any)
475 *
476 * @return {string|null} Name extension or null if there is none
477 */
478 getExtension: function () {
479 return this.ext;
480 },
481
482 /**
483 * Shortcut for appendable string to form the main page name.
484 *
485 * Returns a string like ".json", or "" if no extension.
486 *
487 * @return {string}
488 */
489 getDotExtension: function () {
490 return this.ext === null ? '' : '.' + this.ext;
491 },
492
493 /**
494 * Get the main page name
495 *
496 * Example: "Example_image.svg" for "File:Example_image.svg".
497 *
498 * @return {string}
499 */
500 getMain: function () {
501 return this.getName() + this.getDotExtension();
502 },
503
504 /**
505 * Get the main page name (transformed by #text)
506 *
507 * Example: "Example image.svg" for "File:Example_image.svg".
508 *
509 * @return {string}
510 */
511 getMainText: function () {
512 return text( this.getMain() );
513 },
514
515 /**
516 * Get the full page name
517 *
518 * Example: "File:Example_image.svg".
519 * Most useful for API calls, anything that must identify the "title".
520 *
521 * @return {string}
522 */
523 getPrefixedDb: function () {
524 return this.getNamespacePrefix() + this.getMain();
525 },
526
527 /**
528 * Get the full page name (transformed by #text)
529 *
530 * Example: "File:Example image.svg" for "File:Example_image.svg".
531 *
532 * @return {string}
533 */
534 getPrefixedText: function () {
535 return text( this.getPrefixedDb() );
536 },
537
538 /**
539 * Get the page name relative to a namespace
540 *
541 * Example:
542 *
543 * - "Foo:Bar" relative to the Foo namespace becomes "Bar".
544 * - "Bar" relative to any non-main namespace becomes ":Bar".
545 * - "Foo:Bar" relative to any namespace other than Foo stays "Foo:Bar".
546 *
547 * @param {number} namespace The namespace to be relative to
548 * @return {string}
549 */
550 getRelativeText: function ( namespace ) {
551 if ( this.getNamespaceId() === namespace ) {
552 return this.getMainText();
553 } else if ( this.getNamespaceId() === NS_MAIN ) {
554 return ':' + this.getPrefixedText();
555 } else {
556 return this.getPrefixedText();
557 }
558 },
559
560 /**
561 * Get the fragment (if any).
562 *
563 * Note that this method (by design) does not include the hash character and
564 * the value is not url encoded.
565 *
566 * @return {string|null}
567 */
568 getFragment: function () {
569 return this.fragment;
570 },
571
572 /**
573 * Get the URL to this title
574 *
575 * @see mw.util#getUrl
576 * @param {Object} [params] A mapping of query parameter names to values,
577 * e.g. `{ action: 'edit' }`.
578 * @return {string}
579 */
580 getUrl: function ( params ) {
581 return mw.util.getUrl( this.toString(), params );
582 },
583
584 /**
585 * Whether this title exists on the wiki.
586 *
587 * @see #static-method-exists
588 * @return {boolean|null} Boolean if the information is available, otherwise null
589 */
590 exists: function () {
591 return Title.exists( this );
592 }
593 };
594
595 /**
596 * @alias #getPrefixedDb
597 * @method
598 */
599 Title.prototype.toString = Title.prototype.getPrefixedDb;
600
601 /**
602 * @alias #getPrefixedText
603 * @method
604 */
605 Title.prototype.toText = Title.prototype.getPrefixedText;
606
607 // Expose
608 mw.Title = Title;
609
610 }( mediaWiki, jQuery ) );