Remove unused $entryPoint from Preferences::tryFormSubmit
[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 #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 .substr( 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 .substr( 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 .substr( 0, i )
178 // Trim underscores, again (strips "_" from "bar" in "Foo_bar_#quux")
179 .replace( rUnderscoreTrim, '' );
180 }
181
182
183 // Reject illegal characters
184 if ( title.match( rInvalid ) ) {
185 return false;
186 }
187
188 // Disallow titles that browsers or servers might resolve as directory navigation
189 if (
190 title.indexOf( '.' ) !== -1 && (
191 title === '.' || title === '..' ||
192 title.indexOf( './' ) === 0 ||
193 title.indexOf( '../' ) === 0 ||
194 title.indexOf( '/./' ) !== -1 ||
195 title.indexOf( '/../' ) !== -1 ||
196 title.substr( title.length - 2 ) === '/.' ||
197 title.substr( title.length - 3 ) === '/..'
198 )
199 ) {
200 return false;
201 }
202
203 // Disallow magic tilde sequence
204 if ( title.indexOf( '~~~' ) !== -1 ) {
205 return false;
206 }
207
208 // Disallow titles exceeding the 255 byte size limit (size of underlying database field)
209 // Except for special pages, e.g. [[Special:Block/Long name]]
210 // Note: The PHP implementation also asserts that even in NS_SPECIAL, the title should
211 // be less than 512 bytes.
212 if ( namespace !== NS_SPECIAL && $.byteLength( title ) > 255 ) {
213 return false;
214 }
215
216 // Can't make a link to a namespace alone.
217 if ( title === '' && namespace !== NS_MAIN ) {
218 return false;
219 }
220
221 // Any remaining initial :s are illegal.
222 if ( title.charAt( 0 ) === ':' ) {
223 return false;
224 }
225
226 // For backwards-compatibility with old mw.Title, we separate the extension from the
227 // rest of the title.
228 i = title.lastIndexOf( '.' );
229 if ( i === -1 || title.length <= i + 1 ) {
230 // Extensions are the non-empty segment after the last dot
231 ext = null;
232 } else {
233 ext = title.substr( i + 1 );
234 title = title.substr( 0, i );
235 }
236
237 return {
238 namespace: namespace,
239 title: title,
240 ext: ext,
241 fragment: fragment
242 };
243 },
244
245 /**
246 * Convert db-key to readable text.
247 *
248 * @private
249 * @static
250 * @method text
251 * @param {string} s
252 * @return {string}
253 */
254 text = function ( s ) {
255 if ( s !== null && s !== undefined ) {
256 return s.replace( /_/g, ' ' );
257 } else {
258 return '';
259 }
260 },
261
262 // Polyfill for ES5 Object.create
263 createObject = Object.create || ( function () {
264 return function ( o ) {
265 function Title() {}
266 if ( o !== Object( o ) ) {
267 throw new Error( 'Cannot inherit from a non-object' );
268 }
269 Title.prototype = o;
270 return new Title();
271 };
272 }() );
273
274
275 /* Static members */
276
277 /**
278 * Constructor for Title objects with a null return instead of an exception for invalid titles.
279 *
280 * @static
281 * @method
282 * @param {string} title
283 * @param {number} [namespace=NS_MAIN] Default namespace
284 * @return {mw.Title|null} A valid Title object or null if the title is invalid
285 */
286 Title.newFromText = function ( title, namespace ) {
287 var t, parsed = parse( title, namespace );
288 if ( !parsed ) {
289 return null;
290 }
291
292 t = createObject( Title.prototype );
293 t.namespace = parsed.namespace;
294 t.title = parsed.title;
295 t.ext = parsed.ext;
296 t.fragment = parsed.fragment;
297
298 return t;
299 };
300
301 /**
302 * Get the file title from an image element
303 *
304 * var title = mw.Title.newFromImg( $( 'img:first' ) );
305 *
306 * @static
307 * @param {HTMLElement|jQuery} img The image to use as a base
308 * @return {mw.Title|null} The file title or null if unsuccessful
309 */
310 Title.newFromImg = function ( img ) {
311 var matches, i, regex, src, decodedSrc,
312
313 // thumb.php-generated thumbnails
314 thumbPhpRegex = /thumb\.php/,
315 regexes = [
316 // Thumbnails
317 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
318
319 // Thumbnails in non-hashed upload directories
320 /\/([^\s\/]+)\/[^\s\/]+-(?:\1|thumbnail)[^\s\/]*$/,
321
322 // Full size images
323 /\/[a-f0-9]\/[a-f0-9]{2}\/([^\s\/]+)$/,
324
325 // Full-size images in non-hashed upload directories
326 /\/([^\s\/]+)$/
327 ],
328
329 recount = regexes.length;
330
331 src = img.jquery ? img[0].src : img.src;
332
333 matches = src.match( thumbPhpRegex );
334
335 if ( matches ) {
336 return mw.Title.newFromText( 'File:' + mw.util.getParamValue( 'f', src ) );
337 }
338
339 decodedSrc = decodeURIComponent( src );
340
341 for ( i = 0; i < recount; i++ ) {
342 regex = regexes[i];
343 matches = decodedSrc.match( regex );
344
345 if ( matches && matches[1] ) {
346 return mw.Title.newFromText( 'File:' + matches[1] );
347 }
348 }
349
350 return null;
351 };
352
353 /**
354 * Whether this title exists on the wiki.
355 *
356 * @static
357 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
358 * @return {boolean|null} Boolean if the information is available, otherwise null
359 */
360 Title.exists = function ( title ) {
361 var match,
362 type = $.type( title ),
363 obj = Title.exist.pages;
364
365 if ( type === 'string' ) {
366 match = obj[title];
367 } else if ( type === 'object' && title instanceof Title ) {
368 match = obj[title.toString()];
369 } else {
370 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
371 }
372
373 if ( typeof match === 'boolean' ) {
374 return match;
375 }
376
377 return null;
378 };
379
380 Title.exist = {
381 /**
382 * Boolean true value indicates page does exist.
383 *
384 * @static
385 * @property {Object} exist.pages Keyed by PrefixedDb title.
386 */
387 pages: {},
388
389 /**
390 * Example to declare existing titles:
391 * Title.exist.set( ['User:John_Doe', ...] );
392 * Eample to declare titles nonexistent:
393 * Title.exist.set( ['File:Foo_bar.jpg', ...], false );
394 *
395 * @static
396 * @property exist.set
397 * @param {string|Array} titles Title(s) in strict prefixedDb title form
398 * @param {boolean} [state=true] State of the given titles
399 * @return {boolean}
400 */
401 set: function ( titles, state ) {
402 titles = $.isArray( titles ) ? titles : [titles];
403 state = state === undefined ? true : !!state;
404 var pages = this.pages, i, len = titles.length;
405 for ( i = 0; i < len; i++ ) {
406 pages[ titles[i] ] = state;
407 }
408 return true;
409 }
410 };
411
412 /* Public members */
413
414 Title.prototype = {
415 constructor: Title,
416
417 /**
418 * Get the namespace number
419 *
420 * Example: 6 for "File:Example_image.svg".
421 *
422 * @return {number}
423 */
424 getNamespaceId: function () {
425 return this.namespace;
426 },
427
428 /**
429 * Get the namespace prefix (in the content language)
430 *
431 * Example: "File:" for "File:Example_image.svg".
432 * In #NS_MAIN this is '', otherwise namespace name plus ':'
433 *
434 * @return {string}
435 */
436 getNamespacePrefix: function () {
437 return this.namespace === NS_MAIN ?
438 '' :
439 ( mw.config.get( 'wgFormattedNamespaces' )[ this.namespace ].replace( / /g, '_' ) + ':' );
440 },
441
442 /**
443 * Get the page name without extension or namespace prefix
444 *
445 * Example: "Example_image" for "File:Example_image.svg".
446 *
447 * For the page title (full page name without namespace prefix), see #getMain.
448 *
449 * @return {string}
450 */
451 getName: function () {
452 if ( $.inArray( this.namespace, mw.config.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ) {
453 return this.title;
454 } else {
455 return $.ucFirst( this.title );
456 }
457 },
458
459 /**
460 * Get the page name (transformed by #text)
461 *
462 * Example: "Example image" for "File:Example_image.svg".
463 *
464 * For the page title (full page name without namespace prefix), see #getMainText.
465 *
466 * @return {string}
467 */
468 getNameText: function () {
469 return text( this.getName() );
470 },
471
472 /**
473 * Get the extension of the page name (if any)
474 *
475 * @return {string|null} Name extension or null if there is none
476 */
477 getExtension: function () {
478 return this.ext;
479 },
480
481 /**
482 * Shortcut for appendable string to form the main page name.
483 *
484 * Returns a string like ".json", or "" if no extension.
485 *
486 * @return {string}
487 */
488 getDotExtension: function () {
489 return this.ext === null ? '' : '.' + this.ext;
490 },
491
492 /**
493 * Get the main page name (transformed by #text)
494 *
495 * Example: "Example_image.svg" for "File:Example_image.svg".
496 *
497 * @return {string}
498 */
499 getMain: function () {
500 return this.getName() + this.getDotExtension();
501 },
502
503 /**
504 * Get the main page name (transformed by #text)
505 *
506 * Example: "Example image.svg" for "File:Example_image.svg".
507 *
508 * @return {string}
509 */
510 getMainText: function () {
511 return text( this.getMain() );
512 },
513
514 /**
515 * Get the full page name
516 *
517 * Eaxample: "File:Example_image.svg".
518 * Most useful for API calls, anything that must identify the "title".
519 *
520 * @return {string}
521 */
522 getPrefixedDb: function () {
523 return this.getNamespacePrefix() + this.getMain();
524 },
525
526 /**
527 * Get the full page name (transformed by #text)
528 *
529 * Example: "File:Example image.svg" for "File:Example_image.svg".
530 *
531 * @return {string}
532 */
533 getPrefixedText: function () {
534 return text( this.getPrefixedDb() );
535 },
536
537 /**
538 * Get the fragment (if any).
539 *
540 * Note that this method (by design) does not include the hash character and
541 * the value is not url encoded.
542 *
543 * @return {string|null}
544 */
545 getFragment: function () {
546 return this.fragment;
547 },
548
549 /**
550 * Get the URL to this title
551 *
552 * @see mw.util#getUrl
553 * @param {Object} [params] A mapping of query parameter names to values,
554 * e.g. `{ action: 'edit' }`.
555 * @return {string}
556 */
557 getUrl: function ( params ) {
558 return mw.util.getUrl( this.toString(), params );
559 },
560
561 /**
562 * Whether this title exists on the wiki.
563 *
564 * @see #static-method-exists
565 * @return {boolean|null} Boolean if the information is available, otherwise null
566 */
567 exists: function () {
568 return Title.exists( this );
569 }
570 };
571
572 /**
573 * @alias #getPrefixedDb
574 * @method
575 */
576 Title.prototype.toString = Title.prototype.getPrefixedDb;
577
578
579 /**
580 * @alias #getPrefixedText
581 * @method
582 */
583 Title.prototype.toText = Title.prototype.getPrefixedText;
584
585 // Expose
586 mw.Title = Title;
587
588 }( mediaWiki, jQuery ) );