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