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