985c5c92057ca776c1b15588e3829d96645dd6d7
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.Title.js
1 /**
2 * mediaWiki.Title
3 *
4 * @author Neil Kandalgaonkar, 2010
5 * @author Timo Tijhof, 2011
6 * @since 1.18
7 *
8 * Relies on: mw.config (wgFormattedNamespaces, wgNamespaceIds, wgCaseSensitiveNamespaces), mw.util.wikiGetlink
9 */
10 ( function( $ ) {
11
12 /* Local space */
13
14 /**
15 * Title
16 * @constructor
17 *
18 * @param title {String} Title of the page. If no second argument given,
19 * this will be searched for a namespace.
20 * @param namespace {Number} (optional) Namespace id. If given, title will be taken as-is.
21 * @return {Title} this
22 */
23 var Title = function( title, namespace ) {
24 this._ns = 0; // integer namespace id
25 this._name = null; // name in canonical 'database' form
26 this._ext = null; // extension
27
28 if ( arguments.length === 2 ) {
29 setNameAndExtension( this, title );
30 this._ns = fixNsId( namespace );
31 } else if ( arguments.length === 1 ) {
32 setAll( this, title );
33 }
34 return this;
35 },
36
37 /**
38 * Strip some illegal chars: control chars, colon, less than, greater than,
39 * brackets, braces, pipe, whitespace and normal spaces. This still leaves some insanity
40 * intact, like unicode bidi chars, but it's a good start..
41 * @param s {String}
42 * @return {String}
43 */
44 clean = function( s ) {
45 if ( s !== undefined ) {
46 return s.replace( /[\x00-\x1f\x23\x3c\x3e\x5b\x5d\x7b\x7c\x7d\x7f\s]+/g, '_' );
47 }
48 },
49
50 /**
51 * Convert db-key to readable text.
52 * @param s {String}
53 * @return {String}
54 */
55 text = function ( s ) {
56 if ( s !== null && s !== undefined ) {
57 return s.replace( /_/g, ' ' );
58 } else {
59 return '';
60 }
61 },
62
63 /**
64 * Sanatize name.
65 */
66 fixName = function( s ) {
67 return clean( $.trim( s ) );
68 },
69
70 /**
71 * Sanatize name.
72 */
73 fixExt = function( s ) {
74 return clean( s.toLowerCase() );
75 },
76
77 /**
78 * Sanatize namespace id.
79 * @param id {Number} Namespace id.
80 * @return {Number|Boolean} The id as-is or boolean false if invalid.
81 */
82 fixNsId = function( id ) {
83 // wgFormattedNamespaces is an object of *string* key-vals (ie. arr["0"] not arr[0] )
84 var ns = mw.config.get( 'wgFormattedNamespaces' )[id.toString()];
85
86 // Check only undefined (may be false-y, such as '' (main namespace) ).
87 if ( ns === undefined ) {
88 return false;
89 } else {
90 return Number( id );
91 }
92 },
93
94 /**
95 * Get namespace id from namespace name by any known namespace/id pair (localized, canonical or alias).
96 *
97 * @example On a German wiki this would return 6 for any of 'File', 'Datei', 'Image' or even 'Bild'.
98 * @param ns {String} Namespace name (case insensitive, leading/trailing space ignored).
99 * @return {Number|Boolean} Namespace id or boolean false if unrecognized.
100 */
101 getNsIdByName = function( ns ) {
102 // toLowerCase throws exception on null/undefined. Return early.
103 if ( ns == null ) {
104 return false;
105 }
106 ns = clean( $.trim( ns.toLowerCase() ) ); // Normalize
107 var id = mw.config.get( 'wgNamespaceIds' )[ns];
108 if ( id === undefined ) {
109 mw.log( 'mw.Title: Unrecognized namespace: ' + ns );
110 return false;
111 }
112 return fixNsId( id );
113 },
114
115 /**
116 * Helper to extract namespace, name and extension from a string.
117 *
118 * @param title {mw.Title}
119 * @param raw {String}
120 * @return {mw.Title}
121 */
122 setAll = function( title, s ) {
123 var matches = s.match( /^(?:([^:]+):)?(.*?)(?:\.(\w{1,5}))?$/ ),
124 ns_match = getNsIdByName( matches[1] );
125 if ( matches.length && ns_match ) {
126 if ( matches[1] ) { title._ns = ns_match; }
127 if ( matches[2] ) { title._name = fixName( matches[2] ); }
128 if ( matches[3] ) { title._ext = fixExt( matches[3] ); }
129 } else {
130 // Consistency with MediaWiki: Unknown namespace > fallback to main namespace.
131 title._ns = 0;
132 setNameAndExtension( title, s );
133 }
134 return title;
135 },
136
137 /**
138 * Helper to extract name and extension from a string.
139 *
140 * @param title {mw.Title}
141 * @param raw {String}
142 * @return {mw.Title}
143 */
144 setNameAndExtension = function( title, raw ) {
145 var matches = raw.match( /^(?:)?(.*?)(?:\.(\w{1,5}))?$/ );
146 if ( matches.length ) {
147 if ( matches[1] ) { title._name = fixName( matches[1] ); }
148 if ( matches[2] ) { title._ext = fixExt( matches[2] ); }
149 } else {
150 throw new Error( 'mw.Title: Could not parse title "' + raw + '"' );
151 }
152 return title;
153 };
154
155
156 /* Static space */
157
158 /**
159 * Wether this title exists on the wiki.
160 * @param title {mixed} prefixed db-key name (string) or instance of Title
161 * @return {mixed} Boolean true/false if the information is available. Otherwise null.
162 */
163 Title.exists = function( title ) {
164 var type = $.type( title ), obj = Title.exist.pages, match;
165 if ( type === 'string' ) {
166 match = obj[title];
167 } else if ( type === 'object' && title instanceof Title ) {
168 match = obj[title.toString()];
169 } else {
170 throw new Error( 'mw.Title.exists: title must be a string or an instance of Title' );
171 }
172 if ( typeof match === 'boolean' ) {
173 return match;
174 }
175 return null;
176 };
177
178 /**
179 * @var Title.exist {Object}
180 */
181 Title.exist = {
182 /**
183 * @var Title.exist.pages {Object} Keyed by PrefixedDb title.
184 * Boolean true value indicates page does exist.
185 */
186 pages: {},
187 /**
188 * @example Declare existing titles: Title.exist.set(['User:John_Doe', ...]);
189 * @example Declare titles inexisting: Title.exist.set(['File:Foo_bar.jpg', ...], false);
190 * @param titles {String|Array} Title(s) in strict prefixedDb title form.
191 * @param state {Boolean} (optional) State of the given titles. Defaults to true.
192 * @return {Boolean}
193 */
194 set: function( titles, state ) {
195 titles = $.isArray( titles ) ? titles : [titles];
196 state = state === undefined ? true : !!state;
197 var pages = this.pages, i, len = titles.length;
198 for ( i = 0; i < len; i++ ) {
199 pages[ titles[i] ] = state;
200 }
201 return true;
202 }
203 };
204
205 /* Public methods */
206
207 var fn = {
208 constructor: Title,
209
210 /**
211 * Get the namespace number.
212 * @return {Number}
213 */
214 getNamespaceId: function(){
215 return this._ns;
216 },
217
218 /**
219 * Get the namespace prefix (in the content-language).
220 * In NS_MAIN this is '', otherwise namespace name plus ':'
221 * @return {String}
222 */
223 getNamespacePrefix: function(){
224 return mw.config.get( 'wgFormattedNamespaces' )[this._ns].replace( / /g, '_' ) + (this._ns === 0 ? '' : ':');
225 },
226
227 /**
228 * The name, like "Foo_bar"
229 * @return {String}
230 */
231 getName: function() {
232 if ( $.inArray( this._ns, mw.config.get( 'wgCaseSensitiveNamespaces' ) ) !== -1 ) {
233 return this._name;
234 } else {
235 return $.ucFirst( this._name );
236 }
237 },
238
239 /**
240 * The name, like "Foo bar"
241 * @return {String}
242 */
243 getNameText: function() {
244 return text( this.getName() );
245 },
246
247 /**
248 * Get full name in prefixed DB form, like File:Foo_bar.jpg,
249 * most useful for API calls, anything that must identify the "title".
250 */
251 getPrefixedDb: function() {
252 return this.getNamespacePrefix() + this.getMain();
253 },
254
255 /**
256 * Get full name in text form, like "File:Foo bar.jpg".
257 * @return {String}
258 */
259 getPrefixedText: function() {
260 return text( this.getPrefixedDb() );
261 },
262
263 /**
264 * The main title (without namespace), like "Foo_bar.jpg"
265 * @return {String}
266 */
267 getMain: function() {
268 return this.getName() + this.getDotExtension();
269 },
270
271 /**
272 * The "text" form, like "Foo bar.jpg"
273 * @return {String}
274 */
275 getMainText: function() {
276 return text( this.getMain() );
277 },
278
279 /**
280 * Get the extension (returns null if there was none)
281 * @return {String|null} extension
282 */
283 getExtension: function() {
284 return this._ext;
285 },
286
287 /**
288 * Convenience method: return string like ".jpg", or "" if no extension
289 * @return {String}
290 */
291 getDotExtension: function() {
292 return this._ext === null ? '' : '.' + this._ext;
293 },
294
295 /**
296 * Return the URL to this title
297 * @return {String}
298 */
299 getUrl: function() {
300 return mw.util.wikiGetlink( this.toString() );
301 },
302
303 /**
304 * Wether this title exists on the wiki.
305 * @return {mixed} Boolean true/false if the information is available. Otherwise null.
306 */
307 exists: function() {
308 return Title.exists( this );
309 }
310 };
311
312 // Alias
313 fn.toString = fn.getPrefixedDb;
314 fn.toText = fn.getPrefixedText;
315
316 // Assign
317 Title.prototype = fn;
318
319 // Expose
320 mw.Title = Title;
321
322 })(jQuery);