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