Merge "mediawiki.user: Simplify mw.user.generateRandomSessionId"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.Uri.js
1 /**
2 * Library for simple URI parsing and manipulation.
3 *
4 * Intended to be minimal, but featureful; do not expect full RFC 3986 compliance. The use cases we
5 * have in mind are constructing 'next page' or 'previous page' URLs, detecting whether we need to
6 * use cross-domain proxies for an API, constructing simple URL-based API calls, etc. Parsing here
7 * is regex-based, so may not work on all URIs, but is good enough for most.
8 *
9 * You can modify the properties directly, then use the #toString method to extract the full URI
10 * string again. Example:
11 *
12 * var uri = new mw.Uri( 'http://example.com/mysite/mypage.php?quux=2' );
13 *
14 * if ( uri.host == 'example.com' ) {
15 * uri.host = 'foo.example.com';
16 * uri.extend( { bar: 1 } );
17 *
18 * $( 'a#id1' ).attr( 'href', uri );
19 * // anchor with id 'id1' now links to http://foo.example.com/mysite/mypage.php?bar=1&quux=2
20 *
21 * $( 'a#id2' ).attr( 'href', uri.clone().extend( { bar: 3, pif: 'paf' } ) );
22 * // anchor with id 'id2' now links to http://foo.example.com/mysite/mypage.php?bar=3&quux=2&pif=paf
23 * }
24 *
25 * Given a URI like
26 * `http://usr:pwd@www.example.com:81/dir/dir.2/index.htm?q1=0&&test1&test2=&test3=value+%28escaped%29&r=1&r=2#top`
27 * the returned object will have the following properties:
28 *
29 * protocol 'http'
30 * user 'usr'
31 * password 'pwd'
32 * host 'www.example.com'
33 * port '81'
34 * path '/dir/dir.2/index.htm'
35 * query {
36 * q1: '0',
37 * test1: null,
38 * test2: '',
39 * test3: 'value (escaped)'
40 * r: ['1', '2']
41 * }
42 * fragment 'top'
43 *
44 * (N.b., 'password' is technically not allowed for HTTP URIs, but it is possible with other kinds
45 * of URIs.)
46 *
47 * Parsing based on parseUri 1.2.2 (c) Steven Levithan <http://stevenlevithan.com>, MIT License.
48 * <http://stevenlevithan.com/demo/parseuri/js/>
49 *
50 * @class mw.Uri
51 */
52
53 /* eslint-disable no-use-before-define */
54
55 ( function ( mw, $ ) {
56 var parser, properties;
57
58 /**
59 * Function that's useful when constructing the URI string -- we frequently encounter the pattern
60 * of having to add something to the URI as we go, but only if it's present, and to include a
61 * character before or after if so.
62 *
63 * @private
64 * @static
65 * @param {string|undefined} pre To prepend
66 * @param {string} val To include
67 * @param {string} post To append
68 * @param {boolean} raw If true, val will not be encoded
69 * @return {string} Result
70 */
71 function cat( pre, val, post, raw ) {
72 if ( val === undefined || val === null || val === '' ) {
73 return '';
74 }
75
76 return pre + ( raw ? val : mw.Uri.encode( val ) ) + post;
77 }
78
79 /**
80 * Regular expressions to parse many common URIs.
81 *
82 * As they are gnarly, they have been moved to separate files to allow us to format them in the
83 * 'extended' regular expression format (which JavaScript normally doesn't support). The subset of
84 * features handled is minimal, but just the free whitespace gives us a lot.
85 *
86 * @private
87 * @static
88 * @property {Object} parser
89 */
90 parser = {
91 strict: mw.template.get( 'mediawiki.Uri', 'strict.regexp' ).render(),
92 loose: mw.template.get( 'mediawiki.Uri', 'loose.regexp' ).render()
93 };
94
95 /**
96 * The order here matches the order of captured matches in the `parser` property regexes.
97 *
98 * @private
99 * @static
100 * @property {Array} properties
101 */
102 properties = [
103 'protocol',
104 'user',
105 'password',
106 'host',
107 'port',
108 'path',
109 'query',
110 'fragment'
111 ];
112
113 /**
114 * @property {string} protocol For example `http` (always present)
115 */
116 /**
117 * @property {string|undefined} user For example `usr`
118 */
119 /**
120 * @property {string|undefined} password For example `pwd`
121 */
122 /**
123 * @property {string} host For example `www.example.com` (always present)
124 */
125 /**
126 * @property {string|undefined} port For example `81`
127 */
128 /**
129 * @property {string} path For example `/dir/dir.2/index.htm` (always present)
130 */
131 /**
132 * @property {Object} query For example `{ a: '0', b: '', c: 'value' }` (always present)
133 */
134 /**
135 * @property {string|undefined} fragment For example `top`
136 */
137
138 /**
139 * A factory method to create a Uri class with a default location to resolve relative URLs
140 * against (including protocol-relative URLs).
141 *
142 * @method
143 * @param {string|Function} documentLocation A full url, or function returning one.
144 * If passed a function, the return value may change over time and this will be honoured. (T74334)
145 * @member mw
146 * @return {Function} Uri class
147 */
148 mw.UriRelative = function ( documentLocation ) {
149 var getDefaultUri = ( function () {
150 // Cache
151 var href, uri;
152
153 return function () {
154 var hrefCur = typeof documentLocation === 'string' ? documentLocation : documentLocation();
155 if ( href === hrefCur ) {
156 return uri;
157 }
158 href = hrefCur;
159 uri = new Uri( href );
160 return uri;
161 };
162 }() );
163
164 /**
165 * Construct a new URI object. Throws error if arguments are illegal/impossible, or
166 * otherwise don't parse.
167 *
168 * @class mw.Uri
169 * @constructor
170 * @param {Object|string} [uri] URI string, or an Object with appropriate properties (especially
171 * another URI object to clone). Object must have non-blank `protocol`, `host`, and `path`
172 * properties. If omitted (or set to `undefined`, `null` or empty string), then an object
173 * will be created for the default `uri` of this constructor (`location.href` for mw.Uri,
174 * other values for other instances -- see mw.UriRelative for details).
175 * @param {Object|boolean} [options] Object with options, or (backwards compatibility) a boolean
176 * for strictMode
177 * @param {boolean} [options.strictMode=false] Trigger strict mode parsing of the url.
178 * @param {boolean} [options.overrideKeys=false] Whether to let duplicate query parameters
179 * override each other (`true`) or automagically convert them to an array (`false`).
180 */
181 function Uri( uri, options ) {
182 var prop,
183 defaultUri = getDefaultUri();
184
185 options = typeof options === 'object' ? options : { strictMode: !!options };
186 options = $.extend( {
187 strictMode: false,
188 overrideKeys: false
189 }, options );
190
191 if ( uri !== undefined && uri !== null && uri !== '' ) {
192 if ( typeof uri === 'string' ) {
193 this.parse( uri, options );
194 } else if ( typeof uri === 'object' ) {
195 // Copy data over from existing URI object
196 for ( prop in uri ) {
197 // Only copy direct properties, not inherited ones
198 if ( uri.hasOwnProperty( prop ) ) {
199 // Deep copy object properties
200 if ( $.isArray( uri[ prop ] ) || $.isPlainObject( uri[ prop ] ) ) {
201 this[ prop ] = $.extend( true, {}, uri[ prop ] );
202 } else {
203 this[ prop ] = uri[ prop ];
204 }
205 }
206 }
207 if ( !this.query ) {
208 this.query = {};
209 }
210 }
211 } else {
212 // If we didn't get a URI in the constructor, use the default one.
213 return defaultUri.clone();
214 }
215
216 // protocol-relative URLs
217 if ( !this.protocol ) {
218 this.protocol = defaultUri.protocol;
219 }
220 // No host given:
221 if ( !this.host ) {
222 this.host = defaultUri.host;
223 // port ?
224 if ( !this.port ) {
225 this.port = defaultUri.port;
226 }
227 }
228 if ( this.path && this.path[ 0 ] !== '/' ) {
229 // A real relative URL, relative to defaultUri.path. We can't really handle that since we cannot
230 // figure out whether the last path component of defaultUri.path is a directory or a file.
231 throw new Error( 'Bad constructor arguments' );
232 }
233 if ( !( this.protocol && this.host && this.path ) ) {
234 throw new Error( 'Bad constructor arguments' );
235 }
236 }
237
238 /**
239 * Encode a value for inclusion in a url.
240 *
241 * Standard encodeURIComponent, with extra stuff to make all browsers work similarly and more
242 * compliant with RFC 3986. Similar to rawurlencode from PHP and our JS library
243 * mw.util.rawurlencode, except this also replaces spaces with `+`.
244 *
245 * @static
246 * @param {string} s String to encode
247 * @return {string} Encoded string for URI
248 */
249 Uri.encode = function ( s ) {
250 return encodeURIComponent( s )
251 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
252 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' )
253 .replace( /%20/g, '+' );
254 };
255
256 /**
257 * Decode a url encoded value.
258 *
259 * Reversed #encode. Standard decodeURIComponent, with addition of replacing
260 * `+` with a space.
261 *
262 * @static
263 * @param {string} s String to decode
264 * @return {string} Decoded string
265 */
266 Uri.decode = function ( s ) {
267 return decodeURIComponent( s.replace( /\+/g, '%20' ) );
268 };
269
270 Uri.prototype = {
271
272 /**
273 * Parse a string and set our properties accordingly.
274 *
275 * @private
276 * @param {string} str URI, see constructor.
277 * @param {Object} options See constructor.
278 */
279 parse: function ( str, options ) {
280 var q, matches,
281 uri = this,
282 hasOwn = Object.prototype.hasOwnProperty;
283
284 // Apply parser regex and set all properties based on the result
285 matches = parser[ options.strictMode ? 'strict' : 'loose' ].exec( str );
286 $.each( properties, function ( i, property ) {
287 uri[ property ] = matches[ i + 1 ];
288 } );
289
290 // uri.query starts out as the query string; we will parse it into key-val pairs then make
291 // that object the "query" property.
292 // we overwrite query in uri way to make cloning easier, it can use the same list of properties.
293 q = {};
294 // using replace to iterate over a string
295 if ( uri.query ) {
296 uri.query.replace( /(?:^|&)([^&=]*)(?:(=)([^&]*))?/g, function ( $0, $1, $2, $3 ) {
297 var k, v;
298 if ( $1 ) {
299 k = Uri.decode( $1 );
300 v = ( $2 === '' || $2 === undefined ) ? null : Uri.decode( $3 );
301
302 // If overrideKeys, always (re)set top level value.
303 // If not overrideKeys but this key wasn't set before, then we set it as well.
304 if ( options.overrideKeys || !hasOwn.call( q, k ) ) {
305 q[ k ] = v;
306
307 // Use arrays if overrideKeys is false and key was already seen before
308 } else {
309 // Once before, still a string, turn into an array
310 if ( typeof q[ k ] === 'string' ) {
311 q[ k ] = [ q[ k ] ];
312 }
313 // Add to the array
314 if ( $.isArray( q[ k ] ) ) {
315 q[ k ].push( v );
316 }
317 }
318 }
319 } );
320 }
321 uri.query = q;
322 },
323
324 /**
325 * Get user and password section of a URI.
326 *
327 * @return {string}
328 */
329 getUserInfo: function () {
330 return cat( '', this.user, cat( ':', this.password, '' ) );
331 },
332
333 /**
334 * Get host and port section of a URI.
335 *
336 * @return {string}
337 */
338 getHostPort: function () {
339 return this.host + cat( ':', this.port, '' );
340 },
341
342 /**
343 * Get the userInfo, host and port section of the URI.
344 *
345 * In most real-world URLs this is simply the hostname, but the definition of 'authority' section is more general.
346 *
347 * @return {string}
348 */
349 getAuthority: function () {
350 return cat( '', this.getUserInfo(), '@' ) + this.getHostPort();
351 },
352
353 /**
354 * Get the query arguments of the URL, encoded into a string.
355 *
356 * Does not preserve the original order of arguments passed in the URI. Does handle escaping.
357 *
358 * @return {string}
359 */
360 getQueryString: function () {
361 var args = [];
362 $.each( this.query, function ( key, val ) {
363 var k = Uri.encode( key ),
364 vals = $.isArray( val ) ? val : [ val ];
365 $.each( vals, function ( i, v ) {
366 if ( v === null ) {
367 args.push( k );
368 } else if ( k === 'title' ) {
369 args.push( k + '=' + mw.util.wikiUrlencode( v ) );
370 } else {
371 args.push( k + '=' + Uri.encode( v ) );
372 }
373 } );
374 } );
375 return args.join( '&' );
376 },
377
378 /**
379 * Get everything after the authority section of the URI.
380 *
381 * @return {string}
382 */
383 getRelativePath: function () {
384 return this.path + cat( '?', this.getQueryString(), '', true ) + cat( '#', this.fragment, '' );
385 },
386
387 /**
388 * Get the entire URI string.
389 *
390 * May not be precisely the same as input due to order of query arguments.
391 *
392 * @return {string} The URI string
393 */
394 toString: function () {
395 return this.protocol + '://' + this.getAuthority() + this.getRelativePath();
396 },
397
398 /**
399 * Clone this URI
400 *
401 * @return {Object} New URI object with same properties
402 */
403 clone: function () {
404 return new Uri( this );
405 },
406
407 /**
408 * Extend the query section of the URI with new parameters.
409 *
410 * @param {Object} parameters Query parameters to add to ours (or to override ours with) as an
411 * object
412 * @return {Object} This URI object
413 */
414 extend: function ( parameters ) {
415 $.extend( this.query, parameters );
416 return this;
417 }
418 };
419
420 return Uri;
421 };
422
423 // Default to the current browsing location (for relative URLs).
424 mw.Uri = mw.UriRelative( function () {
425 return location.href;
426 } );
427
428 }( mediaWiki, jQuery ) );