[FileRepo] Fixed file move data-loss race condition.
[mediawiki.git] / resources / mediawiki / mediawiki.util.js
blob4c20fadd41f59c25f94fcb93ff75835518f25eee
1 /**
2  * Implements mediaWiki.util library
3  */
4 ( function ( $, mw ) {
5         "use strict";
7         // Local cache and alias
8         var util = {
10                 /**
11                  * Initialisation
12                  * (don't call before document ready)
13                  */
14                 init: function () {
15                         var profile, $tocTitle, $tocToggleLink, hideTocCookie;
17                         /* Set up $.messageBox */
18                         $.messageBoxNew( {
19                                 id: 'mw-js-message',
20                                 parent: '#content'
21                         } );
23                         /* Set tooltipAccessKeyPrefix */
24                         profile = $.client.profile();
26                         // Opera on any platform
27                         if ( profile.name === 'opera' ) {
28                                 util.tooltipAccessKeyPrefix = 'shift-esc-';
30                         // Chrome on any platform
31                         } else if ( profile.name === 'chrome' ) {
33                                 util.tooltipAccessKeyPrefix = (
34                                         profile.platform === 'mac'
35                                                 // Chrome on Mac
36                                                 ? 'ctrl-option-'
37                                                 : profile.platform === 'win'
38                                                         // Chrome on Windows
39                                                         // (both alt- and alt-shift work, but alt-f triggers Chrome wrench menu
40                                                         // which alt-shift-f does not)
41                                                         ? 'alt-shift-'
42                                                         // Chrome on other (Ubuntu?)
43                                                         : 'alt-'
44                                 );
46                         // Non-Windows Safari with webkit_version > 526
47                         } else if ( profile.platform !== 'win'
48                                 && profile.name === 'safari'
49                                 && profile.layoutVersion > 526 ) {
50                                 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
52                         // Safari/Konqueror on any platform, or any browser on Mac
53                         // (but not Safari on Windows)
54                         } else if ( !( profile.platform === 'win' && profile.name === 'safari' )
55                                                         && ( profile.name === 'safari'
56                                                         || profile.platform === 'mac'
57                                                         || profile.name === 'konqueror' ) ) {
58                                 util.tooltipAccessKeyPrefix = 'ctrl-';
60                         // Firefox 2.x and later
61                         } else if ( profile.name === 'firefox' && profile.versionBase > '1' ) {
62                                 util.tooltipAccessKeyPrefix = 'alt-shift-';
63                         }
65                         /* Fill $content var */
66                         if ( $( '#bodyContent' ).length ) {
67                                 // Vector, Monobook, Chick etc.
68                                 util.$content = $( '#bodyContent' );
70                         } else if ( $( '#mw_contentholder' ).length ) {
71                                 // Modern
72                                 util.$content = $( '#mw_contentholder' );
74                         } else if ( $( '#article' ).length ) {
75                                 // Standard, CologneBlue
76                                 util.$content = $( '#article' );
78                         } else {
79                                 // #content is present on almost all if not all skins. Most skins (the above cases)
80                                 // have #content too, but as an outer wrapper instead of the article text container.
81                                 // The skins that don't have an outer wrapper do have #content for everything
82                                 // so it's a good fallback
83                                 util.$content = $( '#content' );
84                         }
86                         // Table of contents toggle
87                         $tocTitle = $( '#toctitle' );
88                         $tocToggleLink = $( '#togglelink' );
89                         // Only add it if there is a TOC and there is no toggle added already
90                         if ( $( '#toc' ).length && $tocTitle.length && !$tocToggleLink.length ) {
91                                 hideTocCookie = $.cookie( 'mw_hidetoc' );
92                                         $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
93                                                 .text( mw.msg( 'hidetoc' ) )
94                                                 .click( function ( e ) {
95                                                         e.preventDefault();
96                                                         util.toggleToc( $(this) );
97                                                 } );
98                                 $tocTitle.append(
99                                         $tocToggleLink
100                                                 .wrap( '<span class="toctoggle"></span>' )
101                                                 .parent()
102                                                         .prepend( '&nbsp;[' )
103                                                         .append( ']&nbsp;' )
104                                 );
106                                 if ( hideTocCookie === '1' ) {
107                                         util.toggleToc( $tocToggleLink );
108                                 }
109                         }
110                 },
112                 /* Main body */
114                 /**
115                  * Encode the string like PHP's rawurlencode
116                  *
117                  * @param str string String to be encoded
118                  */
119                 rawurlencode: function ( str ) {
120                         str = String( str );
121                         return encodeURIComponent( str )
122                                 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
123                                 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
124                 },
126                 /**
127                  * Encode page titles for use in a URL
128                  * We want / and : to be included as literal characters in our title URLs
129                  * as they otherwise fatally break the title
130                  *
131                  * @param str string String to be encoded
132                  */
133                 wikiUrlencode: function ( str ) {
134                         return util.rawurlencode( str )
135                                 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
136                 },
138                 /**
139                  * Get the link to a page name (relative to wgServer)
140                  *
141                  * @param str String: Page name to get the link for.
142                  * @return String: Location for a page with name of 'str' or boolean false on error.
143                  */
144                 wikiGetlink: function ( str ) {
145                         return mw.config.get( 'wgArticlePath' ).replace( '$1',
146                                 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
147                 },
149                 /**
150                  * Get address to a script in the wiki root.
151                  * For index.php use mw.config.get( 'wgScript' )
152                  *
153                  * @since 1.18
154                  * @param str string Name of script (eg. 'api'), defaults to 'index'
155                  * @return string Address to script (eg. '/w/api.php' )
156                  */
157                 wikiScript: function ( str ) {
158                         return mw.config.get( 'wgScriptPath' ) + '/' + ( str || 'index' ) +
159                                 mw.config.get( 'wgScriptExtension' );
160                 },
162                 /**
163                  * Append a new style block to the head and return the CSSStyleSheet object.
164                  * Use .ownerNode to access the <style> element, or use mw.loader.addStyleTag.
165                  * This function returns the styleSheet object for convience (due to cross-browsers
166                  * difference as to where it is located).
167                  * @example
168                  * <code>
169                  * var sheet = mw.util.addCSS('.foobar { display: none; }');
170                  * $(foo).click(function () {
171                  *     // Toggle the sheet on and off
172                  *     sheet.disabled = !sheet.disabled;
173                  * });
174                  * </code>
175                  *
176                  * @param text string CSS to be appended
177                  * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
178                  */
179                 addCSS: function ( text ) {
180                         var s = mw.loader.addStyleTag( text );
181                         return s.sheet || s;
182                 },
184                 /**
185                  * Hide/show the table of contents element
186                  *
187                  * @param $toggleLink jQuery A jQuery object of the toggle link.
188                  * @param callback function Function to be called after the toggle is
189                  * completed (including the animation) (optional)
190                  * @return mixed Boolean visibility of the toc (true if it's visible)
191                  * or Null if there was no table of contents.
192                  */
193                 toggleToc: function ( $toggleLink, callback ) {
194                         var $tocList = $( '#toc ul:first' );
196                         // This function shouldn't be called if there's no TOC,
197                         // but just in case...
198                         if ( $tocList.length ) {
199                                 if ( $tocList.is( ':hidden' ) ) {
200                                         $tocList.slideDown( 'fast', callback );
201                                         $toggleLink.text( mw.msg( 'hidetoc' ) );
202                                         $( '#toc' ).removeClass( 'tochidden' );
203                                         $.cookie( 'mw_hidetoc', null, {
204                                                 expires: 30,
205                                                 path: '/'
206                                         } );
207                                         return true;
208                                 } else {
209                                         $tocList.slideUp( 'fast', callback );
210                                         $toggleLink.text( mw.msg( 'showtoc' ) );
211                                         $( '#toc' ).addClass( 'tochidden' );
212                                         $.cookie( 'mw_hidetoc', '1', {
213                                                 expires: 30,
214                                                 path: '/'
215                                         } );
216                                         return false;
217                                 }
218                         } else {
219                                 return null;
220                         }
221                 },
223                 /**
224                  * Grab the URL parameter value for the given parameter.
225                  * Returns null if not found.
226                  *
227                  * @param param string The parameter name.
228                  * @param url string URL to search through (optional)
229                  * @return mixed Parameter value or null.
230                  */
231                 getParamValue: function ( param, url ) {
232                         url = url || document.location.href;
233                         // Get last match, stop at hash
234                         var     re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
235                                 m = re.exec( url );
236                         if ( m && m.length > 1 ) {
237                                 // Beware that decodeURIComponent is not required to understand '+'
238                                 // by spec, as encodeURIComponent does not produce it.
239                                 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
240                         }
241                         return null;
242                 },
244                 /**
245                  * @var string
246                  * Access key prefix. Will be re-defined based on browser/operating system
247                  * detection in mw.util.init().
248                  */
249                 tooltipAccessKeyPrefix: 'alt-',
251                 /**
252                  * @var RegExp
253                  * Regex to match accesskey tooltips.
254                  */
255                 tooltipAccessKeyRegexp: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
257                 /**
258                  * Add the appropriate prefix to the accesskey shown in the tooltip.
259                  * If the nodeList parameter is given, only those nodes are updated;
260                  * otherwise, all the nodes that will probably have accesskeys by
261                  * default are updated.
262                  *
263                  * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
264                  * of elements to update.
265                  */
266                 updateTooltipAccessKeys: function ( $nodes ) {
267                         if ( !$nodes ) {
268                                 // Rather than going into a loop of all anchor tags, limit to few elements that
269                                 // contain the relevant anchor tags.
270                                 // Input and label are rare enough that no such optimization is needed
271                                 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
272                         } else if ( !( $nodes instanceof $ ) ) {
273                                 $nodes = $( $nodes );
274                         }
276                         $nodes.attr( 'title', function ( i, val ) {
277                                 if ( val && util.tooltipAccessKeyRegexp.exec( val ) ) {
278                                         return val.replace( util.tooltipAccessKeyRegexp,
279                                                 '[' + util.tooltipAccessKeyPrefix + '$5]' );
280                                 }
281                                 return val;
282                         } );
283                 },
285                 /*
286                  * @var jQuery
287                  * A jQuery object that refers to the page-content element
288                  * Populated by init().
289                  */
290                 $content: null,
292                 /**
293                  * Add a link to a portlet menu on the page, such as:
294                  *
295                  * p-cactions (Content actions), p-personal (Personal tools),
296                  * p-navigation (Navigation), p-tb (Toolbox)
297                  *
298                  * The first three paramters are required, the others are optional and
299                  * may be null. Though providing an id and tooltip is recommended.
300                  *
301                  * By default the new link will be added to the end of the list. To
302                  * add the link before a given existing item, pass the DOM node
303                  * (document.getElementById( 'foobar' )) or the jQuery-selector
304                  * ( '#foobar' ) of that item.
305                  *
306                  * @example mw.util.addPortletLink(
307                  *       'p-tb', 'http://mediawiki.org/',
308                  *       'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
309                  * )
310                  *
311                  * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
312                  * @param href string Link URL
313                  * @param text string Link text
314                  * @param id string ID of the new item, should be unique and preferably have
315                  * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
316                  * @param tooltip string Text to show when hovering over the link, without accesskey suffix
317                  * @param accesskey string Access key to activate this link (one character, try
318                  * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
319                  * see if 'x' is already used.
320                  * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
321                  * item should be added before, should be another item in the same
322                  * list, it will be ignored otherwise
323                  *
324                  * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
325                  * depending on the skin) or null if no element was added to the document.
326                  */
327                 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
328                         var $item, $link, $portlet, $ul;
330                         // Check if there's atleast 3 arguments to prevent a TypeError
331                         if ( arguments.length < 3 ) {
332                                 return null;
333                         }
334                         // Setup the anchor tag
335                         $link = $( '<a>' ).attr( 'href', href ).text( text );
336                         if ( tooltip ) {
337                                 $link.attr( 'title', tooltip );
338                         }
340                         // Some skins don't have any portlets
341                         // just add it to the bottom of their 'sidebar' element as a fallback
342                         switch ( mw.config.get( 'skin' ) ) {
343                         case 'standard':
344                         case 'cologneblue':
345                                 $( '#quickbar' ).append( $link.after( '<br/>' ) );
346                                 return $link[0];
347                         case 'nostalgia':
348                                 $( '#searchform' ).before( $link ).before( ' &#124; ' );
349                                 return $link[0];
350                         default: // Skins like chick, modern, monobook, myskin, simple, vector...
352                                 // Select the specified portlet
353                                 $portlet = $( '#' + portlet );
354                                 if ( $portlet.length === 0 ) {
355                                         return null;
356                                 }
357                                 // Select the first (most likely only) unordered list inside the portlet
358                                 $ul = $portlet.find( 'ul' );
360                                 // If it didn't have an unordered list yet, create it
361                                 if ( $ul.length === 0 ) {
362                                         // If there's no <div> inside, append it to the portlet directly
363                                         if ( $portlet.find( 'div:first' ).length === 0 ) {
364                                                 $portlet.append( '<ul></ul>' );
365                                         } else {
366                                                 // otherwise if there's a div (such as div.body or div.pBody)
367                                                 // append the <ul> to last (most likely only) div
368                                                 $portlet.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
369                                         }
370                                         // Select the created element
371                                         $ul = $portlet.find( 'ul' ).eq( 0 );
372                                 }
373                                 // Just in case..
374                                 if ( $ul.length === 0 ) {
375                                         return null;
376                                 }
378                                 // Unhide portlet if it was hidden before
379                                 $portlet.removeClass( 'emptyPortlet' );
381                                 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
382                                 // and back up the selector to the list item
383                                 if ( $portlet.hasClass( 'vectorTabs' ) ) {
384                                         $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
385                                 } else {
386                                         $item = $link.wrap( '<li></li>' ).parent();
387                                 }
389                                 // Implement the properties passed to the function
390                                 if ( id ) {
391                                         $item.attr( 'id', id );
392                                 }
393                                 if ( accesskey ) {
394                                         $link.attr( 'accesskey', accesskey );
395                                         tooltip += ' [' + accesskey + ']';
396                                         $link.attr( 'title', tooltip );
397                                 }
398                                 if ( accesskey && tooltip ) {
399                                         util.updateTooltipAccessKeys( $link );
400                                 }
402                                 // Where to put our node ?
403                                 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
404                                 if ( nextnode && nextnode.parentNode === $ul[0] ) {
405                                         $(nextnode).before( $item );
407                                 // - nextnode is a CSS selector for jQuery
408                                 } else if ( typeof nextnode === 'string' && $ul.find( nextnode ).length !== 0 ) {
409                                         $ul.find( nextnode ).eq( 0 ).before( $item );
411                                 // If the jQuery selector isn't found within the <ul>,
412                                 // or if nextnode was invalid or not passed at all,
413                                 // then just append it at the end of the <ul> (this is the default behaviour)
414                                 } else {
415                                         $ul.append( $item );
416                                 }
419                                 return $item[0];
420                         }
421                 },
423                 /**
424                  * Add a little box at the top of the screen to inform the user of
425                  * something, replacing any previous message.
426                  * Calling with no arguments, with an empty string or null will hide the message
427                  *
428                  * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
429                  * @param className {String} Used in adding a class; should be different for each call
430                  * to allow CSS/JS to hide different boxes. null = no class used.
431                  * @return {Boolean} True on success, false on failure.
432                  */
433                 jsMessage: function ( message, className ) {
434                         if ( !arguments.length || message === '' || message === null ) {
435                                 $( '#mw-js-message' ).empty().hide();
436                                 return true; // Emptying and hiding message is intended behaviour, return true
438                         } else {
439                                 // We special-case skin structures provided by the software. Skins that
440                                 // choose to abandon or significantly modify our formatting can just define
441                                 // an mw-js-message div to start with.
442                                 var $messageDiv = $( '#mw-js-message' );
443                                 if ( !$messageDiv.length ) {
444                                         $messageDiv = $( '<div id="mw-js-message"></div>' );
445                                         if ( util.$content.parent().length ) {
446                                                 util.$content.parent().prepend( $messageDiv );
447                                         } else {
448                                                 return false;
449                                         }
450                                 }
452                                 if ( className ) {
453                                         $messageDiv.prop( 'class', 'mw-js-message-' + className );
454                                 }
456                                 if ( typeof message === 'object' ) {
457                                         $messageDiv.empty();
458                                         $messageDiv.append( message );
459                                 } else {
460                                         $messageDiv.html( message );
461                                 }
463                                 $messageDiv.slideDown();
464                                 return true;
465                         }
466                 },
468                 /**
469                  * Validate a string as representing a valid e-mail address
470                  * according to HTML5 specification. Please note the specification
471                  * does not validate a domain with one character.
472                  *
473                  * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
474                  *
475                  * @param mailtxt string E-mail address to be validated.
476                  * @return mixed Null if mailtxt was an empty string, otherwise true/false
477                  * is determined by validation.
478                  */
479                 validateEmail: function ( mailtxt ) {
480                         var rfc5322_atext, rfc1034_ldh_str, HTML5_email_regexp;
482                         if ( mailtxt === '' ) {
483                                 return null;
484                         }
486                         /**
487                          * HTML5 defines a string as valid e-mail address if it matches
488                          * the ABNF:
489                          *      1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
490                          * With:
491                          * - atext      : defined in RFC 5322 section 3.2.3
492                          * - ldh-str : defined in RFC 1034 section 3.5
493                          *
494                          * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
495                          */
497                         /**
498                          * First, define the RFC 5322 'atext' which is pretty easy:
499                          * atext = ALPHA / DIGIT / ; Printable US-ASCII
500                                                  "!" / "#" /     ; characters not including
501                                                  "$" / "%" /     ; specials. Used for atoms.
502                                                  "&" / "'" /
503                                                  "*" / "+" /
504                                                  "-" / "/" /
505                                                  "=" / "?" /
506                                                  "^" / "_" /
507                                                  "`" / "{" /
508                                                  "|" / "}" /
509                                                  "~"
510                         */
511                         rfc5322_atext = "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
513                         /**
514                          * Next define the RFC 1034 'ldh-str'
515                          *      <domain> ::= <subdomain> | " "
516                          *      <subdomain> ::= <label> | <subdomain> "." <label>
517                          *      <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
518                          *      <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
519                          *      <let-dig-hyp> ::= <let-dig> | "-"
520                          *      <let-dig> ::= <letter> | <digit>
521                          */
522                         rfc1034_ldh_str = "a-z0-9\\-";
524                         HTML5_email_regexp = new RegExp(
525                                 // start of string
526                                 '^'
527                                 +
528                                 // User part which is liberal :p
529                                 '[' + rfc5322_atext + '\\.]+'
530                                 +
531                                 // 'at'
532                                 '@'
533                                 +
534                                 // Domain first part
535                                 '[' + rfc1034_ldh_str + ']+'
536                                 +
537                                 // Optional second part and following are separated by a dot
538                                 '(?:\\.[' + rfc1034_ldh_str + ']+)*'
539                                 +
540                                 // End of string
541                                 '$',
542                                 // RegExp is case insensitive
543                                 'i'
544                         );
545                         return (null !== mailtxt.match( HTML5_email_regexp ) );
546                 },
548                 /**
549                  * Note: borrows from IP::isIPv4
550                  *
551                  * @param address string
552                  * @param allowBlock boolean
553                  * @return boolean
554                  */
555                 isIPv4Address: function ( address, allowBlock ) {
556                         if ( typeof address !== 'string' ) {
557                                 return false;
558                         }
560                         var     block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
561                                 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
562                                 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
564                         return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
565                 },
567                 /**
568                  * Note: borrows from IP::isIPv6
569                  *
570                  * @param address string
571                  * @param allowBlock boolean
572                  * @return boolean
573                  */
574                 isIPv6Address: function ( address, allowBlock ) {
575                         if ( typeof address !== 'string' ) {
576                                 return false;
577                         }
579                         var     block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
580                                 RE_IPV6_ADD =
581                         '(?:' + // starts with "::" (including "::")
582                         ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
583                         '|' + // ends with "::" (except "::")
584                         '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
585                         '|' + // contains no "::"
586                         '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
587                         ')';
589                         if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
590                                 return true;
591                         }
593                         RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
594                                 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
596                         return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
597                                 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
598                 }
599         };
601         mw.util = util;
603 } )( jQuery, mediaWiki );