]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - resources/mediawiki.util/mediawiki.util.js
MediaWiki 1.17.0
[autoinstalls/mediawiki.git] / resources / mediawiki.util / mediawiki.util.js
1 /*
2  * Utilities
3  */
4 ( function( $, mw ) {
5
6         mediaWiki.util = {
7
8                 /* Initialisation */
9                 'initialised' : false,
10                 'init' : function () {
11                         if ( this.initialised === false ) {
12                                 this.initialised = true;
13
14                                 // Any initialisation after the DOM is ready
15                                 $( function() {
16
17                                         // Shortcut
18                                         var profile = $.client.profile();
19
20                                         // Set tooltipAccessKeyPrefix
21
22                                         // Opera on any platform
23                                         if ( profile.name == 'opera' ) {
24                                                 mw.util.tooltipAccessKeyPrefix = 'shift-esc-';
25
26                                         // Chrome on any platform
27                                         } else if ( profile.name == 'chrome' ) {
28                                                 // Chrome on Mac or Chrome on other platform ?
29                                                 mw.util.tooltipAccessKeyPrefix = ( profile.platform == 'mac'
30                                                         ? 'ctrl-option-' : 'alt-' );
31
32                                         // Non-Windows Safari with webkit_version > 526
33                                         } else if ( profile.platform !== 'win'
34                                                 && profile.name == 'safari'
35                                                 && profile.layoutVersion > 526 )
36                                         {
37                                                 mw.util.tooltipAccessKeyPrefix = 'ctrl-alt-';
38
39                                         // Safari/Konqueror on any platform, or any browser on Mac
40                                         // (but not Safari on Windows)
41                                         } else if ( !( profile.platform == 'win' && profile.name == 'safari' )
42                                                                         && ( profile.name == 'safari'
43                                                                         || profile.platform == 'mac'
44                                                                         || profile.name == 'konqueror' ) ) {
45                                                 mw.util.tooltipAccessKeyPrefix = 'ctrl-';
46
47                                         // Firefox 2.x
48                                         } else if ( profile.name == 'firefox' && profile.versionBase == '2' ) {
49                                                 mw.util.tooltipAccessKeyPrefix = 'alt-shift-';
50                                         }
51
52                                         // Enable CheckboxShiftClick
53                                         $('input[type=checkbox]:not(.noshiftselect)').checkboxShiftClick();
54
55                                         // Emulate placeholder if not supported by browser
56                                         if ( !( 'placeholder' in document.createElement( 'input' ) ) ) {
57                                                 $('input[placeholder]').placeholder();
58                                         }
59
60                                         // Fill $content var
61                                         if ( $('#bodyContent').length ) {
62                                                 mw.util.$content = $('#bodyContent');
63                                         } else if ( $('#article').length ) {
64                                                 mw.util.$content = $('#article');
65                                         } else {
66                                                 mw.util.$content = $('#content');
67                                         }
68                                 });
69
70                                 return true;
71                         }
72                         return false;
73                 },
74
75                 /* Main body */
76
77                 /**
78                  * Encode the string like PHP's rawurlencode
79                  *
80                  * @param str String to be encoded
81                  */
82                 'rawurlencode' : function( str ) {
83                         str = (str + '').toString();
84                         return encodeURIComponent( str )
85                                 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
86                                 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
87                 },
88
89                 /**
90                  * Encode page titles for use in a URL
91                  * We want / and : to be included as literal characters in our title URLs
92                  * as they otherwise fatally break the title
93                  *
94                  * @param str String to be encoded
95                  */
96                 'wikiUrlencode' : function( str ) {
97                         return this.rawurlencode( str )
98                                 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
99                 },
100
101                 /**
102                  * Append a new style block to the head
103                  *
104                  * @param text String CSS to be appended
105                  * @return the CSS stylesheet
106                  */
107                 'addCSS' : function( text ) {
108                         var s = document.createElement( 'style' );
109                         s.type = 'text/css';
110                         s.rel = 'stylesheet';
111                         if ( s.styleSheet ) {
112                                 s.styleSheet.cssText = text; // IE
113                         } else {
114                                 s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
115                         }
116                         document.getElementsByTagName("head")[0].appendChild( s );
117                         return s.sheet || s;
118                 },
119
120                 /**
121                  * Get the full URL to a page name
122                  *
123                  * @param str Page name to link to
124                  */
125                 'wikiGetlink' : function( str ) {
126                         return wgServer + wgArticlePath.replace( '$1', this.wikiUrlencode( str ) );
127                 },
128
129                 /**
130                  * Grab the URL parameter value for the given parameter.
131                  * Returns null if not found.
132                  *
133                  * @param param The parameter name
134                  * @param url URL to search through (optional)
135                  */
136                 'getParamValue' : function( param, url ) {
137                         url = url ? url : document.location.href;
138                         // Get last match, stop at hash
139                         var re = new RegExp( '[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' );
140                         var m = re.exec( url );
141                         if ( m && m.length > 1 ) {
142                                 return decodeURIComponent( m[1] );
143                         }
144                         return null;
145                 },
146
147                 // Access key prefix.
148                 // Will be re-defined based on browser/operating system detection in
149                 // mw.util.init().
150                 'tooltipAccessKeyPrefix' : 'alt-',
151
152                 // Regex to match accesskey tooltips
153                 'tooltipAccessKeyRegexp': /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
154
155                 /**
156                  * Add the appropriate prefix to the accesskey shown in the tooltip.
157                  * If the nodeList parameter is given, only those nodes are updated;
158                  * otherwise, all the nodes that will probably have accesskeys by
159                  * default are updated.
160                  *
161                  * @param nodeList jQuery object, or array of elements
162                  */
163                 'updateTooltipAccessKeys' : function( nodeList ) {
164                         var $nodes;
165                         if ( nodeList instanceof jQuery ) {
166                                 $nodes = nodeList;
167                         } else if ( nodeList ) {
168                                 $nodes = $(nodeList);
169                         } else {
170                                 // Rather than scanning all links, just the elements that
171                                 // contain the relevant links
172                                 this.updateTooltipAccessKeys(
173                                         $('#column-one a, #mw-head a, #mw-panel a, #p-logo a') );
174
175                                 // these are rare enough that no such optimization is needed
176                                 this.updateTooltipAccessKeys( $('input') );
177                                 this.updateTooltipAccessKeys( $('label') );
178                                 return;
179                         }
180
181                         $nodes.each( function ( i ) {
182                                 var tip = $(this).attr( 'title' );
183                                 if ( !!tip && mw.util.tooltipAccessKeyRegexp.exec( tip ) ) {
184                                         tip = tip.replace( mw.util.tooltipAccessKeyRegexp,
185                                                 '[' + mw.util.tooltipAccessKeyPrefix + "$5]" );
186                                         $(this).attr( 'title', tip );
187                                 }
188                         });
189                 },
190
191                 // jQuery object that refers to the page-content element
192                 // Populated by init()
193                 '$content' : null,
194
195                 /**
196                  * Add a link to a portlet menu on the page, such as:
197                  *
198                  * p-cactions (Content actions), p-personal (Personal tools),
199                  * p-navigation (Navigation), p-tb (Toolbox)
200                  *
201                  * The first three paramters are required, others are optionals. Though
202                  * providing an id and tooltip is recommended.
203                  *
204                  * By default the new link will be added to the end of the list. To
205                  * add the link before a given existing item, pass the DOM node
206                  * (document.getElementById('foobar')) or the jQuery-selector
207                  * ('#foobar') of that item.
208                  *
209                  * @example mw.util.addPortletLink(
210                  *       'p-tb', 'http://mediawiki.org/',
211                  *       'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
212                  * )
213                  *
214                  * @param portlet ID of the target portlet ('p-cactions' or 'p-personal' etc.)
215                  * @param href Link URL
216                  * @param text Link text (will be automatically converted to lower
217                  *       case by CSS for p-cactions in Monobook)
218                  * @param id ID of the new item, should be unique and preferably have
219                  *       the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
220                  * @param tooltip Text to show when hovering over the link, without accesskey suffix
221                  * @param accesskey Access key to activate this link (one character, try
222                  *       to avoid conflicts. Use $( '[accesskey=x' ).get() in the console to
223                  *       see if 'x' is already used.
224                  * @param nextnode DOM node or jQuery-selector of the item that the new
225                  *       item should be added before, should be another item in the same
226                  *       list will be ignored if not the so
227                  *
228                  * @return The DOM node of the new item (a LI element, or A element for
229                  *       older skins) or null.
230                  */
231                 'addPortletLink' : function( portlet, href, text, id, tooltip, accesskey, nextnode ) {
232
233                         // Check if there's atleast 3 arguments to prevent a TypeError
234                         if ( arguments.length < 3 ) {
235                                 return null;
236                         }
237                         // Setup the anchor tag
238                         var $link = $( '<a></a>' ).attr( 'href', href ).text( text );
239                         if ( tooltip ) {
240                                 $link.attr( 'title', tooltip );
241                         }
242
243                         // Some skins don't have any portlets
244                         // just add it to the bottom of their 'sidebar' element as a fallback
245                         switch ( skin ) {
246                         case 'standard' :
247                         case 'cologneblue' :
248                                 $("#quickbar").append($link.after( '<br />' ));
249                                 return $link.get(0);
250                         case 'nostalgia' :
251                                 $("#searchform").before($link).before( ' &#124; ' );
252                                 return $link.get(0);
253                         default : // Skins like chick, modern, monobook, myskin, simple, vector...
254
255                                 // Select the specified portlet
256                                 var $portlet = $('#' + portlet);
257                                 if ( $portlet.length === 0 ) {
258                                         return null;
259                                 }
260                                 // Select the first (most likely only) unordered list inside the portlet
261                                 var $ul = $portlet.find( 'ul' ).eq( 0 );
262
263                                 // If it didn't have an unordered list yet, create it
264                                 if ($ul.length === 0) {
265                                         // If there's no <div> inside, append it to the portlet directly
266                                         if ($portlet.find( 'div' ).length === 0) {
267                                                 $portlet.append( '<ul></ul>' );
268                                         } else {
269                                                 // otherwise if there's a div (such as div.body or div.pBody)
270                                                 // append the <ul> to last (most likely only) div
271                                                 $portlet.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
272                                         }
273                                         // Select the created element
274                                         $ul = $portlet.find( 'ul' ).eq( 0 );
275                                 }
276                                 // Just in case..
277                                 if ( $ul.length === 0 ) {
278                                         return null;
279                                 }
280
281                                 // Unhide portlet if it was hidden before
282                                 $portlet.removeClass( 'emptyPortlet' );
283
284                                 // Wrap the anchor tag in a <span> and create a list item for it
285                                 // and back up the selector to the list item
286                                 var $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
287
288                                 // Implement the properties passed to the function
289                                 if ( id ) {
290                                         $item.attr( 'id', id );
291                                 }
292                                 if ( accesskey ) {
293                                         $link.attr( 'accesskey', accesskey );
294                                         tooltip += ' [' + accesskey + ']';
295                                 }
296                                 if ( tooltip ) {
297                                         $link.attr( 'title', tooltip );
298                                 }
299                                 if ( accesskey && tooltip ) {
300                                         this.updateTooltipAccessKeys( $link );
301                                 }
302
303                                 // Append using DOM-element passing
304                                 if ( nextnode && nextnode.parentNode == $ul.get( 0 ) ) {
305                                         $(nextnode).before( $item );
306                                 } else {
307                                         // If the jQuery selector isn't found within the <ul>, just
308                                         // append it at the end
309                                         if ( $ul.find( nextnode ).length === 0 ) {
310                                                 $ul.append( $item );
311                                         } else {
312                                                 // Append using jQuery CSS selector
313                                                 $ul.find( nextnode ).eq( 0 ).before( $item );
314                                         }
315                                 }
316
317                                 return $item.get( 0 );
318                         }
319                 },
320         
321                 /**
322                  * Validate a string as representing a valid e-mail address
323                  * according to HTML5 specification. Please note the specification
324                  * does not validate a domain with one character.
325                  *
326                  * FIXME: should be moved to a JavaScript validation module.
327                  */
328                 'validateEmail' : function( mailtxt ) {
329                         if( mailtxt === '' ) {
330                                 return null;
331                         }
332                 
333                         /**
334                          * HTML5 defines a string as valid e-mail address if it matches
335                          * the ABNF:
336                          *      1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
337                          * With:
338                          * - atext      : defined in RFC 5322 section 3.2.3
339                          * - ldh-str : defined in RFC 1034 section 3.5
340                          *
341                          * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
342                          */
343                 
344                         /**
345                          * First, define the RFC 5322 'atext' which is pretty easy :
346                          * atext = ALPHA / DIGIT / ; Printable US-ASCII
347                                                  "!" / "#" /     ; characters not including
348                                                  "$" / "%" /     ; specials. Used for atoms.
349                                                  "&" / "'" /
350                                                  "*" / "+" /
351                                                  "-" / "/" /
352                                                  "=" / "?" /
353                                                  "^" / "_" /
354                                                  "`" / "{" /
355                                                  "|" / "}" /
356                                                  "~"
357                         */
358                         var     rfc5322_atext = "a-z0-9!#$%&'*+\\-/=?^_`{|}~",
359                 
360                         /**
361                          * Next define the RFC 1034 'ldh-str'
362                          *      <domain> ::= <subdomain> | " "
363                          *      <subdomain> ::= <label> | <subdomain> "." <label>
364                          *      <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
365                          *      <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
366                          *      <let-dig-hyp> ::= <let-dig> | "-"
367                          *      <let-dig> ::= <letter> | <digit>
368                          */
369                                 rfc1034_ldh_str = "a-z0-9\\-",
370         
371                                 HTML5_email_regexp = new RegExp(
372                                         // start of string
373                                         '^'
374                                         +
375                                         // User part which is liberal :p
376                                         '[' + rfc5322_atext + '\\.]+'
377                                         +
378                                         // "at"
379                                         '@'
380                                         +
381                                         // Domain first part
382                                         '[' + rfc1034_ldh_str + ']+'
383                                         +
384                                         // Optional second part and following are separated by a dot
385                                         '(?:\\.[' + rfc1034_ldh_str + ']+)*'
386                                         +
387                                         // End of string
388                                         '$',
389                                         // RegExp is case insensitive
390                                         'i'
391                                 );
392                         return (null !== mailtxt.match( HTML5_email_regexp ) );
393                 }
394
395         };
396
397         mediaWiki.util.init();
398
399 } )( jQuery, mediaWiki );