Reverting r103856 since it does not work. <body> is not available at startup.
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.Uri.js
1 /**
2 * Library for simple URI parsing and manipulation. Requires jQuery.
3 *
4 * Do not expect full RFC 3986 compliance. Intended to be minimal, but featureful.
5 * The use cases we have in mind are constructing 'next page' or 'previous page' URLs,
6 * detecting whether we need to use cross-domain proxies for an API, constructing
7 * simple URL-based API calls, etc.
8 *
9 * Intended to compress very well if you use a JS-parsing minifier.
10 *
11 * Dependencies: mw, jQuery
12 *
13 * Example:
14 *
15 * var uri = new mw.Uri( 'http://foo.com/mysite/mypage.php?quux=2' );
16 *
17 * if ( uri.host == 'foo.com' ) {
18 * uri.host = 'www.foo.com';
19 * uri.extend( { bar: 1 } );
20 *
21 * $( 'a#id1' ).attr( 'href', uri );
22 * // anchor with id 'id1' now links to http://foo.com/mysite/mypage.php?bar=1&quux=2
23 *
24 * $( 'a#id2' ).attr( 'href', uri.clone().extend( { bar: 3, pif: 'paf' } ) );
25 * // anchor with id 'id2' now links to http://foo.com/mysite/mypage.php?bar=3&quux=2&pif=paf
26 * }
27 *
28 * Parsing here is regex based, so may not work on all URIs, but is good enough for most.
29 *
30 * Given a URI like
31 * 'http://usr:pwd@www.test.com:81/dir/dir.2/index.htm?q1=0&&test1&test2=&test3=value+%28escaped%29&r=1&r=2#top':
32 * The returned object will have the following properties:
33 *
34 * protocol 'http'
35 * user 'usr'
36 * password 'pwd'
37 * host 'www.test.com'
38 * port '81'
39 * path '/dir/dir.2/index.htm'
40 * query {
41 * q1: 0,
42 * test1: null,
43 * test2: '',
44 * test3: 'value (escaped)'
45 * r: [1, 2]
46 * }
47 * fragment 'top'
48 *
49 * n.b. 'password' is not technically allowed for HTTP URIs, but it is possible with other
50 * sorts of URIs.
51 * You can modify the properties directly. Then use the toString() method to extract the
52 * full URI string again.
53 *
54 * Parsing based on parseUri 1.2.2 (c) Steven Levithan <stevenlevithan.com> MIT License
55 * http://stevenlevithan.com/demo/parseuri/js/
56 *
57 */
58
59 ( function( $, mw ) {
60
61 /**
62 * Function that's useful when constructing the URI string -- we frequently encounter the pattern of
63 * having to add something to the URI as we go, but only if it's present, and to include a character before or after if so.
64 * @param {String} to prepend, if value not empty
65 * @param {String} value to include, if not empty
66 * @param {String} to append, if value not empty
67 * @param {Boolean} raw -- if true, do not URI encode
68 * @return {String}
69 */
70 function cat( pre, val, post, raw ) {
71 if ( val === undefined || val === null || val === '' ) {
72 return '';
73 } else {
74 return pre + ( raw ? val : mw.Uri.encode( val ) ) + post;
75 }
76 }
77
78 // Regular expressions to parse many common URIs.
79 var parser = {
80 strict: /^(?:([^:\/?#]+):)?(?:\/\/(?:(?:([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)?((?:[^?#\/]*\/)*[^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
81 loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?(?:(?:([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?((?:\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?[^?#\/]*)(?:\?([^#]*))?(?:#(.*))?/
82 },
83
84 // The order here matches the order of captured matches in the above parser regexes.
85 properties = [
86 'protocol', // http
87 'user', // usr
88 'password', // pwd
89 'host', // www.test.com
90 'port', // 81
91 'path', // /dir/dir.2/index.htm
92 'query', // q1=0&&test1&test2=value (will become { q1: '0', test1: '', test2: 'value' } )
93 'fragment' // top
94 ];
95
96
97 /**
98 * We use a factory to inject a document location, for relative URLs, including protocol-relative URLs.
99 * so the library is still testable & purely functional.
100 */
101 mw.UriRelative = function( documentLocation ) {
102
103 /**
104 * Constructs URI object. Throws error if arguments are illegal/impossible, or otherwise don't parse.
105 * @constructor
106 * @param {Object|String} URI string, or an Object with appropriate properties (especially another URI object to clone).
107 * Object must have non-blank 'protocol', 'host', and 'path' properties.
108 * @param {Object|Boolean} Object with options, or (backwards compatibility) a boolean for strictMode
109 * - strictMode {Boolean} Trigger strict mode parsing of the url. Default: false
110 * - overrideKeys {Boolean} Wether to let duplicate query parameters override eachother (true) or automagically
111 * convert to an array (false, default).
112 */
113 function Uri( uri, options ) {
114 options = typeof options === 'object' ? options : { strictMode: !!options };
115 options = $.extend( {
116 strictMode: false,
117 overrideKeys: false
118 }, options );
119
120 if ( uri !== undefined && uri !== null || uri !== '' ) {
121 if ( typeof uri === 'string' ) {
122 this._parse( uri, options );
123 } else if ( typeof uri === 'object' ) {
124 var _this = this;
125 $.each( properties, function( i, property ) {
126 _this[property] = uri[property];
127 } );
128 if ( this.query === undefined ) {
129 this.query = {};
130 }
131 }
132 }
133
134 // protocol-relative URLs
135 if ( !this.protocol ) {
136 this.protocol = defaultProtocol;
137 }
138
139 if ( !( this.protocol && this.host && this.path ) ) {
140 throw new Error( 'Bad constructor arguments' );
141 }
142 }
143
144 /**
145 * Standard encodeURIComponent, with extra stuff to make all browsers work similarly and more compliant with RFC 3986
146 * Similar to rawurlencode from PHP and our JS library mw.util.rawurlencode, but we also replace space with a +
147 * @param {String} string
148 * @return {String} encoded for URI
149 */
150 Uri.encode = function( s ) {
151 return encodeURIComponent( s )
152 .replace( /!/g, '%21').replace( /'/g, '%27').replace( /\(/g, '%28')
153 .replace( /\)/g, '%29').replace( /\*/g, '%2A')
154 .replace( /%20/g, '+' );
155 };
156
157 /**
158 * Standard decodeURIComponent, with '+' to space
159 * @param {String} string encoded for URI
160 * @return {String} decoded string
161 */
162 Uri.decode = function( s ) {
163 return decodeURIComponent( s ).replace( /\+/g, ' ' );
164 };
165
166 Uri.prototype = {
167
168 /**
169 * Parse a string and set our properties accordingly.
170 * @param {String} URI
171 * @param {Object} options
172 * @return {Boolean} success
173 */
174 _parse: function( str, options ) {
175 var matches = parser[ options.strictMode ? 'strict' : 'loose' ].exec( str );
176 var uri = this;
177 $.each( properties, function( i, property ) {
178 uri[ property ] = matches[ i+1 ];
179 } );
180
181 // uri.query starts out as the query string; we will parse it into key-val pairs then make
182 // that object the "query" property.
183 // we overwrite query in uri way to make cloning easier, it can use the same list of properties.
184 var q = {};
185 // using replace to iterate over a string
186 if ( uri.query ) {
187 uri.query.replace( /(?:^|&)([^&=]*)(?:(=)([^&]*))?/g, function ($0, $1, $2, $3) {
188 if ( $1 ) {
189 var k = Uri.decode( $1 );
190 var v = ( $2 === '' || $2 === undefined ) ? null : Uri.decode( $3 );
191
192 // If overrideKeys, always (re)set top level value.
193 // If not overrideKeys but this key wasn't set before, then we set it as well.
194 if ( options.overrideKeys || q[ k ] === undefined ) {
195 q[ k ] = v;
196
197 // Use arrays if overrideKeys is false and key was already seen before
198 } else {
199 // Once before, still a string, turn into an array
200 if ( typeof q[ k ] === 'string' ) {
201 q[ k ] = [ q[ k ] ];
202 }
203 // Add to the array
204 if ( $.isArray( q[ k ] ) ) {
205 q[ k ].push( v );
206 }
207 }
208 }
209 } );
210 }
211 this.query = q;
212 },
213
214 /**
215 * Returns user and password portion of a URI.
216 * @return {String}
217 */
218 getUserInfo: function() {
219 return cat( '', this.user, cat( ':', this.password, '' ) );
220 },
221
222 /**
223 * Gets host and port portion of a URI.
224 * @return {String}
225 */
226 getHostPort: function() {
227 return this.host + cat( ':', this.port, '' );
228 },
229
230 /**
231 * Returns the userInfo and host and port portion of the URI.
232 * In most real-world URLs, this is simply the hostname, but it is more general.
233 * @return {String}
234 */
235 getAuthority: function() {
236 return cat( '', this.getUserInfo(), '@' ) + this.getHostPort();
237 },
238
239 /**
240 * Returns the query arguments of the URL, encoded into a string
241 * Does not preserve the order of arguments passed into the URI. Does handle escaping.
242 * @return {String}
243 */
244 getQueryString: function() {
245 var args = [];
246 $.each( this.query, function( key, val ) {
247 var k = Uri.encode( key );
248 var vals = val === null ? [ null ] : $.makeArray( val );
249 $.each( vals, function( i, v ) {
250 args.push( k + ( v === null ? '' : '=' + Uri.encode( v ) ) );
251 } );
252 } );
253 return args.join( '&' );
254 },
255
256 /**
257 * Returns everything after the authority section of the URI
258 * @return {String}
259 */
260 getRelativePath: function() {
261 return this.path + cat( '?', this.getQueryString(), '', true ) + cat( '#', this.fragment, '' );
262 },
263
264 /**
265 * Gets the entire URI string. May not be precisely the same as input due to order of query arguments.
266 * @return {String} the URI string
267 */
268 toString: function() {
269 return this.protocol + '://' + this.getAuthority() + this.getRelativePath();
270 },
271
272 /**
273 * Clone this URI
274 * @return {Object} new URI object with same properties
275 */
276 clone: function() {
277 return new Uri( this );
278 },
279
280 /**
281 * Extend the query -- supply query parameters to override or add to ours
282 * @param {Object} query parameters in key-val form to override or add
283 * @return {Object} this URI object
284 */
285 extend: function( parameters ) {
286 $.extend( this.query, parameters );
287 return this;
288 }
289 };
290
291 var defaultProtocol = ( new Uri( documentLocation ) ).protocol;
292
293 return Uri;
294 };
295
296 // if we are running in a browser, inject the current document location, for relative URLs
297 if ( document && document.location && document.location.href ) {
298 mw.Uri = mw.UriRelative( document.location.href );
299 }
300
301 } )( jQuery, mediaWiki );