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