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