| 1 | 'use strict'; |
| 2 | |
| 3 | let config = require( './config.json' ); |
| 4 | const portletLinkOptions = require( './portletLinkOptions.json' ); |
| 5 | const infinityValues = require( './infinityValues.json' ); |
| 6 | |
| 7 | require( './jquery.accessKeyLabel.js' ); |
| 8 | |
| 9 | /** |
| 10 | * Encode the string like PHP's rawurlencode. |
| 11 | * |
| 12 | * @ignore |
| 13 | * @param {string} str String to be encoded. |
| 14 | * @return {string} Encoded string |
| 15 | */ |
| 16 | function rawurlencode( str ) { |
| 17 | return encodeURIComponent( String( str ) ) |
| 18 | .replace( /!/g, '%21' ) |
| 19 | .replace( /'/g, '%27' ) |
| 20 | .replace( /\(/g, '%28' ) |
| 21 | .replace( /\)/g, '%29' ) |
| 22 | .replace( /\*/g, '%2A' ) |
| 23 | .replace( /~/g, '%7E' ); |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Private helper function used by util.escapeId*() |
| 28 | * |
| 29 | * @ignore |
| 30 | * @param {string} str String to be encoded |
| 31 | * @param {string} mode Encoding mode, see documentation at |
| 32 | * MainConfigSchema::FragmentMode. |
| 33 | * @return {string} Encoded string |
| 34 | */ |
| 35 | function escapeIdInternal( str, mode ) { |
| 36 | str = String( str ); |
| 37 | |
| 38 | switch ( mode ) { |
| 39 | case 'html5': |
| 40 | return str.replace( / /g, '_' ); |
| 41 | case 'legacy': |
| 42 | return rawurlencode( str.replace( / /g, '_' ) ) |
| 43 | .replace( /%3A/g, ':' ) |
| 44 | .replace( /%/g, '.' ); |
| 45 | default: |
| 46 | throw new Error( 'Unrecognized ID escaping mode ' + mode ); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Library providing useful common skin-agnostic utility functions. Please see |
| 52 | * [mediawiki.util]{@link module:mediawiki.util}. |
| 53 | * |
| 54 | * Alias for the [mediawiki.util]{@link module:mediawiki.util} module. |
| 55 | * |
| 56 | * @namespace mw.util |
| 57 | */ |
| 58 | |
| 59 | /** |
| 60 | * Utility library provided by the `mediawiki.util` ResourceLoader module. Accessible inside ResourceLoader modules |
| 61 | * or for gadgets as part of the [mw global object]{@link mw}. |
| 62 | * |
| 63 | * @example |
| 64 | * // Inside MediaWiki extensions |
| 65 | * const util = require( 'mediawiki.util' ); |
| 66 | * // In gadgets |
| 67 | * const mwUtil = mw.util; |
| 68 | * @exports mediawiki.util |
| 69 | */ |
| 70 | const util = { |
| 71 | |
| 72 | /** |
| 73 | * Encode the string like PHP's rawurlencode. |
| 74 | * |
| 75 | * @method |
| 76 | * @param {string} str String to be encoded. |
| 77 | * @return {string} Encoded string |
| 78 | */ |
| 79 | rawurlencode: rawurlencode, |
| 80 | |
| 81 | /** |
| 82 | * Encode a string as CSS id, for use as HTML id attribute value. |
| 83 | * |
| 84 | * Analog to `Sanitizer::escapeIdForAttribute()` in PHP. |
| 85 | * |
| 86 | * @since 1.30 |
| 87 | * @param {string} str String to encode |
| 88 | * @return {string} Encoded string |
| 89 | */ |
| 90 | escapeIdForAttribute: function ( str ) { |
| 91 | return escapeIdInternal( str, config.FragmentMode[ 0 ] ); |
| 92 | }, |
| 93 | |
| 94 | /** |
| 95 | * Encode a string as URL fragment, for use as HTML anchor link. |
| 96 | * |
| 97 | * Analog to `Sanitizer::escapeIdForLink()` in PHP. |
| 98 | * |
| 99 | * @since 1.30 |
| 100 | * @param {string} str String to encode |
| 101 | * @return {string} Encoded string |
| 102 | */ |
| 103 | escapeIdForLink: function ( str ) { |
| 104 | return escapeIdInternal( str, config.FragmentMode[ 0 ] ); |
| 105 | }, |
| 106 | |
| 107 | /** |
| 108 | * Get the target element from a link hash. |
| 109 | * |
| 110 | * This is the same element as you would get from |
| 111 | * document.querySelectorAll(':target'), but can be used on |
| 112 | * an arbitrary hash fragment, or after pushState/replaceState |
| 113 | * has been used. |
| 114 | * |
| 115 | * Link fragments can be unencoded, fully encoded or partially |
| 116 | * encoded, as defined in the spec. |
| 117 | * |
| 118 | * We can't just use decodeURI as that assumes the fragment |
| 119 | * is fully encoded, and throws an error on a string like '%A', |
| 120 | * so we use the percent-decode. |
| 121 | * |
| 122 | * @param {string} [hash] Hash fragment, without the leading '#'. |
| 123 | * Taken from location.hash if omitted. |
| 124 | * @return {HTMLElement|null} Element, if found |
| 125 | */ |
| 126 | getTargetFromFragment: function ( hash ) { |
| 127 | hash = hash || location.hash.slice( 1 ); |
| 128 | if ( !hash ) { |
| 129 | // Firefox emits a console warning if you pass an empty string |
| 130 | // to getElementById (T272844). |
| 131 | return null; |
| 132 | } |
| 133 | // Per https://html.spec.whatwg.org/multipage/browsing-the-web.html#target-element |
| 134 | // we try the raw fragment first, then the percent-decoded fragment. |
| 135 | const element = document.getElementById( hash ); |
| 136 | if ( element ) { |
| 137 | return element; |
| 138 | } |
| 139 | const decodedHash = this.percentDecodeFragment( hash ); |
| 140 | if ( !decodedHash ) { |
| 141 | // decodedHash can return null, calling getElementById would cast it to a string |
| 142 | return null; |
| 143 | } |
| 144 | return document.getElementById( decodedHash ); |
| 145 | }, |
| 146 | |
| 147 | /** |
| 148 | * Percent-decode a string, as found in a URL hash fragment. |
| 149 | * |
| 150 | * Implements the percent-decode method as defined in |
| 151 | * https://url.spec.whatwg.org/#percent-decode. |
| 152 | * |
| 153 | * URLSearchParams implements https://url.spec.whatwg.org/#concept-urlencoded-parser |
| 154 | * which performs a '+' to ' ' substitution before running percent-decode. |
| 155 | * |
| 156 | * To get the desired behaviour we percent-encode any '+' in the fragment |
| 157 | * to effectively expose the percent-decode implementation. |
| 158 | * |
| 159 | * @param {string} text Text to decode |
| 160 | * @return {string|null} Decoded text, null if decoding failed |
| 161 | */ |
| 162 | percentDecodeFragment: function ( text ) { |
| 163 | const params = new URLSearchParams( |
| 164 | 'q=' + |
| 165 | text |
| 166 | // Query string param decoding replaces '+' with ' ' before doing the |
| 167 | // percent_decode, so encode '+' to prevent this. |
| 168 | .replace( /\+/g, '%2B' ) |
| 169 | // Query strings are split on '&' and then '=' so encode these too. |
| 170 | .replace( /&/g, '%26' ) |
| 171 | .replace( /=/g, '%3D' ) |
| 172 | ); |
| 173 | return params.get( 'q' ); |
| 174 | }, |
| 175 | |
| 176 | /** |
| 177 | * Return a function, that, as long as it continues to be invoked, will not |
| 178 | * be triggered. The function will be called after it stops being called for |
| 179 | * N milliseconds. If `immediate` is passed, trigger the function on the |
| 180 | * leading edge, instead of the trailing. |
| 181 | * |
| 182 | * Ported from Underscore.js 1.5.2, Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud |
| 183 | * and Investigative Reporters & Editors, distributed under the MIT license, from |
| 184 | * <https://github.com/jashkenas/underscore/blob/1.5.2/underscore.js#L689>. |
| 185 | * |
| 186 | * @since 1.34 |
| 187 | * @param {Function} func Function to debounce |
| 188 | * @param {number} [wait=0] Wait period in milliseconds |
| 189 | * @param {boolean} [immediate] Trigger on leading edge |
| 190 | * @return {Function} Debounced function |
| 191 | */ |
| 192 | debounce: function ( func, wait, immediate ) { |
| 193 | // Old signature (wait, func). |
| 194 | if ( typeof func === 'number' ) { |
| 195 | const tmpWait = wait; |
| 196 | wait = func; |
| 197 | func = tmpWait; |
| 198 | } |
| 199 | let timeout; |
| 200 | return function () { |
| 201 | const context = this, |
| 202 | args = arguments, |
| 203 | later = function () { |
| 204 | timeout = null; |
| 205 | if ( !immediate ) { |
| 206 | func.apply( context, args ); |
| 207 | } |
| 208 | }; |
| 209 | if ( immediate && !timeout ) { |
| 210 | func.apply( context, args ); |
| 211 | } |
| 212 | if ( !timeout || wait ) { |
| 213 | clearTimeout( timeout ); |
| 214 | timeout = setTimeout( later, wait ); |
| 215 | } |
| 216 | }; |
| 217 | }, |
| 218 | |
| 219 | /** |
| 220 | * Return a function, that, when invoked, will only be triggered at most once |
| 221 | * during a given window of time. If called again during that window, it will |
| 222 | * wait until the window ends and then trigger itself again. |
| 223 | * |
| 224 | * As it's not knowable to the caller whether the function will actually run |
| 225 | * when the wrapper is called, return values from the function are entirely |
| 226 | * discarded. |
| 227 | * |
| 228 | * Ported from OOUI. |
| 229 | * |
| 230 | * @param {Function} func Function to throttle |
| 231 | * @param {number} wait Throttle window length, in milliseconds |
| 232 | * @return {Function} Throttled function |
| 233 | */ |
| 234 | throttle: function ( func, wait ) { |
| 235 | let context, args, timeout, |
| 236 | previous = Date.now() - wait; |
| 237 | const run = function () { |
| 238 | timeout = null; |
| 239 | previous = Date.now(); |
| 240 | func.apply( context, args ); |
| 241 | }; |
| 242 | return function () { |
| 243 | // Check how long it's been since the last time the function was |
| 244 | // called, and whether it's more or less than the requested throttle |
| 245 | // period. If it's less, run the function immediately. If it's more, |
| 246 | // set a timeout for the remaining time -- but don't replace an |
| 247 | // existing timeout, since that'd indefinitely prolong the wait. |
| 248 | const remaining = Math.max( wait - ( Date.now() - previous ), 0 ); |
| 249 | context = this; |
| 250 | args = arguments; |
| 251 | if ( !timeout ) { |
| 252 | // If time is up, do setTimeout( run, 0 ) so the function |
| 253 | // always runs asynchronously, just like Promise#then . |
| 254 | timeout = setTimeout( run, remaining ); |
| 255 | } |
| 256 | }; |
| 257 | }, |
| 258 | |
| 259 | /** |
| 260 | * Encode page titles in a way that matches `wfUrlencode` in PHP. |
| 261 | * |
| 262 | * This is important both for readability and consistency in the user experience, |
| 263 | * as well as for caching. If URLs are not formatted in the canonical way, they |
| 264 | * may be subject to drastically shorter cache durations and/or miss automatic |
| 265 | * purging after edits, thus leading to stale content being served from a |
| 266 | * non-canonical URL. |
| 267 | * |
| 268 | * @method |
| 269 | * @param {string} str String to be encoded. |
| 270 | * @return {string} Encoded string |
| 271 | */ |
| 272 | wikiUrlencode: mw.internalWikiUrlencode, |
| 273 | |
| 274 | /** |
| 275 | * Get the URL to a given local wiki page name. |
| 276 | * |
| 277 | * @param {string|null} [pageName=wgPageName] Page name |
| 278 | * @param {Object} [params] A mapping of query parameter names to values, |
| 279 | * e.g. `{ action: 'edit' }` |
| 280 | * @return {string} URL, relative to `wgServer`. |
| 281 | */ |
| 282 | getUrl: function ( pageName, params ) { |
| 283 | let url, query, fragment, |
| 284 | title = typeof pageName === 'string' ? pageName : mw.config.get( 'wgPageName' ); |
| 285 | |
| 286 | // Find any fragment |
| 287 | const fragmentIdx = title.indexOf( '#' ); |
| 288 | if ( fragmentIdx !== -1 ) { |
| 289 | fragment = title.slice( fragmentIdx + 1 ); |
| 290 | // Exclude the fragment from the page name |
| 291 | title = title.slice( 0, fragmentIdx ); |
| 292 | } |
| 293 | |
| 294 | // Produce query string |
| 295 | if ( params ) { |
| 296 | query = $.param( params ); |
| 297 | } |
| 298 | |
| 299 | if ( !title && fragment ) { |
| 300 | // If only a fragment was given, make a fragment-only link (T288415) |
| 301 | url = ''; |
| 302 | } else if ( query ) { |
| 303 | url = title ? |
| 304 | util.wikiScript() + '?title=' + util.wikiUrlencode( title ) + '&' + query : |
| 305 | util.wikiScript() + '?' + query; |
| 306 | } else { |
| 307 | // Specify a function as the replacement, |
| 308 | // so that "$" characters in title are not interpreted. |
| 309 | url = mw.config.get( 'wgArticlePath' ) |
| 310 | .replace( '$1', () => util.wikiUrlencode( title ) ); |
| 311 | } |
| 312 | |
| 313 | // Append the encoded fragment |
| 314 | if ( fragment ) { |
| 315 | url += '#' + util.escapeIdForLink( fragment ); |
| 316 | } |
| 317 | |
| 318 | return url; |
| 319 | }, |
| 320 | |
| 321 | /** |
| 322 | * Get URL to a MediaWiki entry point. |
| 323 | * |
| 324 | * Similar to `wfScript()` in PHP. |
| 325 | * |
| 326 | * @since 1.18 |
| 327 | * @param {string} [str="index"] Name of entry point (e.g. 'index' or 'api') |
| 328 | * @return {string} URL to the script file (e.g. `/w/api.php`) |
| 329 | */ |
| 330 | wikiScript: function ( str ) { |
| 331 | if ( !str || str === 'index' ) { |
| 332 | return mw.config.get( 'wgScript' ); |
| 333 | } else if ( str === 'load' ) { |
| 334 | return config.LoadScript; |
| 335 | } else { |
| 336 | return mw.config.get( 'wgScriptPath' ) + '/' + str + '.php'; |
| 337 | } |
| 338 | }, |
| 339 | |
| 340 | /** |
| 341 | * Append a new style block to the head and return the CSSStyleSheet object. |
| 342 | * |
| 343 | * To access the `<style>` element, reference `sheet.ownerNode`, or call |
| 344 | * the {@link mw.loader.addStyleTag} method directly. |
| 345 | * |
| 346 | * This function returns the CSSStyleSheet object for convenience with features |
| 347 | * that are managed at that level, such as toggling of styles: |
| 348 | * ``` |
| 349 | * var sheet = util.addCSS( '.foobar { display: none; }' ); |
| 350 | * $( '#myButton' ).click( function () { |
| 351 | * // Toggle the sheet on and off |
| 352 | * sheet.disabled = !sheet.disabled; |
| 353 | * } ); |
| 354 | * ``` |
| 355 | * |
| 356 | * See also [MDN: CSSStyleSheet](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet). |
| 357 | * |
| 358 | * @param {string} text CSS to be appended |
| 359 | * @return {CSSStyleSheet} The sheet object |
| 360 | */ |
| 361 | addCSS: function ( text ) { |
| 362 | const s = mw.loader.addStyleTag( text ); |
| 363 | return s.sheet; |
| 364 | }, |
| 365 | |
| 366 | /** |
| 367 | * Get the value for a given URL query parameter. |
| 368 | * |
| 369 | * @example |
| 370 | * mw.util.getParamValue( 'foo', '/?foo=x' ); // "x" |
| 371 | * mw.util.getParamValue( 'foo', '/?foo=' ); // "" |
| 372 | * mw.util.getParamValue( 'foo', '/' ); // null |
| 373 | * |
| 374 | * @param {string} param The parameter name. |
| 375 | * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location. |
| 376 | * @return {string|null} Parameter value, or null if parameter was not found. |
| 377 | */ |
| 378 | getParamValue: function ( param, url ) { |
| 379 | // Get last match, stop at hash |
| 380 | |
| 381 | const re = new RegExp( '^[^#]*[&?]' + util.escapeRegExp( param ) + '=([^&#]*)' ), |
| 382 | m = re.exec( url !== undefined ? url : location.href ); |
| 383 | |
| 384 | if ( m ) { |
| 385 | // Beware that decodeURIComponent is not required to understand '+' |
| 386 | // by spec, as encodeURIComponent does not produce it. |
| 387 | try { |
| 388 | return decodeURIComponent( m[ 1 ].replace( /\+/g, '%20' ) ); |
| 389 | } catch ( e ) { |
| 390 | // catch URIError if parameter is invalid UTF-8 |
| 391 | // due to malformed or double-decoded values (T106244), |
| 392 | // e.g. "Autom%F3vil" instead of "Autom%C3%B3vil". |
| 393 | } |
| 394 | } |
| 395 | return null; |
| 396 | }, |
| 397 | |
| 398 | /** |
| 399 | * Get the value for an array query parameter, combined according to similar rules as PHP uses. |
| 400 | * Currently this does not handle associative or multi-dimensional arrays, but that may be |
| 401 | * improved in the future. |
| 402 | * |
| 403 | * @example |
| 404 | * mw.util.getArrayParam( 'foo', new URLSearchParams( '?foo[0]=a&foo[1]=b' ) ); // [ 'a', 'b' ] |
| 405 | * mw.util.getArrayParam( 'foo', new URLSearchParams( '?foo[]=a&foo[]=b' ) ); // [ 'a', 'b' ] |
| 406 | * mw.util.getArrayParam( 'foo', new URLSearchParams( '?foo=a' ) ); // null |
| 407 | * |
| 408 | * @param {string} param The parameter name. |
| 409 | * @param {URLSearchParams} [params] Parsed URL parameters to search through, defaulting to the current browsing location. |
| 410 | * @return {string[]|null} Parameter value, or null if parameter was not found. |
| 411 | */ |
| 412 | getArrayParam: function ( param, params ) { |
| 413 | |
| 414 | const paramRe = new RegExp( '^' + util.escapeRegExp( param ) + '\\[(\\d*)\\]$' ); |
| 415 | |
| 416 | if ( !params ) { |
| 417 | params = new URLSearchParams( location.search ); |
| 418 | } |
| 419 | |
| 420 | const arr = []; |
| 421 | params.forEach( ( v, k ) => { |
| 422 | const paramMatch = k.match( paramRe ); |
| 423 | if ( paramMatch ) { |
| 424 | let i = paramMatch[ 1 ]; |
| 425 | if ( i === '' ) { |
| 426 | // If no explicit index, append at the end |
| 427 | i = arr.length; |
| 428 | } |
| 429 | arr[ i ] = v; |
| 430 | } |
| 431 | } ); |
| 432 | |
| 433 | return arr.length ? arr : null; |
| 434 | }, |
| 435 | |
| 436 | /** |
| 437 | * The content wrapper of the skin (`.mw-body`, for example). |
| 438 | * |
| 439 | * Populated on document ready. To use this property, |
| 440 | * wait for `$.ready` and be sure to have a module dependency on |
| 441 | * `mediawiki.util` which will ensure |
| 442 | * your document ready handler fires after initialization. |
| 443 | * |
| 444 | * Because of the lazy-initialised nature of this property, |
| 445 | * you're discouraged from using it. |
| 446 | * |
| 447 | * If you need just the wikipage content (not any of the |
| 448 | * extra elements output by the skin), use `$( '#mw-content-text' )` |
| 449 | * instead. Or listen to {@link event:'wikipage.content' wikipage.content} |
| 450 | * which will allow your code to re-run when the page changes (e.g. live preview |
| 451 | * or re-render after ajax save). |
| 452 | * |
| 453 | * @type {jQuery} |
| 454 | */ |
| 455 | $content: null, |
| 456 | |
| 457 | /** |
| 458 | * Hide a portlet. |
| 459 | * |
| 460 | * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal') |
| 461 | */ |
| 462 | hidePortlet: function ( portletId ) { |
| 463 | const portlet = document.getElementById( portletId ); |
| 464 | if ( portlet ) { |
| 465 | portlet.classList.add( 'emptyPortlet' ); |
| 466 | } |
| 467 | }, |
| 468 | |
| 469 | /** |
| 470 | * Whether a portlet is visible. |
| 471 | * |
| 472 | * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal') |
| 473 | * @return {boolean} |
| 474 | */ |
| 475 | isPortletVisible: function ( portletId ) { |
| 476 | const portlet = document.getElementById( portletId ); |
| 477 | return portlet && !portlet.classList.contains( 'emptyPortlet' ); |
| 478 | }, |
| 479 | |
| 480 | /** |
| 481 | * Reveal a portlet if it is hidden. |
| 482 | * |
| 483 | * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal') |
| 484 | */ |
| 485 | showPortlet: function ( portletId ) { |
| 486 | const portlet = document.getElementById( portletId ); |
| 487 | if ( portlet ) { |
| 488 | portlet.classList.remove( 'emptyPortlet' ); |
| 489 | } |
| 490 | }, |
| 491 | |
| 492 | /** |
| 493 | * Clears the entire subtitle if present in the page. Used for refreshing subtitle |
| 494 | * after edit with response from parse API. |
| 495 | */ |
| 496 | clearSubtitle: function () { |
| 497 | const subtitle = document.getElementById( 'mw-content-subtitle' ); |
| 498 | if ( subtitle ) { |
| 499 | subtitle.innerHTML = ''; |
| 500 | } |
| 501 | }, |
| 502 | |
| 503 | /** |
| 504 | * Create a message box element. Callers are responsible for ensuring suitable Codex styles |
| 505 | * have been added to the page e.g. mediawiki.codex.messagebox.styles. |
| 506 | * |
| 507 | * @since 1.43 |
| 508 | * @param {string|Element} textOrElement text or node. |
| 509 | * @param {string} [type] defaults to notice. |
| 510 | * @param {boolean} [inline] whether the notice should be inline. |
| 511 | * @return {Element} |
| 512 | */ |
| 513 | messageBox: function ( textOrElement, type = 'notice', inline = false ) { |
| 514 | const msgBoxElement = document.createElement( 'div' ); |
| 515 | msgBoxElement.classList.add( 'cdx-message' ); |
| 516 | if ( [ 'error', 'warning', 'success', 'notice' ].indexOf( type ) > -1 ) { |
| 517 | // The following CSS classes are used here: |
| 518 | // * cdx-message--notice |
| 519 | // * cdx-message--warning |
| 520 | // * cdx-message--error |
| 521 | msgBoxElement.classList.add( `cdx-message--${ type }` ); |
| 522 | } |
| 523 | msgBoxElement.classList.add( inline ? 'cdx-message--inline' : 'cdx-message--block' ); |
| 524 | msgBoxElement.setAttribute( 'aria-live', 'polite' ); |
| 525 | const iconElement = document.createElement( 'span' ); |
| 526 | iconElement.classList.add( 'cdx-message__icon' ); |
| 527 | const contentElement = document.createElement( 'div' ); |
| 528 | contentElement.classList.add( 'cdx-message__content' ); |
| 529 | if ( typeof textOrElement === 'string' ) { |
| 530 | contentElement.textContent = textOrElement; |
| 531 | } else { |
| 532 | contentElement.appendChild( textOrElement ); |
| 533 | } |
| 534 | msgBoxElement.appendChild( iconElement ); |
| 535 | msgBoxElement.appendChild( contentElement ); |
| 536 | return msgBoxElement; |
| 537 | }, |
| 538 | |
| 539 | /** |
| 540 | * Add content to the subtitle of the skin. |
| 541 | * |
| 542 | * @param {HTMLElement|string} nodeOrHTMLString |
| 543 | * @return {boolean} Whether the subtitle was updated |
| 544 | */ |
| 545 | addSubtitle: function ( nodeOrHTMLString ) { |
| 546 | const subtitle = document.getElementById( 'mw-content-subtitle' ); |
| 547 | if ( !subtitle ) { |
| 548 | return false; |
| 549 | } |
| 550 | if ( typeof nodeOrHTMLString === 'string' ) { |
| 551 | subtitle.innerHTML += nodeOrHTMLString; |
| 552 | } else { |
| 553 | subtitle.appendChild( nodeOrHTMLString ); |
| 554 | } |
| 555 | return true; |
| 556 | }, |
| 557 | |
| 558 | /** |
| 559 | * Creates a detached portlet Element in the skin with no elements. |
| 560 | * |
| 561 | * @example |
| 562 | * // Create a portlet with 2 menu items that is styled as a dropdown in certain skins. |
| 563 | * const p = mw.util.addPortlet( 'p-myportlet', 'My label', '#p-cactions' ); |
| 564 | * mw.util.addPortletLink( 'p-myportlet', '#', 'Link 1' ); |
| 565 | * mw.util.addPortletLink( 'p-myportlet', '#', 'Link 2' ); |
| 566 | * @param {string} id of the new portlet. |
| 567 | * @param {string} [label] of the new portlet. |
| 568 | * @param {string} [selectorHint] selector of the element the new portlet would like to |
| 569 | * be inserted near. Typically the portlet will be inserted after this selector, but in some |
| 570 | * skins, the skin may relocate the element when provided to the closest available space. |
| 571 | * If this argument is not passed then the caller is responsible for appending the element |
| 572 | * to the DOM before using addPortletLink. |
| 573 | * To add a portlet in an exact position do not rely on this parameter, instead using the return |
| 574 | * element (make sure to also assign the result to a variable), use |
| 575 | * ```p.parentNode.appendChild( p );``` |
| 576 | * When provided, skins can use the parameter to infer information about how the user intended |
| 577 | * the menu to be rendered. For example, in vector and vector-2022 targeting '#p-cactions' will |
| 578 | * result in the creation of a dropdown. |
| 579 | * @fires Hooks~'util.addPortlet' |
| 580 | * @return {HTMLElement|null} will be null if it was not possible to create an portlet with |
| 581 | * the required information e.g. the selector given in `selectorHint` parameter could not be resolved |
| 582 | * to an existing element in the page. |
| 583 | */ |
| 584 | addPortlet: function ( id, label, selectorHint ) { |
| 585 | const portlet = document.createElement( 'div' ); |
| 586 | // These classes should be kept in sync with includes/skins/components/SkinComponentMenu.php. |
| 587 | // eslint-disable-next-line mediawiki/class-doc |
| 588 | portlet.classList.add( 'mw-portlet', 'mw-portlet-' + id, 'emptyPortlet', |
| 589 | // Additional class is added to allow skins to track portlets added via this mechanism. |
| 590 | 'mw-portlet-js' |
| 591 | ); |
| 592 | portlet.id = id; |
| 593 | if ( label ) { |
| 594 | const labelNode = document.createElement( 'label' ); |
| 595 | labelNode.textContent = label; |
| 596 | portlet.appendChild( labelNode ); |
| 597 | } |
| 598 | const listWrapper = document.createElement( 'div' ); |
| 599 | const list = document.createElement( 'ul' ); |
| 600 | listWrapper.appendChild( list ); |
| 601 | portlet.appendChild( listWrapper ); |
| 602 | if ( selectorHint ) { |
| 603 | let referenceNode; |
| 604 | try { |
| 605 | referenceNode = document.querySelector( selectorHint ); |
| 606 | } catch ( e ) { |
| 607 | // CSS selector not supported by browser. |
| 608 | } |
| 609 | if ( referenceNode ) { |
| 610 | const parentNode = referenceNode.parentNode; |
| 611 | parentNode.insertBefore( portlet, referenceNode ); |
| 612 | } else { |
| 613 | return null; |
| 614 | } |
| 615 | } |
| 616 | /** |
| 617 | * Fires when a portlet is successfully created. |
| 618 | * |
| 619 | * @event ~'util.addPortlet' |
| 620 | * @memberof Hooks |
| 621 | * @param {HTMLElement} portlet the portlet that was created. |
| 622 | * @param {string|null} selectorHint the css selector used to append to the DOM. |
| 623 | * |
| 624 | * @example |
| 625 | * mw.hook( 'util.addPortlet' ).add( ( p ) => { |
| 626 | * p.style.border = 'solid 1px black'; |
| 627 | * } ); |
| 628 | */ |
| 629 | mw.hook( 'util.addPortlet' ).fire( portlet, selectorHint ); |
| 630 | return portlet; |
| 631 | }, |
| 632 | /** |
| 633 | * Add a link to a portlet menu on the page. |
| 634 | * |
| 635 | * The portlets that are supported include: |
| 636 | * |
| 637 | * - p-cactions (Content actions) |
| 638 | * - p-personal (Personal tools) |
| 639 | * - p-navigation (Navigation) |
| 640 | * - p-tb (Toolbox) |
| 641 | * - p-associated-pages (For namespaces and special page tabs on supported skins) |
| 642 | * - p-namespaces (For namespaces on legacy skins) |
| 643 | * |
| 644 | * Additional menus can be discovered through the following code: |
| 645 | * ```$('.mw-portlet').toArray().map((el) => el.id);``` |
| 646 | * |
| 647 | * Menu availability varies by skin, wiki, and current page. |
| 648 | * |
| 649 | * The first three parameters are required, the others are optional and |
| 650 | * may be null. Though providing an id and tooltip is recommended. |
| 651 | * |
| 652 | * By default, the new link will be added to the end of the menu. To |
| 653 | * add the link before an existing item, pass the DOM node or a CSS selector |
| 654 | * for that item, e.g. `'#foobar'` or `document.getElementById( 'foobar' )`. |
| 655 | * ``` |
| 656 | * mw.util.addPortletLink( |
| 657 | * 'p-tb', 'https://www.mediawiki.org/', |
| 658 | * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print' |
| 659 | * ); |
| 660 | * |
| 661 | * var node = mw.util.addPortletLink( |
| 662 | * 'p-tb', |
| 663 | * mw.util.getUrl( 'Special:Example' ), |
| 664 | * 'Example' |
| 665 | * ); |
| 666 | * $( node ).on( 'click', function ( e ) { |
| 667 | * console.log( 'Example' ); |
| 668 | * e.preventDefault(); |
| 669 | * } ); |
| 670 | * ``` |
| 671 | * |
| 672 | * Remember that to call this inside a user script, you may have to ensure the |
| 673 | * `mediawiki.util` is loaded first: |
| 674 | * ``` |
| 675 | * $.when( mw.loader.using( [ 'mediawiki.util' ] ), $.ready ).then( function () { |
| 676 | * mw.util.addPortletLink( 'p-tb', 'https://www.mediawiki.org/', 'mediawiki.org' ); |
| 677 | * } ); |
| 678 | * ``` |
| 679 | * |
| 680 | * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal') |
| 681 | * @param {string} href Link URL |
| 682 | * @param {string} text Link text |
| 683 | * @param {string} [id] ID of the list item, should be unique and preferably have |
| 684 | * the appropriate prefix ('ca-', 'pt-', 'n-' or 't-') |
| 685 | * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix |
| 686 | * @param {string} [accesskey] Access key to activate this link. One character only, |
| 687 | * avoid conflicts with other links. Use `$( '[accesskey=x]' )` in the console to |
| 688 | * see if 'x' is already used. |
| 689 | * @param {HTMLElement|jQuery|string} [nextnode] Element that the new item should be added before. |
| 690 | * Must be another item in the same list, it will be ignored otherwise. |
| 691 | * Can be specified as DOM reference, as jQuery object, or as CSS selector string. |
| 692 | * @fires Hooks~'util.addPortletLink' |
| 693 | * @return {HTMLElement|null} The added list item, or null if no element was added. |
| 694 | */ |
| 695 | addPortletLink: function ( portletId, href, text, id, tooltip, accesskey, nextnode ) { |
| 696 | if ( !portletId ) { |
| 697 | // Avoid confusing id="undefined" lookup |
| 698 | return null; |
| 699 | } |
| 700 | |
| 701 | const portlet = document.getElementById( portletId ); |
| 702 | if ( !portlet ) { |
| 703 | // Invalid portlet ID |
| 704 | return null; |
| 705 | } |
| 706 | |
| 707 | // Setup the anchor tag and set any the properties |
| 708 | const link = document.createElement( 'a' ); |
| 709 | link.href = href; |
| 710 | |
| 711 | let linkChild = document.createTextNode( text ); |
| 712 | let i = portletLinkOptions[ 'text-wrapper' ].length; |
| 713 | // Wrap link using text-wrapper option if provided |
| 714 | // Iterate backward since the wrappers are declared from outer to inner, |
| 715 | // and we build it up from the inside out. |
| 716 | while ( i-- ) { |
| 717 | const wrapper = portletLinkOptions[ 'text-wrapper' ][ i ]; |
| 718 | const wrapperElement = document.createElement( wrapper.tag ); |
| 719 | if ( wrapper.attributes ) { |
| 720 | $( wrapperElement ).attr( wrapper.attributes ); |
| 721 | } |
| 722 | wrapperElement.appendChild( linkChild ); |
| 723 | linkChild = wrapperElement; |
| 724 | } |
| 725 | link.appendChild( linkChild ); |
| 726 | |
| 727 | if ( tooltip ) { |
| 728 | link.title = tooltip; |
| 729 | } |
| 730 | if ( accesskey ) { |
| 731 | link.accessKey = accesskey; |
| 732 | } |
| 733 | |
| 734 | // Unhide portlet if it was hidden before |
| 735 | util.showPortlet( portletId ); |
| 736 | |
| 737 | const item = $( '<li>' ).append( link )[ 0 ]; |
| 738 | // mw-list-item-js distinguishes portlet links added via javascript and the server |
| 739 | item.className = 'mw-list-item mw-list-item-js'; |
| 740 | if ( id ) { |
| 741 | item.id = id; |
| 742 | } |
| 743 | |
| 744 | // Select the first (most likely only) unordered list inside the portlet |
| 745 | let ul = portlet.tagName.toLowerCase() === 'ul' ? portlet : portlet.querySelector( 'ul' ); |
| 746 | if ( !ul ) { |
| 747 | // If it didn't have an unordered list yet, create one |
| 748 | ul = document.createElement( 'ul' ); |
| 749 | const portletDiv = portlet.querySelector( 'div' ); |
| 750 | if ( portletDiv ) { |
| 751 | // Support: Legacy skins have a div (such as div.body or div.pBody). |
| 752 | // Append the <ul> to that. |
| 753 | portletDiv.appendChild( ul ); |
| 754 | } else { |
| 755 | // Append it to the portlet directly |
| 756 | portlet.appendChild( ul ); |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | let next; |
| 761 | if ( nextnode && ( typeof nextnode === 'string' || nextnode.nodeType || nextnode.jquery ) ) { |
| 762 | // eslint-disable-next-line no-jquery/variable-pattern |
| 763 | nextnode = $( ul ).find( nextnode ); |
| 764 | if ( nextnode.length === 1 && nextnode[ 0 ].parentNode === ul ) { |
| 765 | // Insertion point: Before nextnode |
| 766 | nextnode.before( item ); |
| 767 | next = true; |
| 768 | } |
| 769 | // Else: Invalid nextnode value (no match, more than one match, or not a direct child) |
| 770 | // Else: Invalid nextnode type |
| 771 | } |
| 772 | |
| 773 | if ( !next ) { |
| 774 | // Insertion point: End of list (default) |
| 775 | ul.appendChild( item ); |
| 776 | } |
| 777 | |
| 778 | // Update tooltip for the access key after inserting into DOM |
| 779 | // to get a localized access key label (T69946). |
| 780 | if ( accesskey ) { |
| 781 | $( link ).updateTooltipAccessKeys(); |
| 782 | } |
| 783 | |
| 784 | /** |
| 785 | * Fires when a portlet link is successfully created. |
| 786 | * |
| 787 | * @event ~'util.addPortletLink' |
| 788 | * @memberof Hooks |
| 789 | * @param {HTMLElement} item the portlet link that was created. |
| 790 | * @param {Object} information about the item include id. |
| 791 | * |
| 792 | * @example |
| 793 | * mw.hook( 'util.addPortletLink' ).add( ( link ) => { |
| 794 | * const span = $( '<span class="icon">' ); |
| 795 | * link.appendChild( span ); |
| 796 | * } ); |
| 797 | */ |
| 798 | mw.hook( 'util.addPortletLink' ).fire( item, { |
| 799 | id: id |
| 800 | } ); |
| 801 | return item; |
| 802 | }, |
| 803 | |
| 804 | /** |
| 805 | * Validate a string as representing a valid e-mail address. |
| 806 | * |
| 807 | * This validation is based on the HTML5 specification. |
| 808 | * |
| 809 | * @example |
| 810 | * mw.util.validateEmail( "[email protected]" ) === true; |
| 811 | * |
| 812 | * @param {string} email E-mail address |
| 813 | * @return {boolean|null} True if valid, false if invalid, null if `email` was empty. |
| 814 | */ |
| 815 | validateEmail: function ( email ) { |
| 816 | if ( email === '' ) { |
| 817 | return null; |
| 818 | } |
| 819 | |
| 820 | // HTML5 defines a string as valid e-mail address if it matches |
| 821 | // the ABNF: |
| 822 | // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str ) |
| 823 | // With: |
| 824 | // - atext : defined in RFC 5322 section 3.2.3 |
| 825 | // - ldh-str : defined in RFC 1034 section 3.5 |
| 826 | // |
| 827 | // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68) |
| 828 | // First, define the RFC 5322 'atext' which is pretty easy: |
| 829 | // atext = ALPHA / DIGIT / ; Printable US-ASCII |
| 830 | // "!" / "#" / ; characters not including |
| 831 | // "$" / "%" / ; specials. Used for atoms. |
| 832 | // "&" / "'" / |
| 833 | // "*" / "+" / |
| 834 | // "-" / "/" / |
| 835 | // "=" / "?" / |
| 836 | // "^" / "_" / |
| 837 | // "`" / "{" / |
| 838 | // "|" / "}" / |
| 839 | // "~" |
| 840 | const rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~'; |
| 841 | |
| 842 | // Next define the RFC 1034 'ldh-str' |
| 843 | // <domain> ::= <subdomain> | " " |
| 844 | // <subdomain> ::= <label> | <subdomain> "." <label> |
| 845 | // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] |
| 846 | // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> |
| 847 | // <let-dig-hyp> ::= <let-dig> | "-" |
| 848 | // <let-dig> ::= <letter> | <digit> |
| 849 | const rfc1034LdhStr = 'a-z0-9\\-'; |
| 850 | |
| 851 | const html5EmailRegexp = new RegExp( |
| 852 | // start of string |
| 853 | '^' + |
| 854 | // User part which is liberal :p |
| 855 | '[' + rfc5322Atext + '\\.]+' + |
| 856 | // 'at' |
| 857 | '@' + |
| 858 | // Domain first part |
| 859 | '[' + rfc1034LdhStr + ']+' + |
| 860 | // Optional second part and following are separated by a dot |
| 861 | '(?:\\.[' + rfc1034LdhStr + ']+)*' + |
| 862 | // End of string |
| 863 | '$', |
| 864 | // RegExp is case insensitive |
| 865 | 'i' |
| 866 | ); |
| 867 | return ( email.match( html5EmailRegexp ) !== null ); |
| 868 | }, |
| 869 | |
| 870 | /** |
| 871 | * Whether a string is a valid IPv4 address or not. |
| 872 | * |
| 873 | * Based on \Wikimedia\IPUtils::isIPv4 in PHP. |
| 874 | * |
| 875 | * @example |
| 876 | * // Valid |
| 877 | * mw.util.isIPv4Address( '80.100.20.101' ); |
| 878 | * mw.util.isIPv4Address( '192.168.1.101' ); |
| 879 | * |
| 880 | * // Invalid |
| 881 | * mw.util.isIPv4Address( '192.0.2.0/24' ); |
| 882 | * mw.util.isIPv4Address( 'hello' ); |
| 883 | * |
| 884 | * @param {string} address |
| 885 | * @param {boolean} [allowBlock=false] |
| 886 | * @return {boolean} |
| 887 | */ |
| 888 | isIPv4Address: function ( address, allowBlock ) { |
| 889 | |
| 890 | if ( typeof address !== 'string' ) { |
| 891 | return false; |
| 892 | } |
| 893 | |
| 894 | const RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])'; |
| 895 | const RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE; |
| 896 | const block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : ''; |
| 897 | |
| 898 | return ( new RegExp( '^' + RE_IP_ADD + block + '$' ).test( address ) ); |
| 899 | }, |
| 900 | |
| 901 | /** |
| 902 | * Whether a string is a valid IPv6 address or not. |
| 903 | * |
| 904 | * Based on \Wikimedia\IPUtils::isIPv6 in PHP. |
| 905 | * |
| 906 | * @example |
| 907 | * // Valid |
| 908 | * mw.util.isIPv6Address( '2001:db8:a:0:0:0:0:0' ); |
| 909 | * mw.util.isIPv6Address( '2001:db8:a::' ); |
| 910 | * |
| 911 | * // Invalid |
| 912 | * mw.util.isIPv6Address( '2001:db8:a::/32' ); |
| 913 | * mw.util.isIPv6Address( 'hello' ); |
| 914 | * |
| 915 | * @param {string} address |
| 916 | * @param {boolean} [allowBlock=false] |
| 917 | * @return {boolean} |
| 918 | */ |
| 919 | isIPv6Address: function ( address, allowBlock ) { |
| 920 | if ( typeof address !== 'string' ) { |
| 921 | return false; |
| 922 | } |
| 923 | |
| 924 | const block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : ''; |
| 925 | let RE_IPV6_ADD = |
| 926 | '(?:' + // starts with "::" (including "::") |
| 927 | ':(?::|(?::' + |
| 928 | '[0-9A-Fa-f]{1,4}' + |
| 929 | '){1,7})' + |
| 930 | '|' + // ends with "::" (except "::") |
| 931 | '[0-9A-Fa-f]{1,4}' + |
| 932 | '(?::' + |
| 933 | '[0-9A-Fa-f]{1,4}' + |
| 934 | '){0,6}::' + |
| 935 | '|' + // contains no "::" |
| 936 | '[0-9A-Fa-f]{1,4}' + |
| 937 | '(?::' + |
| 938 | '[0-9A-Fa-f]{1,4}' + |
| 939 | '){7}' + |
| 940 | ')'; |
| 941 | |
| 942 | if ( new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) ) { |
| 943 | return true; |
| 944 | } |
| 945 | |
| 946 | // contains one "::" in the middle (single '::' check below) |
| 947 | RE_IPV6_ADD = |
| 948 | '[0-9A-Fa-f]{1,4}' + |
| 949 | '(?:::?' + |
| 950 | '[0-9A-Fa-f]{1,4}' + |
| 951 | '){1,6}'; |
| 952 | |
| 953 | return ( |
| 954 | |
| 955 | new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) && |
| 956 | /::/.test( address ) && |
| 957 | !/::.*::/.test( address ) |
| 958 | ); |
| 959 | }, |
| 960 | |
| 961 | /** |
| 962 | * Check whether a string is a valid IP address. |
| 963 | * |
| 964 | * @since 1.25 |
| 965 | * @param {string} address String to check |
| 966 | * @param {boolean} [allowBlock=false] If a block of IPs should be allowed |
| 967 | * @return {boolean} |
| 968 | */ |
| 969 | isIPAddress: function ( address, allowBlock ) { |
| 970 | return util.isIPv4Address( address, allowBlock ) || |
| 971 | util.isIPv6Address( address, allowBlock ); |
| 972 | }, |
| 973 | |
| 974 | /** |
| 975 | * @typedef {Object} ResizeableThumbnailUrl |
| 976 | * @property {string} name File name (same format as Title.getMainText()). |
| 977 | * @property {number} [width] Thumbnail width, in pixels. Null when the file is not |
| 978 | * a thumbnail. |
| 979 | * @property {function(number):string} [resizeUrl] A function that takes a width |
| 980 | * parameter and returns a thumbnail URL (URL-encoded) with that width. The width |
| 981 | * parameter must be smaller than the width of the original image (or equal to it; that |
| 982 | * only works if MediaHandler::mustRender returns true for the file). Null when the |
| 983 | * file in the original URL is not a thumbnail. |
| 984 | * On wikis with $wgGenerateThumbnailOnParse set to true, this will fall back to using |
| 985 | * Special:Redirect which is less efficient. Otherwise, it is a direct thumbnail URL. |
| 986 | */ |
| 987 | |
| 988 | /** |
| 989 | * Parse the URL of an image uploaded to MediaWiki, or a thumbnail for such an image, |
| 990 | * and return the image name, thumbnail size and a template that can be used to resize |
| 991 | * the image. |
| 992 | * |
| 993 | * @param {string} url URL to parse (URL-encoded) |
| 994 | * @return {ResizeableThumbnailUrl|null} null if the URL is not a valid MediaWiki |
| 995 | * image/thumbnail URL. |
| 996 | */ |
| 997 | parseImageUrl: function ( url ) { |
| 998 | let name, decodedName, width, urlTemplate; |
| 999 | |
| 1000 | // thumb.php-generated thumbnails |
| 1001 | // thumb.php?f=<name>&w[idth]=<width>[px] |
| 1002 | if ( /thumb\.php/.test( url ) ) { |
| 1003 | decodedName = mw.util.getParamValue( 'f', url ); |
| 1004 | name = encodeURIComponent( decodedName ); |
| 1005 | width = mw.util.getParamValue( 'width', url ) || mw.util.getParamValue( 'w', url ); |
| 1006 | urlTemplate = url.replace( /([&?])w(?:idth)?=[^&]+/g, '' ) + '&width={width}'; |
| 1007 | } else { |
| 1008 | const regexes = [ |
| 1009 | // Thumbnails |
| 1010 | // /<hash prefix>/<name>/[<options>-]<width>-<name*>[.<ext>] |
| 1011 | // where <name*> could be the filename, 'thumbnail.<ext>' (for long filenames) |
| 1012 | // or the base-36 SHA1 of the filename. |
| 1013 | |
| 1014 | /\/[\da-f]\/[\da-f]{2}\/([^\s/]+)\/(?:[^\s/]+-)?(\d+)px-(?:\1|thumbnail|[a-z\d]{31})(\.[^\s/]+)?$/, |
| 1015 | |
| 1016 | // Full size images |
| 1017 | // /<hash prefix>/<name> |
| 1018 | /\/[\da-f]\/[\da-f]{2}\/([^\s/]+)$/, |
| 1019 | |
| 1020 | // Thumbnails in non-hashed upload directories |
| 1021 | // /<name>/[<options>-]<width>-<name*>[.<ext>] |
| 1022 | |
| 1023 | /\/([^\s/]+)\/(?:[^\s/]+-)?(\d+)px-(?:\1|thumbnail|[a-z\d]{31})[^\s/]*$/, |
| 1024 | |
| 1025 | // Full-size images in non-hashed upload directories |
| 1026 | // /<name> |
| 1027 | /\/([^\s/]+)$/ |
| 1028 | ]; |
| 1029 | for ( let i = 0; i < regexes.length; i++ ) { |
| 1030 | const match = url.match( regexes[ i ] ); |
| 1031 | if ( match ) { |
| 1032 | name = match[ 1 ]; |
| 1033 | decodedName = decodeURIComponent( name ); |
| 1034 | width = match[ 2 ] || null; |
| 1035 | break; |
| 1036 | } |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | if ( name ) { |
| 1041 | if ( width !== null ) { |
| 1042 | width = parseInt( width, 10 ) || null; |
| 1043 | } |
| 1044 | if ( config.GenerateThumbnailOnParse ) { |
| 1045 | // The wiki cannot generate thumbnails on demand. Use a special page - this means |
| 1046 | // an extra redirect and PHP request, but it will generate the thumbnail if it does |
| 1047 | // not exist. |
| 1048 | urlTemplate = mw.util.getUrl( 'Special:Redirect/file/' + decodedName, { width: '{width}' } ) |
| 1049 | // getUrl urlencodes the template variable, fix that |
| 1050 | .replace( '%7Bwidth%7D', '{width}' ); |
| 1051 | } else if ( width && !urlTemplate ) { |
| 1052 | // Javascript does not expose regexp capturing group indexes, and the width |
| 1053 | // part could in theory also occur in the filename so hide that first. |
| 1054 | const strippedUrl = url.replace( name, '{name}' ) |
| 1055 | .replace( name, '{name}' ) |
| 1056 | .replace( width + 'px-', '{width}px-' ); |
| 1057 | urlTemplate = strippedUrl.replace( /\{name\}/g, name ); |
| 1058 | } |
| 1059 | return { |
| 1060 | name: decodedName.replace( /_/g, ' ' ), |
| 1061 | width, |
| 1062 | resizeUrl: urlTemplate ? function ( w ) { |
| 1063 | return urlTemplate.replace( '{width}', w ); |
| 1064 | } : null |
| 1065 | }; |
| 1066 | } |
| 1067 | return null; |
| 1068 | }, |
| 1069 | |
| 1070 | /** |
| 1071 | * Adjust the thumbnail size to fit the width steps defined in config via |
| 1072 | * config.ThumbnailSteps, according to whether config.ThumbnailStepsRatio |
| 1073 | * is set. |
| 1074 | * |
| 1075 | * This logic is duplicated server-side in File::adjustThumbWidthForSteps. |
| 1076 | * |
| 1077 | * @param {number} thumbWidth target width in pixels |
| 1078 | * @param {number} originalWidth original file width |
| 1079 | */ |
| 1080 | adjustThumbWidthForSteps( |
| 1081 | thumbWidth, |
| 1082 | originalWidth |
| 1083 | ) { |
| 1084 | const steps = config.ThumbnailSteps; |
| 1085 | const ratio = config.ThumbnailStepsRatio; |
| 1086 | if ( !steps || !ratio ) { |
| 1087 | return thumbWidth; |
| 1088 | } |
| 1089 | |
| 1090 | // Note: non-integral thumbnailStepsRatio values are treated |
| 1091 | // as equivalent to 1 here. This is a transitional setting |
| 1092 | // for content generation and should be ok to ignore client-side. |
| 1093 | |
| 1094 | for ( const widthStep of steps ) { |
| 1095 | if ( widthStep > originalWidth ) { |
| 1096 | // Round up to original width if there is no step between |
| 1097 | // desired thumb width & original file width |
| 1098 | return originalWidth; |
| 1099 | } |
| 1100 | if ( widthStep >= thumbWidth ) { |
| 1101 | return widthStep; |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | // If no step matched, default to target thumb width |
| 1106 | return thumbWidth; |
| 1107 | }, |
| 1108 | |
| 1109 | /** |
| 1110 | * Escape string for safe inclusion in regular expression. |
| 1111 | * |
| 1112 | * The following characters are escaped: |
| 1113 | * |
| 1114 | * \ { } ( ) | . ? * + - ^ $ [ ] |
| 1115 | * |
| 1116 | * @since 1.26; moved to mw.util in 1.34 |
| 1117 | * @param {string} str String to escape |
| 1118 | * @return {string} Escaped string |
| 1119 | */ |
| 1120 | escapeRegExp: function ( str ) { |
| 1121 | // eslint-disable-next-line no-useless-escape |
| 1122 | return str.replace( /([\\{}()|.?*+\-^$\[\]])/g, '\\$1' ); |
| 1123 | }, |
| 1124 | |
| 1125 | /** |
| 1126 | * Convert an IP into a verbose, uppercase, normalized form. |
| 1127 | * |
| 1128 | * Both IPv4 and IPv6 addresses are trimmed. Additionally, |
| 1129 | * IPv6 addresses in octet notation are expanded to 8 words; |
| 1130 | * IPv4 addresses have leading zeros, in each octet, removed. |
| 1131 | * |
| 1132 | * This functionality has been adapted from \Wikimedia\IPUtils::sanitizeIP() |
| 1133 | * |
| 1134 | * @param {string} ip IP address in quad or octet form (CIDR or not). |
| 1135 | * @return {string|null} |
| 1136 | */ |
| 1137 | sanitizeIP: function ( ip ) { |
| 1138 | if ( typeof ip !== 'string' ) { |
| 1139 | return null; |
| 1140 | } |
| 1141 | ip = ip.trim(); |
| 1142 | if ( ip === '' ) { |
| 1143 | return null; |
| 1144 | } |
| 1145 | if ( !this.isIPAddress( ip, true ) ) { |
| 1146 | return ip; |
| 1147 | } |
| 1148 | if ( this.isIPv4Address( ip, true ) ) { |
| 1149 | return ip.replace( /(^|\.)0+(\d)/g, '$1$2' ); |
| 1150 | } |
| 1151 | ip = ip.toUpperCase(); |
| 1152 | const abbrevPos = ip.indexOf( '::' ); |
| 1153 | if ( abbrevPos !== -1 ) { |
| 1154 | const CIDRStart = ip.indexOf( '/' ); |
| 1155 | const addressEnd = ( CIDRStart !== -1 ) ? CIDRStart - 1 : ip.length - 1; |
| 1156 | let repeatStr, extra, pad; |
| 1157 | if ( abbrevPos === 0 ) { |
| 1158 | repeatStr = '0:'; |
| 1159 | extra = ip === '::' ? '0' : ''; |
| 1160 | pad = 9; |
| 1161 | } else if ( abbrevPos === addressEnd - 1 ) { |
| 1162 | repeatStr = ':0'; |
| 1163 | extra = ''; |
| 1164 | pad = 9; |
| 1165 | } else { |
| 1166 | repeatStr = ':0'; |
| 1167 | extra = ':'; |
| 1168 | pad = 8; |
| 1169 | } |
| 1170 | const count = pad - ( ip.split( ':' ).length - 1 ); |
| 1171 | ip = ip.replace( '::', repeatStr.repeat( count ) + extra ); |
| 1172 | } |
| 1173 | return ip.replace( /(^|:)0+(([0-9A-Fa-f]{1,4}))/g, '$1$2' ); |
| 1174 | }, |
| 1175 | |
| 1176 | /** |
| 1177 | * Prettify an IP for display to end users. |
| 1178 | * |
| 1179 | * This will make it more compact and lower-case. |
| 1180 | * |
| 1181 | * This functionality has been adapted from \Wikimedia\IPUtils::prettifyIP() |
| 1182 | * |
| 1183 | * @param {string} ip IP address in quad or octet form (CIDR or not). |
| 1184 | * @return {string|null} |
| 1185 | */ |
| 1186 | prettifyIP: function ( ip ) { |
| 1187 | ip = this.sanitizeIP( ip ); |
| 1188 | if ( ip === null ) { |
| 1189 | return null; |
| 1190 | } |
| 1191 | if ( this.isIPv6Address( ip, true ) ) { |
| 1192 | let cidr, replaceZeros; |
| 1193 | if ( ip.indexOf( '/' ) !== -1 ) { |
| 1194 | const ipCidrSplit = ip.split( '/', 2 ); |
| 1195 | ip = ipCidrSplit[ 0 ]; |
| 1196 | cidr = ipCidrSplit[ 1 ]; |
| 1197 | } else { |
| 1198 | cidr = ''; |
| 1199 | } |
| 1200 | const matches = ip.match( /(?:^|:)0(?::0)+(?:$|:)/g ); |
| 1201 | if ( matches ) { |
| 1202 | replaceZeros = matches[ 0 ]; |
| 1203 | for ( let i = 1; i < matches.length; i++ ) { |
| 1204 | if ( matches[ i ].length > replaceZeros.length ) { |
| 1205 | replaceZeros = matches[ i ]; |
| 1206 | } |
| 1207 | } |
| 1208 | } |
| 1209 | ip = ip.replace( replaceZeros, '::' ); |
| 1210 | |
| 1211 | if ( cidr !== '' ) { |
| 1212 | ip = ip.concat( '/', cidr ); |
| 1213 | } |
| 1214 | ip = ip.toLowerCase(); |
| 1215 | } |
| 1216 | return ip; |
| 1217 | }, |
| 1218 | |
| 1219 | /** |
| 1220 | * Checks if the given username matches $wgAutoCreateTempUser. |
| 1221 | * |
| 1222 | * This functionality has been adapted from MediaWiki\User\TempUser\Pattern::isMatch() |
| 1223 | * |
| 1224 | * @param {string|null} username |
| 1225 | * @return {boolean} |
| 1226 | */ |
| 1227 | isTemporaryUser: function ( username ) { |
| 1228 | // Just return early if temporary accounts are not known about. |
| 1229 | if ( !config.AutoCreateTempUser.enabled && !config.AutoCreateTempUser.known ) { |
| 1230 | return false; |
| 1231 | } |
| 1232 | if ( username === null ) { |
| 1233 | return false; |
| 1234 | } |
| 1235 | /** @type {string|string[]} */ |
| 1236 | let matchPatterns = config.AutoCreateTempUser.matchPattern; |
| 1237 | if ( typeof matchPatterns === 'string' ) { |
| 1238 | matchPatterns = [ matchPatterns ]; |
| 1239 | } else if ( matchPatterns === null ) { |
| 1240 | matchPatterns = [ config.AutoCreateTempUser.genPattern ]; |
| 1241 | } |
| 1242 | for ( let i = 0; i < matchPatterns.length; i++ ) { |
| 1243 | const autoCreateUserMatchPattern = matchPatterns[ i ]; |
| 1244 | // Check each match pattern, and if any matches then return a match. |
| 1245 | const position = autoCreateUserMatchPattern.indexOf( '$1' ); |
| 1246 | |
| 1247 | // '$1' was not found in autoCreateUserMatchPattern |
| 1248 | if ( position === -1 ) { |
| 1249 | return false; |
| 1250 | } |
| 1251 | const prefix = autoCreateUserMatchPattern.slice( 0, position ); |
| 1252 | const suffix = autoCreateUserMatchPattern.slice( position + '$1'.length ); |
| 1253 | |
| 1254 | let match = true; |
| 1255 | if ( prefix !== '' ) { |
| 1256 | match = ( username.indexOf( prefix ) === 0 ); |
| 1257 | } |
| 1258 | if ( match && suffix !== '' ) { |
| 1259 | match = ( username.slice( -suffix.length ) === suffix ) && |
| 1260 | ( username.length >= prefix.length + suffix.length ); |
| 1261 | } |
| 1262 | if ( match ) { |
| 1263 | return true; |
| 1264 | } |
| 1265 | } |
| 1266 | // No match patterns matched the username, so the given username is not a temporary user. |
| 1267 | return false; |
| 1268 | }, |
| 1269 | |
| 1270 | /** |
| 1271 | * Determine if an input string represents a value of infinity. |
| 1272 | * This is used when testing for infinity in the context of expiries, |
| 1273 | * such as watchlisting, page protection, and block expiries. |
| 1274 | * |
| 1275 | * @param {string|null} str |
| 1276 | * @return {boolean} |
| 1277 | * @stable |
| 1278 | */ |
| 1279 | isInfinity: function ( str ) { |
| 1280 | return infinityValues.indexOf( str ) !== -1; |
| 1281 | } |
| 1282 | }; |
| 1283 | |
| 1284 | /** |
| 1285 | * Initialisation of mw.util.$content |
| 1286 | * |
| 1287 | * @ignore |
| 1288 | */ |
| 1289 | function init() { |
| 1290 | // The preferred standard is class "mw-body". |
| 1291 | // You may also use class "mw-body mw-body-primary" if you use |
| 1292 | // mw-body in multiple locations. Or class "mw-body-primary" if |
| 1293 | // you use mw-body deeper in the DOM. |
| 1294 | const content = document.querySelector( '.mw-body-primary' ) || |
| 1295 | document.querySelector( '.mw-body' ) || |
| 1296 | // If the skin has no such class, fall back to the parser output |
| 1297 | document.querySelector( '#mw-content-text' ) || |
| 1298 | // Should never happen..., except if the skin is still in development. |
| 1299 | document.body; |
| 1300 | |
| 1301 | util.$content = $( content ); |
| 1302 | } |
| 1303 | |
| 1304 | // Backwards-compatible alias for mediawiki.RegExp module. |
| 1305 | // @deprecated since 1.34 |
| 1306 | mw.RegExp = {}; |
| 1307 | mw.log.deprecate( mw.RegExp, 'escape', util.escapeRegExp, 'Use mw.util.escapeRegExp() instead.', 'mw.RegExp.escape' ); |
| 1308 | |
| 1309 | if ( window.QUnit ) { |
| 1310 | // Not allowed outside unit tests |
| 1311 | util.setOptionsForTest = function ( opts ) { |
| 1312 | config = !opts ? require( './config.json' ) : Object.assign( {}, config, opts ); |
| 1313 | }; |
| 1314 | util.init = init; |
| 1315 | } else { |
| 1316 | $( init ); |
| 1317 | } |
| 1318 | |
| 1319 | mw.util = util; |
| 1320 | module.exports = util; |