Merge "Add PreferencesFormPreSave hook"
[mediawiki.git] / resources / mediawiki / mediawiki.util.js
blob40c12cfc7272cb08b825c41a7aacd57bf1220658
1 ( function ( mw, $ ) {
2         'use strict';
4         /**
5          * Utility library
6          * @class mw.util
7          * @singleton
8          */
9         var util = {
11                 /**
12                  * Initialisation
13                  * (don't call before document ready)
14                  */
15                 init: function () {
16                         var profile;
18                         /* Set tooltipAccessKeyPrefix */
19                         profile = $.client.profile();
21                         // Opera on any platform
22                         if ( profile.name === 'opera' ) {
23                                 util.tooltipAccessKeyPrefix = 'shift-esc-';
25                         // Chrome on any platform
26                         } else if ( profile.name === 'chrome' ) {
28                                 util.tooltipAccessKeyPrefix = (
29                                         profile.platform === 'mac'
30                                                 // Chrome on Mac
31                                                 ? 'ctrl-option-'
32                                                 // Chrome on Windows or Linux
33                                                 // (both alt- and alt-shift work, but alt with E, D, F etc does not
34                                                 // work since they are browser shortcuts)
35                                                 : 'alt-shift-'
36                                 );
38                         // Non-Windows Safari with webkit_version > 526
39                         } else if ( profile.platform !== 'win'
40                                 && profile.name === 'safari'
41                                 && profile.layoutVersion > 526 ) {
42                                 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
43                         // Firefox 14+ on Mac
44                         } else if ( profile.platform === 'mac'
45                                 && profile.name === 'firefox'
46                                 && profile.versionNumber >= 14 ) {
47                                 util.tooltipAccessKeyPrefix = 'ctrl-option-';
48                         // Safari/Konqueror on any platform, or any browser on Mac
49                         // (but not Safari on Windows)
50                         } else if ( !( profile.platform === 'win' && profile.name === 'safari' )
51                                                         && ( profile.name === 'safari'
52                                                         || profile.platform === 'mac'
53                                                         || profile.name === 'konqueror' ) ) {
54                                 util.tooltipAccessKeyPrefix = 'ctrl-';
56                         // Firefox/Iceweasel 2.x and later
57                         } else if ( ( profile.name === 'firefox' || profile.name === 'iceweasel' )
58                                 && profile.versionBase > '1' ) {
59                                 util.tooltipAccessKeyPrefix = 'alt-shift-';
60                         }
62                         /* Fill $content var */
63                         util.$content = ( function () {
64                                 var i, l, $content, selectors;
65                                 selectors = [
66                                         // The preferred standard for setting $content (class="mw-body")
67                                         // You may also use (class="mw-body mw-body-primary") if you use
68                                         // mw-body in multiple locations.
69                                         // Or class="mw-body-primary" if you want $content to be deeper
70                                         // in the dom than mw-body
71                                         '.mw-body-primary',
72                                         '.mw-body',
74                                         /* Legacy fallbacks for setting the content */
75                                         // Vector, Monobook, Chick, etc... based skins
76                                         '#bodyContent',
78                                         // Modern based skins
79                                         '#mw_contentholder',
81                                         // Standard, CologneBlue
82                                         '#article',
84                                         // #content is present on almost all if not all skins. Most skins (the above cases)
85                                         // have #content too, but as an outer wrapper instead of the article text container.
86                                         // The skins that don't have an outer wrapper do have #content for everything
87                                         // so it's a good fallback
88                                         '#content',
90                                         // If nothing better is found fall back to our bodytext div that is guaranteed to be here
91                                         '#mw-content-text',
93                                         // Should never happen... well, it could if someone is not finished writing a skin and has
94                                         // not inserted bodytext yet. But in any case <body> should always exist
95                                         'body'
96                                 ];
97                                 for ( i = 0, l = selectors.length; i < l; i++ ) {
98                                         $content = $( selectors[i] ).first();
99                                         if ( $content.length ) {
100                                                 return $content;
101                                         }
102                                 }
104                                 // Make sure we don't unset util.$content if it was preset and we don't find anything
105                                 return util.$content;
106                         } )();
107                 },
109                 /* Main body */
111                 /**
112                  * Encode the string like PHP's rawurlencode
113                  *
114                  * @param {string} str String to be encoded.
115                  */
116                 rawurlencode: function ( str ) {
117                         str = String( str );
118                         return encodeURIComponent( str )
119                                 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
120                                 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
121                 },
123                 /**
124                  * Encode page titles for use in a URL
125                  * We want / and : to be included as literal characters in our title URLs
126                  * as they otherwise fatally break the title
127                  *
128                  * @param {string} str String to be encoded.
129                  */
130                 wikiUrlencode: function ( str ) {
131                         return util.rawurlencode( str )
132                                 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
133                 },
135                 /**
136                  * Get the link to a page name (relative to `wgServer`),
137                  *
138                  * @param {string} str Page name to get the link for.
139                  * @param {Object} [params] A mapping of query parameter names to values,
140                  *     e.g. `{ action: 'edit' }`.
141                  * @return {string} Location for a page with name of `str` or boolean false on error.
142                  */
143                 getUrl: function ( str, params ) {
144                         var url = mw.config.get( 'wgArticlePath' ).replace( '$1',
145                                 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
146                         if ( params && !$.isEmptyObject( params ) ) {
147                                 url += url.indexOf( '?' ) !== -1 ? '&' : '?';
148                                 url += $.param( params );
149                         }
150                         return url;
151                 },
153                 /**
154                  * Get address to a script in the wiki root.
155                  * For index.php use `mw.config.get( 'wgScript' )`.
156                  *
157                  * @since 1.18
158                  * @param str string Name of script (eg. 'api'), defaults to 'index'
159                  * @return string Address to script (eg. '/w/api.php' )
160                  */
161                 wikiScript: function ( str ) {
162                         str = str || 'index';
163                         if ( str === 'index' ) {
164                                 return mw.config.get( 'wgScript' );
165                         } else if ( str === 'load' ) {
166                                 return mw.config.get( 'wgLoadScript' );
167                         } else {
168                                 return mw.config.get( 'wgScriptPath' ) + '/' + str +
169                                         mw.config.get( 'wgScriptExtension' );
170                         }
171                 },
173                 /**
174                  * Append a new style block to the head and return the CSSStyleSheet object.
175                  * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
176                  * This function returns the styleSheet object for convience (due to cross-browsers
177                  * difference as to where it is located).
178                  *
179                  *     var sheet = mw.util.addCSS( '.foobar { display: none; }' );
180                  *     $( foo ).click( function () {
181                  *         // Toggle the sheet on and off
182                  *         sheet.disabled = !sheet.disabled;
183                  *     } );
184                  *
185                  * @param {string} text CSS to be appended
186                  * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
187                  */
188                 addCSS: function ( text ) {
189                         var s = mw.loader.addStyleTag( text );
190                         return s.sheet || s.styleSheet || s;
191                 },
193                 /**
194                  * Hide/show the table of contents element
195                  *
196                  * @param {jQuery} $toggleLink A jQuery object of the toggle link.
197                  * @param {Function} [callback] Function to be called after the toggle is
198                  *  completed (including the animation).
199                  * @return {Mixed} Boolean visibility of the toc (true if it's visible)
200                  * or Null if there was no table of contents.
201                  * @deprecated since 1.23 Use jQuery
202                  */
203                 toggleToc: function ( $toggleLink, callback ) {
204                         var ret, $tocList = $( '#toc ul:first' );
206                         // This function shouldn't be called if there's no TOC,
207                         // but just in case...
208                         if ( !$tocList.length ) {
209                                 return null;
210                         }
211                         ret = $tocList.is( ':hidden' );
212                         $toggleLink.click();
213                         $tocList.promise().done( callback );
214                         return ret;
215                 },
217                 /**
218                  * Grab the URL parameter value for the given parameter.
219                  * Returns null if not found.
220                  *
221                  * @param {string} param The parameter name.
222                  * @param {string} [url=document.location.href] URL to search through, defaulting to the current document's URL.
223                  * @return {Mixed} Parameter value or null.
224                  */
225                 getParamValue: function ( param, url ) {
226                         if ( url === undefined ) {
227                                 url = document.location.href;
228                         }
229                         // Get last match, stop at hash
230                         var     re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
231                                 m = re.exec( url );
232                         if ( m ) {
233                                 // Beware that decodeURIComponent is not required to understand '+'
234                                 // by spec, as encodeURIComponent does not produce it.
235                                 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
236                         }
237                         return null;
238                 },
240                 /**
241                  * @property {string}
242                  * Access key prefix. Will be re-defined based on browser/operating system
243                  * detection in mw.util#init.
244                  */
245                 tooltipAccessKeyPrefix: 'alt-',
247                 /**
248                  * @property {RegExp}
249                  * Regex to match accesskey tooltips.
250                  *
251                  * Should match:
252                  *
253                  * - "ctrl-option-"
254                  * - "alt-shift-"
255                  * - "ctrl-alt-"
256                  * - "ctrl-"
257                  *
258                  * The accesskey is matched in group $6.
259                  */
260                 tooltipAccessKeyRegexp: /\[(ctrl-)?(option-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
262                 /**
263                  * Add the appropriate prefix to the accesskey shown in the tooltip.
264                  * If the nodeList parameter is given, only those nodes are updated;
265                  * otherwise, all the nodes that will probably have accesskeys by
266                  * default are updated.
267                  *
268                  * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
269                  */
270                 updateTooltipAccessKeys: function ( $nodes ) {
271                         if ( !$nodes ) {
272                                 // Rather than going into a loop of all anchor tags, limit to few elements that
273                                 // contain the relevant anchor tags.
274                                 // Input and label are rare enough that no such optimization is needed
275                                 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
276                         } else if ( !( $nodes instanceof $ ) ) {
277                                 $nodes = $( $nodes );
278                         }
280                         $nodes.attr( 'title', function ( i, val ) {
281                                 if ( val && util.tooltipAccessKeyRegexp.test( val ) ) {
282                                         return val.replace( util.tooltipAccessKeyRegexp,
283                                                 '[' + util.tooltipAccessKeyPrefix + '$6]' );
284                                 }
285                                 return val;
286                         } );
287                 },
289                 /*
290                  * @property {jQuery}
291                  * A jQuery object that refers to the content area element.
292                  * Populated by #init.
293                  */
294                 $content: null,
296                 /**
297                  * Add a link to a portlet menu on the page, such as:
298                  *
299                  * p-cactions (Content actions), p-personal (Personal tools),
300                  * p-navigation (Navigation), p-tb (Toolbox)
301                  *
302                  * The first three paramters are required, the others are optional and
303                  * may be null. Though providing an id and tooltip is recommended.
304                  *
305                  * By default the new link will be added to the end of the list. To
306                  * add the link before a given existing item, pass the DOM node
307                  * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
308                  * (e.g. `'#foobar'`) for that item.
309                  *
310                  *     mw.util.addPortletLink(
311                  *         'p-tb', 'http://mediawiki.org/',
312                  *         'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
313                  *     );
314                  *
315                  * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
316                  * @param {string} href Link URL
317                  * @param {string} text Link text
318                  * @param {string} [id] ID of the new item, should be unique and preferably have
319                  *  the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
320                  * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
321                  * @param {string} [accesskey] Access key to activate this link (one character, try
322                  *  to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
323                  *  see if 'x' is already used.
324                  * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
325                  *  the new item should be added before, should be another item in the same
326                  *  list, it will be ignored otherwise
327                  *
328                  * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
329                  * depending on the skin) or null if no element was added to the document.
330                  */
331                 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
332                         var $item, $link, $portlet, $ul;
334                         // Check if there's atleast 3 arguments to prevent a TypeError
335                         if ( arguments.length < 3 ) {
336                                 return null;
337                         }
338                         // Setup the anchor tag
339                         $link = $( '<a>' ).attr( 'href', href ).text( text );
340                         if ( tooltip ) {
341                                 $link.attr( 'title', tooltip );
342                         }
344                         // Select the specified portlet
345                         $portlet = $( '#' + portlet );
346                         if ( $portlet.length === 0 ) {
347                                 return null;
348                         }
349                         // Select the first (most likely only) unordered list inside the portlet
350                         $ul = $portlet.find( 'ul' ).eq( 0 );
352                         // If it didn't have an unordered list yet, create it
353                         if ( $ul.length === 0 ) {
355                                 $ul = $( '<ul>' );
357                                 // If there's no <div> inside, append it to the portlet directly
358                                 if ( $portlet.find( 'div:first' ).length === 0 ) {
359                                         $portlet.append( $ul );
360                                 } else {
361                                         // otherwise if there's a div (such as div.body or div.pBody)
362                                         // append the <ul> to last (most likely only) div
363                                         $portlet.find( 'div' ).eq( -1 ).append( $ul );
364                                 }
365                         }
366                         // Just in case..
367                         if ( $ul.length === 0 ) {
368                                 return null;
369                         }
371                         // Unhide portlet if it was hidden before
372                         $portlet.removeClass( 'emptyPortlet' );
374                         // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
375                         // and back up the selector to the list item
376                         if ( $portlet.hasClass( 'vectorTabs' ) ) {
377                                 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
378                         } else {
379                                 $item = $link.wrap( '<li></li>' ).parent();
380                         }
382                         // Implement the properties passed to the function
383                         if ( id ) {
384                                 $item.attr( 'id', id );
385                         }
387                         if ( tooltip ) {
388                                 // Trim any existing accesskey hint and the trailing space
389                                 tooltip = $.trim( tooltip.replace( util.tooltipAccessKeyRegexp, '' ) );
390                                 if ( accesskey ) {
391                                         tooltip += ' [' + accesskey + ']';
392                                 }
393                                 $link.attr( 'title', tooltip );
394                                 if ( accesskey ) {
395                                         util.updateTooltipAccessKeys( $link );
396                                 }
397                         }
399                         if ( accesskey ) {
400                                 $link.attr( 'accesskey', accesskey );
401                         }
403                         if ( nextnode ) {
404                                 if ( nextnode.nodeType || typeof nextnode === 'string' ) {
405                                         // nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
406                                         // or nextnode is a CSS selector for jQuery
407                                         nextnode = $ul.find( nextnode );
408                                 } else if ( !nextnode.jquery || ( nextnode.length && nextnode[0].parentNode !== $ul[0] ) ) {
409                                         // Fallback
410                                         $ul.append( $item );
411                                         return $item[0];
412                                 }
413                                 if ( nextnode.length === 1 ) {
414                                         // nextnode is a jQuery object that represents exactly one element
415                                         nextnode.before( $item );
416                                         return $item[0];
417                                 }
418                         }
420                         // Fallback (this is the default behavior)
421                         $ul.append( $item );
422                         return $item[0];
424                 },
426                 /**
427                  * Add a little box at the top of the screen to inform the user of
428                  * something, replacing any previous message.
429                  * Calling with no arguments, with an empty string or null will hide the message
430                  *
431                  * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
432                  * to allow CSS/JS to hide different boxes. null = no class used.
433                  * @deprecated since 1.20 Use mw#notify
434                  */
435                 jsMessage: function ( message ) {
436                         if ( !arguments.length || message === '' || message === null ) {
437                                 return true;
438                         }
439                         if ( typeof message !== 'object' ) {
440                                 message = $.parseHTML( message );
441                         }
442                         mw.notify( message, { autoHide: true, tag: 'legacy' } );
443                         return true;
444                 },
446                 /**
447                  * Validate a string as representing a valid e-mail address
448                  * according to HTML5 specification. Please note the specification
449                  * does not validate a domain with one character.
450                  *
451                  * FIXME: should be moved to or replaced by a validation module.
452                  *
453                  * @param {string} mailtxt E-mail address to be validated.
454                  * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
455                  * as determined by validation.
456                  */
457                 validateEmail: function ( mailtxt ) {
458                         var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
460                         if ( mailtxt === '' ) {
461                                 return null;
462                         }
464                         // HTML5 defines a string as valid e-mail address if it matches
465                         // the ABNF:
466                         //      1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
467                         // With:
468                         // - atext   : defined in RFC 5322 section 3.2.3
469                         // - ldh-str : defined in RFC 1034 section 3.5
470                         //
471                         // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
472                         // First, define the RFC 5322 'atext' which is pretty easy:
473                         // atext = ALPHA / DIGIT / ; Printable US-ASCII
474                         //     "!" / "#" /    ; characters not including
475                         //     "$" / "%" /    ; specials. Used for atoms.
476                         //     "&" / "'" /
477                         //     "*" / "+" /
478                         //     "-" / "/" /
479                         //     "=" / "?" /
480                         //     "^" / "_" /
481                         //     "`" / "{" /
482                         //     "|" / "}" /
483                         //     "~"
484                         rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
486                         // Next define the RFC 1034 'ldh-str'
487                         //      <domain> ::= <subdomain> | " "
488                         //      <subdomain> ::= <label> | <subdomain> "." <label>
489                         //      <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
490                         //      <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
491                         //      <let-dig-hyp> ::= <let-dig> | "-"
492                         //      <let-dig> ::= <letter> | <digit>
493                         rfc1034LdhStr = 'a-z0-9\\-';
495                         html5EmailRegexp = new RegExp(
496                                 // start of string
497                                 '^'
498                                 +
499                                 // User part which is liberal :p
500                                 '[' + rfc5322Atext + '\\.]+'
501                                 +
502                                 // 'at'
503                                 '@'
504                                 +
505                                 // Domain first part
506                                 '[' + rfc1034LdhStr + ']+'
507                                 +
508                                 // Optional second part and following are separated by a dot
509                                 '(?:\\.[' + rfc1034LdhStr + ']+)*'
510                                 +
511                                 // End of string
512                                 '$',
513                                 // RegExp is case insensitive
514                                 'i'
515                         );
516                         return ( null !== mailtxt.match( html5EmailRegexp ) );
517                 },
519                 /**
520                  * Note: borrows from IP::isIPv4
521                  *
522                  * @param {string} address
523                  * @param {boolean} allowBlock
524                  * @return {boolean}
525                  */
526                 isIPv4Address: function ( address, allowBlock ) {
527                         if ( typeof address !== 'string' ) {
528                                 return false;
529                         }
531                         var     block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
532                                 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
533                                 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
535                         return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
536                 },
538                 /**
539                  * Note: borrows from IP::isIPv6
540                  *
541                  * @param {string} address
542                  * @param {boolean} allowBlock
543                  * @return {boolean}
544                  */
545                 isIPv6Address: function ( address, allowBlock ) {
546                         if ( typeof address !== 'string' ) {
547                                 return false;
548                         }
550                         var     block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
551                                 RE_IPV6_ADD =
552                         '(?:' + // starts with "::" (including "::")
553                         ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
554                         '|' + // ends with "::" (except "::")
555                         '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
556                         '|' + // contains no "::"
557                         '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
558                         ')';
560                         if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
561                                 return true;
562                         }
564                         RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
565                                 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
567                         return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
568                                 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
569                 }
570         };
572         /**
573          * @method wikiGetlink
574          * @inheritdoc #getUrl
575          * @deprecated since 1.23 Use #getUrl instead.
576          */
577         mw.log.deprecate( util, 'wikiGetlink', util.getUrl, 'Use mw.util.getUrl instead.' );
579         mw.util = util;
581 }( mediaWiki, jQuery ) );