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