Merge "LESS embeddable(): Use lessc::toBool"
[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 * Whether this title exists on the wiki.
304 *
305 * @static
306 * @param {string|mw.Title} title prefixed db-key name (string) or instance of Title
307 * @return {boolean|null} Boolean if the information is available, otherwise null
308 */
309 Title.exists = function ( title ) {
310 var match,
311 type = $.type( title ),
312 obj = Title.exist.pages;
313
314 if ( type === 'string' ) {
315 match = obj[title];
316 } else if ( type === 'object' && title instanceof Title ) {
317 match = obj[title.toString()];
318 } else {
319 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
320 }
321
322 if ( typeof match === 'boolean' ) {
323 return match;
324 }
325
326 return null;
327 };
328
329 Title.exist = {
330 /**
331 * Boolean true value indicates page does exist.
332 *
333 * @static
334 * @property {Object} exist.pages Keyed by PrefixedDb title.
335 */
336 pages: {},
337
338 /**
339 * Example to declare existing titles:
340 * Title.exist.set(['User:John_Doe', ...]);
341 * Eample to declare titles nonexistent:
342 * Title.exist.set(['File:Foo_bar.jpg', ...], false);
343 *
344 * @static
345 * @property exist.set
346 * @param {string|Array} titles Title(s) in strict prefixedDb title form
347 * @param {boolean} [state=true] State of the given titles
348 * @return {boolean}
349 */
350 set: function ( titles, state ) {
351 titles = $.isArray( titles ) ? titles : [titles];
352 state = state === undefined ? true : !!state;
353 var pages = this.pages, i, len = titles.length;
354 for ( i = 0; i < len; i++ ) {
355 pages[ titles[i] ] = state;
356 }
357 return true;
358 }
359 };
360
361 /* Public members */
362
363 Title.prototype = {
364 constructor: Title,
365
366 /**
367 * Get the namespace number
368 *
369 * Example: 6 for "File:Example_image.svg".
370 *
371 * @return {number}
372 */
373 getNamespaceId: function () {
374 return this.namespace;
375 },
376
377 /**
378 * Get the namespace prefix (in the content language)
379 *
380 * Example: "File:" for "File:Example_image.svg".
381 * In #NS_MAIN this is '', otherwise namespace name plus ':'
382 *
383 * @return {string}
384 */
385 getNamespacePrefix: function () {
386 return this.namespace === NS_MAIN ?
387 '' :
388 ( mw.config.get( 'wgFormattedNamespaces' )[ this.namespace ].replace( / /g, '_' ) + ':' );
389 },
390
391 /**
392 * Get the page name without extension or namespace prefix
393 *
394 * Example: "Example_image" for "File:Example_image.svg".
395 *
396 * For the page title (full page name without namespace prefix), see #getMain.
397 *
398 * @return {string}
399 */
400 getName: function () {
401 if ( $.inArray( this.namespace, mw.config.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ) {
402 return this.title;
403 } else {
404 return $.ucFirst( this.title );
405 }
406 },
407
408 /**
409 * Get the page name (transformed by #text)
410 *
411 * Example: "Example image" for "File:Example_image.svg".
412 *
413 * For the page title (full page name without namespace prefix), see #getMainText.
414 *
415 * @return {string}
416 */
417 getNameText: function () {
418 return text( this.getName() );
419 },
420
421 /**
422 * Get the extension of the page name (if any)
423 *
424 * @return {string|null} Name extension or null if there is none
425 */
426 getExtension: function () {
427 return this.ext;
428 },
429
430 /**
431 * Shortcut for appendable string to form the main page name.
432 *
433 * Returns a string like ".json", or "" if no extension.
434 *
435 * @return {string}
436 */
437 getDotExtension: function () {
438 return this.ext === null ? '' : '.' + this.ext;
439 },
440
441 /**
442 * Get the main page name (transformed by #text)
443 *
444 * Example: "Example_image.svg" for "File:Example_image.svg".
445 *
446 * @return {string}
447 */
448 getMain: function () {
449 return this.getName() + this.getDotExtension();
450 },
451
452 /**
453 * Get the main page name (transformed by #text)
454 *
455 * Example: "Example image.svg" for "File:Example_image.svg".
456 *
457 * @return {string}
458 */
459 getMainText: function () {
460 return text( this.getMain() );
461 },
462
463 /**
464 * Get the full page name
465 *
466 * Eaxample: "File:Example_image.svg".
467 * Most useful for API calls, anything that must identify the "title".
468 *
469 * @return {string}
470 */
471 getPrefixedDb: function () {
472 return this.getNamespacePrefix() + this.getMain();
473 },
474
475 /**
476 * Get the full page name (transformed by #text)
477 *
478 * Example: "File:Example image.svg" for "File:Example_image.svg".
479 *
480 * @return {string}
481 */
482 getPrefixedText: function () {
483 return text( this.getPrefixedDb() );
484 },
485
486 /**
487 * Get the fragment (if any).
488 *
489 * Note that this method (by design) does not include the hash character and
490 * the value is not url encoded.
491 *
492 * @return {string|null}
493 */
494 getFragment: function () {
495 return this.fragment;
496 },
497
498 /**
499 * Get the URL to this title
500 *
501 * @see mw.util#wikiGetlink
502 * @return {string}
503 */
504 getUrl: function () {
505 return mw.util.wikiGetlink( this.toString() );
506 },
507
508 /**
509 * Whether this title exists on the wiki.
510 *
511 * @see #static-method-exists
512 * @return {boolean|null} Boolean if the information is available, otherwise null
513 */
514 exists: function () {
515 return Title.exists( this );
516 }
517 };
518
519 /**
520 * @alias #getPrefixedDb
521 * @method
522 */
523 Title.prototype.toString = Title.prototype.getPrefixedDb;
524
525
526 /**
527 * @alias #getPrefixedText
528 * @method
529 */
530 Title.prototype.toText = Title.prototype.getPrefixedText;
531
532 // Expose
533 mw.Title = Title;
534
535 }( mediaWiki, jQuery ) );