Adding a quotation marks message to core.
[mediawiki.git] / resources / mediawiki / mediawiki.util.js
blob4334a9fbf2f2283df8b4a5f175219ca0408c7c17
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                         } )();
108                         // Table of contents toggle
109                         mw.hook( 'wikipage.content' ).add( function () {
110                                 var $tocTitle, $tocToggleLink, hideTocCookie;
111                                 $tocTitle = $( '#toctitle' );
112                                 $tocToggleLink = $( '#togglelink' );
113                                 // Only add it if there is a TOC and there is no toggle added already
114                                 if ( $( '#toc' ).length && $tocTitle.length && !$tocToggleLink.length ) {
115                                         hideTocCookie = $.cookie( 'mw_hidetoc' );
116                                         $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
117                                                 .text( mw.msg( 'hidetoc' ) )
118                                                 .click( function ( e ) {
119                                                         e.preventDefault();
120                                                         util.toggleToc( $(this) );
121                                                 } );
122                                         $tocTitle.append(
123                                                 $tocToggleLink
124                                                         .wrap( '<span class="toctoggle"></span>' )
125                                                         .parent()
126                                                                 .prepend( '&nbsp;[' )
127                                                                 .append( ']&nbsp;' )
128                                         );
130                                         if ( hideTocCookie === '1' ) {
131                                                 util.toggleToc( $tocToggleLink );
132                                         }
133                                 }
134                         } );
135                 },
137                 /* Main body */
139                 /**
140                  * Encode the string like PHP's rawurlencode
141                  *
142                  * @param {string} str String to be encoded.
143                  */
144                 rawurlencode: function ( str ) {
145                         str = String( str );
146                         return encodeURIComponent( str )
147                                 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
148                                 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
149                 },
151                 /**
152                  * Encode page titles for use in a URL
153                  * We want / and : to be included as literal characters in our title URLs
154                  * as they otherwise fatally break the title
155                  *
156                  * @param {string} str String to be encoded.
157                  */
158                 wikiUrlencode: function ( str ) {
159                         return util.rawurlencode( str )
160                                 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
161                 },
163                 /**
164                  * Get the link to a page name (relative to `wgServer`),
165                  *
166                  * @param {string} str Page name to get the link for.
167                  * @param {Object} params A mapping of query parameter names to values,
168                  *     e.g. { action: 'edit' }. Optional.
169                  * @return {string} Location for a page with name of `str` or boolean false on error.
170                  */
171                 wikiGetlink: function ( str, params ) {
172                         var url = mw.config.get( 'wgArticlePath' ).replace( '$1',
173                                 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
174                         if ( params && !$.isEmptyObject( params ) ) {
175                                 url += url.indexOf( '?' ) !== -1 ? '&' : '?';
176                                 url += $.param( params );
177                         }
178                         return url;
179                 },
181                 /**
182                  * Get address to a script in the wiki root.
183                  * For index.php use `mw.config.get( 'wgScript' )`.
184                  *
185                  * @since 1.18
186                  * @param str string Name of script (eg. 'api'), defaults to 'index'
187                  * @return string Address to script (eg. '/w/api.php' )
188                  */
189                 wikiScript: function ( str ) {
190                         str = str || 'index';
191                         if ( str === 'index' ) {
192                                 return mw.config.get( 'wgScript' );
193                         } else if ( str === 'load' ) {
194                                 return mw.config.get( 'wgLoadScript' );
195                         } else {
196                                 return mw.config.get( 'wgScriptPath' ) + '/' + str +
197                                         mw.config.get( 'wgScriptExtension' );
198                         }
199                 },
201                 /**
202                  * Append a new style block to the head and return the CSSStyleSheet object.
203                  * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
204                  * This function returns the styleSheet object for convience (due to cross-browsers
205                  * difference as to where it is located).
206                  *
207                  *     var sheet = mw.util.addCSS('.foobar { display: none; }');
208                  *     $(foo).click(function () {
209                  *         // Toggle the sheet on and off
210                  *         sheet.disabled = !sheet.disabled;
211                  *     });
212                  *
213                  * @param {string} text CSS to be appended
214                  * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
215                  */
216                 addCSS: function ( text ) {
217                         var s = mw.loader.addStyleTag( text );
218                         return s.sheet || s;
219                 },
221                 /**
222                  * Hide/show the table of contents element
223                  *
224                  * @param {jQuery} $toggleLink A jQuery object of the toggle link.
225                  * @param {Function} [callback] Function to be called after the toggle is
226                  *  completed (including the animation).
227                  * @return {Mixed} Boolean visibility of the toc (true if it's visible)
228                  * or Null if there was no table of contents.
229                  */
230                 toggleToc: function ( $toggleLink, callback ) {
231                         var $tocList = $( '#toc ul:first' );
233                         // This function shouldn't be called if there's no TOC,
234                         // but just in case...
235                         if ( $tocList.length ) {
236                                 if ( $tocList.is( ':hidden' ) ) {
237                                         $tocList.slideDown( 'fast', callback );
238                                         $toggleLink.text( mw.msg( 'hidetoc' ) );
239                                         $( '#toc' ).removeClass( 'tochidden' );
240                                         $.cookie( 'mw_hidetoc', null, {
241                                                 expires: 30,
242                                                 path: '/'
243                                         } );
244                                         return true;
245                                 } else {
246                                         $tocList.slideUp( 'fast', callback );
247                                         $toggleLink.text( mw.msg( 'showtoc' ) );
248                                         $( '#toc' ).addClass( 'tochidden' );
249                                         $.cookie( 'mw_hidetoc', '1', {
250                                                 expires: 30,
251                                                 path: '/'
252                                         } );
253                                         return false;
254                                 }
255                         } else {
256                                 return null;
257                         }
258                 },
260                 /**
261                  * Grab the URL parameter value for the given parameter.
262                  * Returns null if not found.
263                  *
264                  * @param {string} param The parameter name.
265                  * @param {string} [url=document.location.href] URL to search through, defaulting to the current document's URL.
266                  * @return {Mixed} Parameter value or null.
267                  */
268                 getParamValue: function ( param, url ) {
269                         if ( url === undefined ) {
270                                 url = document.location.href;
271                         }
272                         // Get last match, stop at hash
273                         var     re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
274                                 m = re.exec( url );
275                         if ( m ) {
276                                 // Beware that decodeURIComponent is not required to understand '+'
277                                 // by spec, as encodeURIComponent does not produce it.
278                                 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
279                         }
280                         return null;
281                 },
283                 /**
284                  * @property {string}
285                  * Access key prefix. Will be re-defined based on browser/operating system
286                  * detection in mw.util#init.
287                  */
288                 tooltipAccessKeyPrefix: 'alt-',
290                 /**
291                  * @property {RegExp}
292                  * Regex to match accesskey tooltips.
293                  *
294                  * Should match:
295                  *
296                  * - "ctrl-option-"
297                  * - "alt-shift-"
298                  * - "ctrl-alt-"
299                  * - "ctrl-"
300                  *
301                  * The accesskey is matched in group $6.
302                  */
303                 tooltipAccessKeyRegexp: /\[(ctrl-)?(option-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
305                 /**
306                  * Add the appropriate prefix to the accesskey shown in the tooltip.
307                  * If the nodeList parameter is given, only those nodes are updated;
308                  * otherwise, all the nodes that will probably have accesskeys by
309                  * default are updated.
310                  *
311                  * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
312                  */
313                 updateTooltipAccessKeys: function ( $nodes ) {
314                         if ( !$nodes ) {
315                                 // Rather than going into a loop of all anchor tags, limit to few elements that
316                                 // contain the relevant anchor tags.
317                                 // Input and label are rare enough that no such optimization is needed
318                                 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
319                         } else if ( !( $nodes instanceof $ ) ) {
320                                 $nodes = $( $nodes );
321                         }
323                         $nodes.attr( 'title', function ( i, val ) {
324                                 if ( val && util.tooltipAccessKeyRegexp.test( val ) ) {
325                                         return val.replace( util.tooltipAccessKeyRegexp,
326                                                 '[' + util.tooltipAccessKeyPrefix + '$6]' );
327                                 }
328                                 return val;
329                         } );
330                 },
332                 /*
333                  * @property {jQuery}
334                  * A jQuery object that refers to the content area element.
335                  * Populated by #init.
336                  */
337                 $content: null,
339                 /**
340                  * Add a link to a portlet menu on the page, such as:
341                  *
342                  * p-cactions (Content actions), p-personal (Personal tools),
343                  * p-navigation (Navigation), p-tb (Toolbox)
344                  *
345                  * The first three paramters are required, the others are optional and
346                  * may be null. Though providing an id and tooltip is recommended.
347                  *
348                  * By default the new link will be added to the end of the list. To
349                  * add the link before a given existing item, pass the DOM node
350                  * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
351                  * (e.g. `'#foobar'`) for that item.
352                  *
353                  *     mw.util.addPortletLink(
354                  *         'p-tb', 'http://mediawiki.org/',
355                  *         'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
356                  *     );
357                  *
358                  * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
359                  * @param {string} href Link URL
360                  * @param {string} text Link text
361                  * @param {string} [id] ID of the new item, should be unique and preferably have
362                  *  the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
363                  * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
364                  * @param {string} [accesskey] Access key to activate this link (one character, try
365                  *  to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
366                  *  see if 'x' is already used.
367                  * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
368                  *  the new item should be added before, should be another item in the same
369                  *  list, it will be ignored otherwise
370                  *
371                  * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
372                  * depending on the skin) or null if no element was added to the document.
373                  */
374                 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
375                         var $item, $link, $portlet, $ul;
377                         // Check if there's atleast 3 arguments to prevent a TypeError
378                         if ( arguments.length < 3 ) {
379                                 return null;
380                         }
381                         // Setup the anchor tag
382                         $link = $( '<a>' ).attr( 'href', href ).text( text );
383                         if ( tooltip ) {
384                                 $link.attr( 'title', tooltip );
385                         }
387                         // Select the specified portlet
388                         $portlet = $( '#' + portlet );
389                         if ( $portlet.length === 0 ) {
390                                 return null;
391                         }
392                         // Select the first (most likely only) unordered list inside the portlet
393                         $ul = $portlet.find( 'ul' ).eq( 0 );
395                         // If it didn't have an unordered list yet, create it
396                         if ( $ul.length === 0 ) {
398                                 $ul = $( '<ul>' );
400                                 // If there's no <div> inside, append it to the portlet directly
401                                 if ( $portlet.find( 'div:first' ).length === 0 ) {
402                                         $portlet.append( $ul );
403                                 } else {
404                                         // otherwise if there's a div (such as div.body or div.pBody)
405                                         // append the <ul> to last (most likely only) div
406                                         $portlet.find( 'div' ).eq( -1 ).append( $ul );
407                                 }
408                         }
409                         // Just in case..
410                         if ( $ul.length === 0 ) {
411                                 return null;
412                         }
414                         // Unhide portlet if it was hidden before
415                         $portlet.removeClass( 'emptyPortlet' );
417                         // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
418                         // and back up the selector to the list item
419                         if ( $portlet.hasClass( 'vectorTabs' ) ) {
420                                 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
421                         } else {
422                                 $item = $link.wrap( '<li></li>' ).parent();
423                         }
425                         // Implement the properties passed to the function
426                         if ( id ) {
427                                 $item.attr( 'id', id );
428                         }
430                         if ( tooltip ) {
431                                 // Trim any existing accesskey hint and the trailing space
432                                 tooltip = $.trim( tooltip.replace( util.tooltipAccessKeyRegexp, '' ) );
433                                 if ( accesskey ) {
434                                         tooltip += ' [' + accesskey + ']';
435                                 }
436                                 $link.attr( 'title', tooltip );
437                                 if ( accesskey ) {
438                                         util.updateTooltipAccessKeys( $link );
439                                 }
440                         }
442                         if ( accesskey ) {
443                                 $link.attr( 'accesskey', accesskey );
444                         }
446                         if ( nextnode ) {
447                                 if ( nextnode.nodeType || typeof nextnode === 'string' ) {
448                                         // nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
449                                         // or nextnode is a CSS selector for jQuery
450                                         nextnode = $ul.find( nextnode );
451                                 } else if ( !nextnode.jquery || nextnode[0].parentNode !== $ul[0] ) {
452                                         // Fallback
453                                         $ul.append( $item );
454                                         return $item[0];
455                                 }
456                                 if ( nextnode.length === 1 ) {
457                                         // nextnode is a jQuery object that represents exactly one element
458                                         nextnode.before( $item );
459                                         return $item[0];
460                                 }
461                         }
463                         // Fallback (this is the default behavior)
464                         $ul.append( $item );
465                         return $item[0];
467                 },
469                 /**
470                  * Add a little box at the top of the screen to inform the user of
471                  * something, replacing any previous message.
472                  * Calling with no arguments, with an empty string or null will hide the message
473                  *
474                  * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
475                  * to allow CSS/JS to hide different boxes. null = no class used.
476                  * @deprecated since 1.20 Use mw#notify
477                  */
478                 jsMessage: function ( message ) {
479                         if ( !arguments.length || message === '' || message === null ) {
480                                 return true;
481                         }
482                         if ( typeof message !== 'object' ) {
483                                 message = $.parseHTML( message );
484                         }
485                         mw.notify( message, { autoHide: true, tag: 'legacy' } );
486                         return true;
487                 },
489                 /**
490                  * Validate a string as representing a valid e-mail address
491                  * according to HTML5 specification. Please note the specification
492                  * does not validate a domain with one character.
493                  *
494                  * FIXME: should be moved to or replaced by a validation module.
495                  *
496                  * @param {string} mailtxt E-mail address to be validated.
497                  * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
498                  * as determined by validation.
499                  */
500                 validateEmail: function ( mailtxt ) {
501                         var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
503                         if ( mailtxt === '' ) {
504                                 return null;
505                         }
507                         // HTML5 defines a string as valid e-mail address if it matches
508                         // the ABNF:
509                         //      1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
510                         // With:
511                         // - atext      : defined in RFC 5322 section 3.2.3
512                         // - ldh-str : defined in RFC 1034 section 3.5
513                         //
514                         // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
515                         // First, define the RFC 5322 'atext' which is pretty easy:
516                         // atext = ALPHA / DIGIT / ; Printable US-ASCII
517                         //     "!" / "#" /    ; characters not including
518                         //     "$" / "%" /    ; specials. Used for atoms.
519                         //     "&" / "'" /
520                         //     "*" / "+" /
521                         //     "-" / "/" /
522                         //     "=" / "?" /
523                         //     "^" / "_" /
524                         //     "`" / "{" /
525                         //     "|" / "}" /
526                         //     "~"
527                         rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
529                         // Next define the RFC 1034 'ldh-str'
530                         //      <domain> ::= <subdomain> | " "
531                         //      <subdomain> ::= <label> | <subdomain> "." <label>
532                         //      <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
533                         //      <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
534                         //      <let-dig-hyp> ::= <let-dig> | "-"
535                         //      <let-dig> ::= <letter> | <digit>
536                         rfc1034LdhStr = 'a-z0-9\\-';
538                         html5EmailRegexp = new RegExp(
539                                 // start of string
540                                 '^'
541                                 +
542                                 // User part which is liberal :p
543                                 '[' + rfc5322Atext + '\\.]+'
544                                 +
545                                 // 'at'
546                                 '@'
547                                 +
548                                 // Domain first part
549                                 '[' + rfc1034LdhStr + ']+'
550                                 +
551                                 // Optional second part and following are separated by a dot
552                                 '(?:\\.[' + rfc1034LdhStr + ']+)*'
553                                 +
554                                 // End of string
555                                 '$',
556                                 // RegExp is case insensitive
557                                 'i'
558                         );
559                         return (null !== mailtxt.match( html5EmailRegexp ) );
560                 },
562                 /**
563                  * Note: borrows from IP::isIPv4
564                  *
565                  * @param {string} address
566                  * @param {boolean} allowBlock
567                  * @return {boolean}
568                  */
569                 isIPv4Address: function ( address, allowBlock ) {
570                         if ( typeof address !== 'string' ) {
571                                 return false;
572                         }
574                         var     block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
575                                 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
576                                 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
578                         return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
579                 },
581                 /**
582                  * Note: borrows from IP::isIPv6
583                  *
584                  * @param {string} address
585                  * @param {boolean} allowBlock
586                  * @return {boolean}
587                  */
588                 isIPv6Address: function ( address, allowBlock ) {
589                         if ( typeof address !== 'string' ) {
590                                 return false;
591                         }
593                         var     block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
594                                 RE_IPV6_ADD =
595                         '(?:' + // starts with "::" (including "::")
596                         ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
597                         '|' + // ends with "::" (except "::")
598                         '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
599                         '|' + // contains no "::"
600                         '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
601                         ')';
603                         if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
604                                 return true;
605                         }
607                         RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
608                                 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
610                         return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
611                                 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
612                 }
613         };
615         mw.util = util;
617 }( mediaWiki, jQuery ) );