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