| 1 | ( function () { |
| 2 | /** |
| 3 | * Function that's useful when constructing the URI string -- we frequently encounter the pattern |
| 4 | * of having to add something to the URI as we go, but only if it's present, and to include a |
| 5 | * character before or after if so. |
| 6 | * |
| 7 | * @private |
| 8 | * @static |
| 9 | * @param {string|undefined} pre To prepend |
| 10 | * @param {string} val To include |
| 11 | * @param {string} post To append |
| 12 | * @param {boolean} raw If true, val will not be encoded |
| 13 | * @return {string} Result |
| 14 | */ |
| 15 | function cat( pre, val, post, raw ) { |
| 16 | if ( val === undefined || val === null || val === '' ) { |
| 17 | return ''; |
| 18 | } |
| 19 | |
| 20 | return pre + ( raw ? val : mw.Uri.encode( val ) ) + post; |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * Regular expressions to parse many common URIs. |
| 25 | * |
| 26 | * These are gnarly expressions. For improved readability, they have been moved to a separate |
| 27 | * file where they make use of named capture groups. That syntax isn't valid in JavaScript ES5, |
| 28 | * so the server-side strips these before delivering to the client. |
| 29 | * |
| 30 | * @private |
| 31 | * @static |
| 32 | * @property {Object} parser |
| 33 | */ |
| 34 | const parser = { |
| 35 | strict: require( './strict.regexp.js' ), |
| 36 | loose: require( './loose.regexp.js' ) |
| 37 | }; |
| 38 | |
| 39 | /** |
| 40 | * The order here matches the order of captured matches in the `parser` property regexes. |
| 41 | * |
| 42 | * @private |
| 43 | * @static |
| 44 | * @property {string[]} properties |
| 45 | */ |
| 46 | const properties = [ |
| 47 | 'protocol', |
| 48 | 'user', |
| 49 | 'password', |
| 50 | 'host', |
| 51 | 'port', |
| 52 | 'path', |
| 53 | 'query', |
| 54 | 'fragment' |
| 55 | ]; |
| 56 | |
| 57 | /** |
| 58 | * A factory method to create an {@link mw.Uri} class with a default location to resolve relative URLs |
| 59 | * against (including protocol-relative URLs). |
| 60 | * |
| 61 | * @memberof mw |
| 62 | * @param {string|Function} documentLocation A full url, or function returning one. |
| 63 | * If passed a function, the return value may change over time and this will be honoured. (T74334) |
| 64 | * @return {mw.Uri} An mw.Uri class constructor |
| 65 | */ |
| 66 | mw.UriRelative = function ( documentLocation ) { |
| 67 | const getDefaultUri = ( function () { |
| 68 | // Cache |
| 69 | let href, uri; |
| 70 | |
| 71 | return function () { |
| 72 | const hrefCur = typeof documentLocation === 'string' ? documentLocation : documentLocation(); |
| 73 | if ( href === hrefCur ) { |
| 74 | return uri; |
| 75 | } |
| 76 | href = hrefCur; |
| 77 | uri = new Uri( href ); |
| 78 | return uri; |
| 79 | }; |
| 80 | }() ); |
| 81 | /** |
| 82 | * Options for mw.Uri object. |
| 83 | * |
| 84 | * @typedef {Object} mw.Uri.UriOptions |
| 85 | * @property {boolean} [strictMode=false] Trigger strict mode parsing of the url. |
| 86 | * @property {boolean} [overrideKeys=false] Whether to let duplicate query parameters |
| 87 | * override each other (`true`) or automagically convert them to an array (`false`). |
| 88 | * @property {boolean} [arrayParams=false] Whether to parse array query parameters (e.g. |
| 89 | * `&foo[0]=a&foo[1]=b` or `&foo[]=a&foo[]=b`) or leave them alone. Currently this does not |
| 90 | * handle associative or multi-dimensional arrays, but that may be improved in the future. |
| 91 | * Implies `overrideKeys: true` (query parameters without `[...]` are not parsed as arrays). |
| 92 | */ |
| 93 | |
| 94 | /** |
| 95 | * @classdesc Create and manipulate MediaWiki URIs. |
| 96 | * |
| 97 | * **DEPRECATED: mw.Uri has been deprecated in MediaWiki 1.43.** |
| 98 | * Please use the browser native {@link URL} class instead. |
| 99 | * See {@link https://www.mediawiki.org/wiki/Migrating_mw.Uri_to_URL migration guide}. |
| 100 | * |
| 101 | * Intended to be minimal, but featureful; do not expect full RFC 3986 compliance. The use cases we |
| 102 | * have in mind are constructing 'next page' or 'previous page' URLs, detecting whether we need to |
| 103 | * use cross-domain proxies for an API, constructing simple URL-based API calls, etc. Parsing here |
| 104 | * is regex-based, so may not work on all URIs, but is good enough for most. |
| 105 | * |
| 106 | * You can modify the properties directly, then use the {@link mw.Uri#toString toString} method to extract the full URI |
| 107 | * string again. Example: |
| 108 | * ``` |
| 109 | * var uri = new mw.Uri( 'http://example.com/mysite/mypage.php?quux=2' ); |
| 110 | * |
| 111 | * if ( uri.host == 'example.com' ) { |
| 112 | * uri.host = 'foo.example.com'; |
| 113 | * uri.extend( { bar: 1 } ); |
| 114 | * |
| 115 | * $( 'a#id1' ).attr( 'href', uri ); |
| 116 | * // anchor with id 'id1' now links to http://foo.example.com/mysite/mypage.php?bar=1&quux=2 |
| 117 | * |
| 118 | * $( 'a#id2' ).attr( 'href', uri.clone().extend( { bar: 3, pif: 'paf' } ) ); |
| 119 | * // anchor with id 'id2' now links to http://foo.example.com/mysite/mypage.php?bar=3&quux=2&pif=paf |
| 120 | * } |
| 121 | * ``` |
| 122 | * Given a URI like |
| 123 | * `http://usr:[email protected]:81/dir/dir.2/index.htm?q1=0&&test1&test2=&test3=value+%28escaped%29&r=1&r=2#top` |
| 124 | * the returned object will have the following properties: |
| 125 | * ``` |
| 126 | * protocol 'http' |
| 127 | * user 'usr' |
| 128 | * password 'pwd' |
| 129 | * host 'www.example.com' |
| 130 | * port '81' |
| 131 | * path '/dir/dir.2/index.htm' |
| 132 | * query { |
| 133 | * q1: '0', |
| 134 | * test1: null, |
| 135 | * test2: '', |
| 136 | * test3: 'value (escaped)' |
| 137 | * r: ['1', '2'] |
| 138 | * } |
| 139 | * fragment 'top' |
| 140 | * ``` |
| 141 | * Note: 'password' is technically not allowed for HTTP URIs, but it is possible with other kinds |
| 142 | * of URIs. |
| 143 | * |
| 144 | * Parsing based on parseUri 1.2.2 (c) Steven Levithan <http://stevenlevithan.com>, MIT License. |
| 145 | * <http://stevenlevithan.com/demo/parseuri/js/> |
| 146 | * |
| 147 | * @deprecated since MediaWiki 1.43. |
| 148 | * Please use the browser native {@link URL} class instead. |
| 149 | * See {@link https://www.mediawiki.org/wiki/Migrating_mw.Uri_to_URL migration guide}. |
| 150 | * |
| 151 | * @class |
| 152 | * @name mw.Uri |
| 153 | * |
| 154 | * @constructor |
| 155 | * @description Construct a new URI object. Throws error if arguments are illegal/impossible, or |
| 156 | * otherwise don't parse. |
| 157 | * @param {Object|string} [uri] URI string, or an Object with appropriate properties (especially |
| 158 | * another URI object to clone). Object must have non-blank `protocol`, `host`, and `path` |
| 159 | * properties. If omitted (or set to `undefined`, `null` or empty string), then an object |
| 160 | * will be created for the default `uri` of this constructor (`location.href` for mw.Uri, |
| 161 | * other values for other instances -- see {@link mw.UriRelative} for details). |
| 162 | * @param {mw.Uri.UriOptions|boolean} [options] Object with options, or (backwards compatibility) a boolean |
| 163 | * for strictMode |
| 164 | * @throws {Error} when the query string or fragment contains an unknown % sequence |
| 165 | */ |
| 166 | function Uri( uri, options ) { |
| 167 | const hasOptions = ( options !== undefined ), |
| 168 | defaultUri = getDefaultUri(); |
| 169 | |
| 170 | options = typeof options === 'object' ? options : { strictMode: !!options }; |
| 171 | options = Object.assign( { |
| 172 | strictMode: false, |
| 173 | overrideKeys: false, |
| 174 | arrayParams: false |
| 175 | }, options ); |
| 176 | |
| 177 | this.arrayParams = options.arrayParams; |
| 178 | |
| 179 | if ( uri !== undefined && uri !== null && uri !== '' ) { |
| 180 | if ( typeof uri === 'string' ) { |
| 181 | this.parse( uri, options ); |
| 182 | } else if ( typeof uri === 'object' ) { |
| 183 | // Copy data over from existing URI object |
| 184 | for ( const prop in uri ) { |
| 185 | // Only copy direct properties, not inherited ones |
| 186 | if ( Object.prototype.hasOwnProperty.call( uri, prop ) ) { |
| 187 | // Deep copy object properties |
| 188 | if ( Array.isArray( uri[ prop ] ) || $.isPlainObject( uri[ prop ] ) ) { |
| 189 | this[ prop ] = $.extend( true, {}, uri[ prop ] ); |
| 190 | } else { |
| 191 | this[ prop ] = uri[ prop ]; |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | if ( !this.query ) { |
| 196 | this.query = {}; |
| 197 | } |
| 198 | } |
| 199 | } else if ( hasOptions ) { |
| 200 | // We didn't get a URI in the constructor, but we got options. |
| 201 | const hrefCur = typeof documentLocation === 'string' ? documentLocation : documentLocation(); |
| 202 | this.parse( hrefCur, options ); |
| 203 | } else { |
| 204 | // We didn't get a URI or options in the constructor, use the default instance. |
| 205 | return defaultUri.clone(); |
| 206 | } |
| 207 | |
| 208 | // protocol-relative URLs |
| 209 | if ( !this.protocol ) { |
| 210 | this.protocol = defaultUri.protocol; |
| 211 | } |
| 212 | // No host given: |
| 213 | if ( !this.host ) { |
| 214 | this.host = defaultUri.host; |
| 215 | // port ? |
| 216 | if ( !this.port ) { |
| 217 | this.port = defaultUri.port; |
| 218 | } |
| 219 | } |
| 220 | if ( this.path && this.path[ 0 ] !== '/' ) { |
| 221 | // A real relative URL, relative to defaultUri.path. We can't really handle that since we cannot |
| 222 | // figure out whether the last path component of defaultUri.path is a directory or a file. |
| 223 | throw new Error( 'Bad constructor arguments' ); |
| 224 | } |
| 225 | if ( !( this.protocol && this.host && this.path ) ) { |
| 226 | throw new Error( 'Bad constructor arguments' ); |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * For example `http` (always present). |
| 232 | * |
| 233 | * @name mw.Uri.prototype.protocol |
| 234 | * @type {string} |
| 235 | */ |
| 236 | |
| 237 | /** |
| 238 | * For example `usr`. |
| 239 | * |
| 240 | * @name mw.Uri.prototype.user |
| 241 | * @type {string|undefined} |
| 242 | */ |
| 243 | /** |
| 244 | * For example `pwd`. |
| 245 | * |
| 246 | * @name mw.Uri.prototype.password |
| 247 | * @type {string|undefined} |
| 248 | */ |
| 249 | /** |
| 250 | * For example `www.example.com` (always present). |
| 251 | * |
| 252 | * @name mw.Uri.prototype.host |
| 253 | * @type {string} |
| 254 | */ |
| 255 | /** |
| 256 | * For example `81`. |
| 257 | * |
| 258 | * @name mw.Uri.prototype.port |
| 259 | * @type {string|undefined} |
| 260 | */ |
| 261 | /** |
| 262 | * For example `/dir/dir.2/index.htm` (always present). |
| 263 | * |
| 264 | * @name mw.Uri.prototype.path |
| 265 | * @type {string} |
| 266 | */ |
| 267 | /** |
| 268 | * For example `{ a: '0', b: '', c: 'value' }` (always present). |
| 269 | * |
| 270 | * @name mw.Uri.prototype.query |
| 271 | * @type {Object} |
| 272 | */ |
| 273 | /** |
| 274 | * For example `top`. |
| 275 | * |
| 276 | * @name mw.Uri.prototype.fragment |
| 277 | * @type {string|undefined} |
| 278 | */ |
| 279 | |
| 280 | /** |
| 281 | * Encode a value for inclusion in a url. |
| 282 | * |
| 283 | * Standard encodeURIComponent, with extra stuff to make all browsers work similarly and more |
| 284 | * compliant with RFC 3986. Similar to rawurlencode from PHP and our JS library |
| 285 | * {@link module:mediawiki.util.rawurlencode mw.util.rawurlencode}, except this also replaces spaces with `+`. |
| 286 | * |
| 287 | * @method |
| 288 | * @name mw.Uri.encode |
| 289 | * @param {string} s String to encode |
| 290 | * @return {string} Encoded string for URI |
| 291 | */ |
| 292 | Uri.encode = function ( s ) { |
| 293 | return encodeURIComponent( s ) |
| 294 | .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ) |
| 295 | .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ) |
| 296 | .replace( /%20/g, '+' ); |
| 297 | }; |
| 298 | |
| 299 | /** |
| 300 | * Decode a url encoded value. |
| 301 | * |
| 302 | * Reversed {@link mw.Uri.encode encode}. Standard decodeURIComponent, with addition of replacing |
| 303 | * `+` with a space. |
| 304 | * |
| 305 | * @method |
| 306 | * @name mw.Uri.decode |
| 307 | * @param {string} s String to decode |
| 308 | * @return {string} Decoded string |
| 309 | * @throws {Error} when the string contains an unknown % sequence |
| 310 | */ |
| 311 | Uri.decode = function ( s ) { |
| 312 | return decodeURIComponent( s.replace( /\+/g, '%20' ) ); |
| 313 | }; |
| 314 | |
| 315 | Uri.prototype = /** @lends mw.Uri.prototype */ { |
| 316 | |
| 317 | /** |
| 318 | * Parse a string and set our properties accordingly. |
| 319 | * |
| 320 | * @private |
| 321 | * @param {string} str URI, see constructor. |
| 322 | * @param {Object} options See constructor. |
| 323 | * @throws {Error} when the query string or fragment contains an unknown % sequence |
| 324 | */ |
| 325 | parse: function ( str, options ) { |
| 326 | const uri = this, |
| 327 | hasOwn = Object.prototype.hasOwnProperty; |
| 328 | |
| 329 | // Apply parser regex and set all properties based on the result |
| 330 | const matches = parser[ options.strictMode ? 'strict' : 'loose' ].exec( str ); |
| 331 | properties.forEach( ( property, i ) => { |
| 332 | uri[ property ] = matches[ i + 1 ]; |
| 333 | } ); |
| 334 | |
| 335 | // uri.query starts out as the query string; we will parse it into key-val pairs then make |
| 336 | // that object the "query" property. |
| 337 | // we overwrite query in uri way to make cloning easier, it can use the same list of properties. |
| 338 | const q = {}; |
| 339 | // using replace to iterate over a string |
| 340 | if ( uri.query ) { |
| 341 | |
| 342 | uri.query.replace( /(?:^|&)([^&=]*)(?:(=)([^&]*))?/g, ( match, k, eq, v ) => { |
| 343 | let arrayKeyMatch, i; |
| 344 | if ( k ) { |
| 345 | k = Uri.decode( k ); |
| 346 | v = ( eq === '' || eq === undefined ) ? null : Uri.decode( v ); |
| 347 | arrayKeyMatch = k.match( /^([^[]+)\[(\d*)\]$/ ); |
| 348 | |
| 349 | // If arrayParams and this parameter name contains an array index... |
| 350 | if ( options.arrayParams && arrayKeyMatch ) { |
| 351 | // Remove the index from parameter name |
| 352 | k = arrayKeyMatch[ 1 ]; |
| 353 | |
| 354 | // Turn the parameter value into an array (throw away anything else) |
| 355 | if ( !Array.isArray( q[ k ] ) ) { |
| 356 | q[ k ] = []; |
| 357 | } |
| 358 | |
| 359 | i = arrayKeyMatch[ 2 ]; |
| 360 | if ( i === '' ) { |
| 361 | // If no explicit index, append at the end |
| 362 | i = q[ k ].length; |
| 363 | } |
| 364 | |
| 365 | q[ k ][ i ] = v; |
| 366 | |
| 367 | // If overrideKeys, always (re)set top level value. |
| 368 | // If not overrideKeys but this key wasn't set before, then we set it as well. |
| 369 | // arrayParams implies overrideKeys (no array handling for non-array params). |
| 370 | } else if ( options.arrayParams || options.overrideKeys || !hasOwn.call( q, k ) ) { |
| 371 | q[ k ] = v; |
| 372 | |
| 373 | // Use arrays if overrideKeys is false and key was already seen before |
| 374 | } else { |
| 375 | // Once before, still a string, turn into an array |
| 376 | if ( typeof q[ k ] === 'string' ) { |
| 377 | q[ k ] = [ q[ k ] ]; |
| 378 | } |
| 379 | // Add to the array |
| 380 | if ( Array.isArray( q[ k ] ) ) { |
| 381 | q[ k ].push( v ); |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | } ); |
| 386 | } |
| 387 | uri.query = q; |
| 388 | |
| 389 | // Decode uri.fragment, otherwise it gets double-encoded when serializing |
| 390 | if ( uri.fragment !== undefined ) { |
| 391 | uri.fragment = Uri.decode( uri.fragment ); |
| 392 | } |
| 393 | }, |
| 394 | |
| 395 | /** |
| 396 | * Get user and password section of a URI. |
| 397 | * |
| 398 | * @return {string} |
| 399 | */ |
| 400 | getUserInfo: function () { |
| 401 | return cat( '', this.user, cat( ':', this.password, '' ) ); |
| 402 | }, |
| 403 | |
| 404 | /** |
| 405 | * Get host and port section of a URI. |
| 406 | * |
| 407 | * @return {string} |
| 408 | */ |
| 409 | getHostPort: function () { |
| 410 | return this.host + cat( ':', this.port, '' ); |
| 411 | }, |
| 412 | |
| 413 | /** |
| 414 | * Get the userInfo, host and port section of the URI. |
| 415 | * |
| 416 | * In most real-world URLs this is simply the hostname, but the definition of 'authority' section is more general. |
| 417 | * |
| 418 | * @return {string} |
| 419 | */ |
| 420 | getAuthority: function () { |
| 421 | return cat( '', this.getUserInfo(), '@' ) + this.getHostPort(); |
| 422 | }, |
| 423 | |
| 424 | /** |
| 425 | * Get the query arguments of the URL, encoded into a string. |
| 426 | * |
| 427 | * Does not preserve the original order of arguments passed in the URI. Does handle escaping. |
| 428 | * |
| 429 | * @return {string} |
| 430 | */ |
| 431 | getQueryString: function () { |
| 432 | const args = [], |
| 433 | arrayParams = this.arrayParams; |
| 434 | Object.keys( this.query ).forEach( ( key ) => { |
| 435 | const val = this.query[ key ]; |
| 436 | const k = Uri.encode( key ), |
| 437 | isArrayParam = Array.isArray( val ), |
| 438 | vals = isArrayParam ? val : [ val ]; |
| 439 | vals.forEach( ( v, i ) => { |
| 440 | let ki = k; |
| 441 | if ( arrayParams && isArrayParam ) { |
| 442 | ki += Uri.encode( '[' + i + ']' ); |
| 443 | } |
| 444 | if ( v === null ) { |
| 445 | args.push( ki ); |
| 446 | } else if ( k === 'title' ) { |
| 447 | args.push( ki + '=' + mw.util.wikiUrlencode( v ) ); |
| 448 | } else { |
| 449 | args.push( ki + '=' + Uri.encode( v ) ); |
| 450 | } |
| 451 | } ); |
| 452 | } ); |
| 453 | return args.join( '&' ); |
| 454 | }, |
| 455 | |
| 456 | /** |
| 457 | * Get everything after the authority section of the URI. |
| 458 | * |
| 459 | * @return {string} |
| 460 | */ |
| 461 | getRelativePath: function () { |
| 462 | return this.path + cat( '?', this.getQueryString(), '', true ) + cat( '#', this.fragment, '' ); |
| 463 | }, |
| 464 | |
| 465 | /** |
| 466 | * Get the entire URI string. |
| 467 | * |
| 468 | * Note that the output may not be precisely the same as the constructor input, |
| 469 | * due to order of query arguments. |
| 470 | * Note also that the fragment is not always roundtripped as-is; some characters will |
| 471 | * become encoded, including the slash character, which can cause problems with e.g. |
| 472 | * mediawiki.router. It is recommended to use the native URL class (via |
| 473 | * web2017-polyfills, which loads a polyfill if needed) in contexts where the fragment |
| 474 | * is important. |
| 475 | * |
| 476 | * @return {string} The URI string |
| 477 | */ |
| 478 | toString: function () { |
| 479 | return this.protocol + '://' + this.getAuthority() + this.getRelativePath(); |
| 480 | }, |
| 481 | |
| 482 | /** |
| 483 | * Clone this URI. |
| 484 | * |
| 485 | * @return {Object} New URI object with same properties |
| 486 | */ |
| 487 | clone: function () { |
| 488 | return new Uri( this ); |
| 489 | }, |
| 490 | |
| 491 | /** |
| 492 | * Extend the query section of the URI with new parameters. |
| 493 | * |
| 494 | * @param {Object} parameters Query parameters to add to ours (or to override ours with) as an |
| 495 | * object |
| 496 | * @return {Object} This URI object |
| 497 | */ |
| 498 | extend: function ( parameters ) { |
| 499 | for ( const name in parameters ) { |
| 500 | const parameter = parameters[ name ]; |
| 501 | if ( parameter !== undefined ) { |
| 502 | this.query[ name ] = parameter; |
| 503 | } |
| 504 | } |
| 505 | return this; |
| 506 | } |
| 507 | }; |
| 508 | |
| 509 | return Uri; |
| 510 | }; |
| 511 | |
| 512 | /** |
| 513 | * Default to the current browsing location (for relative URLs). |
| 514 | * |
| 515 | * @ignore |
| 516 | * @return {mw.Uri} |
| 517 | */ |
| 518 | mw.Uri = mw.UriRelative( () => location.href ); |
| 519 | |
| 520 | }() ); |