]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - resources/mediawiki.util/mediawiki.util.js
MediaWiki 1.17.4
[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                                 // Beware that decodeURIComponent is not required to understand '+'
143                                 // by spec, as encodeURIComponent does not produce it.
144                                 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
145                         }
146                         return null;
147                 },
148
149                 // Access key prefix.
150                 // Will be re-defined based on browser/operating system detection in
151                 // mw.util.init().
152                 'tooltipAccessKeyPrefix' : 'alt-',
153
154                 // Regex to match accesskey tooltips
155                 'tooltipAccessKeyRegexp': /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
156
157                 /**
158                  * Add the appropriate prefix to the accesskey shown in the tooltip.
159                  * If the nodeList parameter is given, only those nodes are updated;
160                  * otherwise, all the nodes that will probably have accesskeys by
161                  * default are updated.
162                  *
163                  * @param nodeList jQuery object, or array of elements
164                  */
165                 'updateTooltipAccessKeys' : function( nodeList ) {
166                         var $nodes;
167                         if ( nodeList instanceof jQuery ) {
168                                 $nodes = nodeList;
169                         } else if ( nodeList ) {
170                                 $nodes = $(nodeList);
171                         } else {
172                                 // Rather than scanning all links, just the elements that
173                                 // contain the relevant links
174                                 this.updateTooltipAccessKeys(
175                                         $('#column-one a, #mw-head a, #mw-panel a, #p-logo a') );
176
177                                 // these are rare enough that no such optimization is needed
178                                 this.updateTooltipAccessKeys( $('input') );
179                                 this.updateTooltipAccessKeys( $('label') );
180                                 return;
181                         }
182
183                         $nodes.each( function ( i ) {
184                                 var tip = $(this).attr( 'title' );
185                                 if ( !!tip && mw.util.tooltipAccessKeyRegexp.exec( tip ) ) {
186                                         tip = tip.replace( mw.util.tooltipAccessKeyRegexp,
187                                                 '[' + mw.util.tooltipAccessKeyPrefix + "$5]" );
188                                         $(this).attr( 'title', tip );
189                                 }
190                         });
191                 },
192
193                 // jQuery object that refers to the page-content element
194                 // Populated by init()
195                 '$content' : null,
196
197                 /**
198                  * Add a link to a portlet menu on the page, such as:
199                  *
200                  * p-cactions (Content actions), p-personal (Personal tools),
201                  * p-navigation (Navigation), p-tb (Toolbox)
202                  *
203                  * The first three paramters are required, others are optionals. Though
204                  * providing an id and tooltip is recommended.
205                  *
206                  * By default the new link will be added to the end of the list. To
207                  * add the link before a given existing item, pass the DOM node
208                  * (document.getElementById('foobar')) or the jQuery-selector
209                  * ('#foobar') of that item.
210                  *
211                  * @example mw.util.addPortletLink(
212                  *       'p-tb', 'http://mediawiki.org/',
213                  *       'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
214                  * )
215                  *
216                  * @param portlet ID of the target portlet ('p-cactions' or 'p-personal' etc.)
217                  * @param href Link URL
218                  * @param text Link text (will be automatically converted to lower
219                  *       case by CSS for p-cactions in Monobook)
220                  * @param id ID of the new item, should be unique and preferably have
221                  *       the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
222                  * @param tooltip Text to show when hovering over the link, without accesskey suffix
223                  * @param accesskey Access key to activate this link (one character, try
224                  *       to avoid conflicts. Use $( '[accesskey=x' ).get() in the console to
225                  *       see if 'x' is already used.
226                  * @param nextnode DOM node or jQuery-selector of the item that the new
227                  *       item should be added before, should be another item in the same
228                  *       list will be ignored if not the so
229                  *
230                  * @return The DOM node of the new item (a LI element, or A element for
231                  *       older skins) or null.
232                  */
233                 'addPortletLink' : function( portlet, href, text, id, tooltip, accesskey, nextnode ) {
234
235                         // Check if there's atleast 3 arguments to prevent a TypeError
236                         if ( arguments.length < 3 ) {
237                                 return null;
238                         }
239                         // Setup the anchor tag
240                         var $link = $( '<a></a>' ).attr( 'href', href ).text( text );
241                         if ( tooltip ) {
242                                 $link.attr( 'title', tooltip );
243                         }
244
245                         // Some skins don't have any portlets
246                         // just add it to the bottom of their 'sidebar' element as a fallback
247                         switch ( skin ) {
248                         case 'standard' :
249                         case 'cologneblue' :
250                                 $("#quickbar").append($link.after( '<br />' ));
251                                 return $link.get(0);
252                         case 'nostalgia' :
253                                 $("#searchform").before($link).before( ' &#124; ' );
254                                 return $link.get(0);
255                         default : // Skins like chick, modern, monobook, myskin, simple, vector...
256
257                                 // Select the specified portlet
258                                 var $portlet = $('#' + portlet);
259                                 if ( $portlet.length === 0 ) {
260                                         return null;
261                                 }
262                                 // Select the first (most likely only) unordered list inside the portlet
263                                 var $ul = $portlet.find( 'ul' ).eq( 0 );
264
265                                 // If it didn't have an unordered list yet, create it
266                                 if ($ul.length === 0) {
267                                         // If there's no <div> inside, append it to the portlet directly
268                                         if ($portlet.find( 'div' ).length === 0) {
269                                                 $portlet.append( '<ul></ul>' );
270                                         } else {
271                                                 // otherwise if there's a div (such as div.body or div.pBody)
272                                                 // append the <ul> to last (most likely only) div
273                                                 $portlet.find( 'div' ).eq( -1 ).append( '<ul></ul>' );
274                                         }
275                                         // Select the created element
276                                         $ul = $portlet.find( 'ul' ).eq( 0 );
277                                 }
278                                 // Just in case..
279                                 if ( $ul.length === 0 ) {
280                                         return null;
281                                 }
282
283                                 // Unhide portlet if it was hidden before
284                                 $portlet.removeClass( 'emptyPortlet' );
285
286                                 // Wrap the anchor tag in a <span> and create a list item for it
287                                 // and back up the selector to the list item
288                                 var $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
289
290                                 // Implement the properties passed to the function
291                                 if ( id ) {
292                                         $item.attr( 'id', id );
293                                 }
294                                 if ( accesskey ) {
295                                         $link.attr( 'accesskey', accesskey );
296                                         tooltip += ' [' + accesskey + ']';
297                                 }
298                                 if ( tooltip ) {
299                                         $link.attr( 'title', tooltip );
300                                 }
301                                 if ( accesskey && tooltip ) {
302                                         this.updateTooltipAccessKeys( $link );
303                                 }
304
305                                 // Append using DOM-element passing
306                                 if ( nextnode && nextnode.parentNode == $ul.get( 0 ) ) {
307                                         $(nextnode).before( $item );
308                                 } else {
309                                         // If the jQuery selector isn't found within the <ul>, just
310                                         // append it at the end
311                                         if ( $ul.find( nextnode ).length === 0 ) {
312                                                 $ul.append( $item );
313                                         } else {
314                                                 // Append using jQuery CSS selector
315                                                 $ul.find( nextnode ).eq( 0 ).before( $item );
316                                         }
317                                 }
318
319                                 return $item.get( 0 );
320                         }
321                 },
322         
323                 /**
324                  * Validate a string as representing a valid e-mail address
325                  * according to HTML5 specification. Please note the specification
326                  * does not validate a domain with one character.
327                  *
328                  * FIXME: should be moved to a JavaScript validation module.
329                  */
330                 'validateEmail' : function( mailtxt ) {
331                         if( mailtxt === '' ) {
332                                 return null;
333                         }
334                 
335                         /**
336                          * HTML5 defines a string as valid e-mail address if it matches
337                          * the ABNF:
338                          *      1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
339                          * With:
340                          * - atext      : defined in RFC 5322 section 3.2.3
341                          * - ldh-str : defined in RFC 1034 section 3.5
342                          *
343                          * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
344                          */
345                 
346                         /**
347                          * First, define the RFC 5322 'atext' which is pretty easy :
348                          * atext = ALPHA / DIGIT / ; Printable US-ASCII
349                                                  "!" / "#" /     ; characters not including
350                                                  "$" / "%" /     ; specials. Used for atoms.
351                                                  "&" / "'" /
352                                                  "*" / "+" /
353                                                  "-" / "/" /
354                                                  "=" / "?" /
355                                                  "^" / "_" /
356                                                  "`" / "{" /
357                                                  "|" / "}" /
358                                                  "~"
359                         */
360                         var     rfc5322_atext = "a-z0-9!#$%&'*+\\-/=?^_`{|}~",
361                 
362                         /**
363                          * Next define the RFC 1034 'ldh-str'
364                          *      <domain> ::= <subdomain> | " "
365                          *      <subdomain> ::= <label> | <subdomain> "." <label>
366                          *      <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
367                          *      <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
368                          *      <let-dig-hyp> ::= <let-dig> | "-"
369                          *      <let-dig> ::= <letter> | <digit>
370                          */
371                                 rfc1034_ldh_str = "a-z0-9\\-",
372         
373                                 HTML5_email_regexp = new RegExp(
374                                         // start of string
375                                         '^'
376                                         +
377                                         // User part which is liberal :p
378                                         '[' + rfc5322_atext + '\\.]+'
379                                         +
380                                         // "at"
381                                         '@'
382                                         +
383                                         // Domain first part
384                                         '[' + rfc1034_ldh_str + ']+'
385                                         +
386                                         // Optional second part and following are separated by a dot
387                                         '(?:\\.[' + rfc1034_ldh_str + ']+)*'
388                                         +
389                                         // End of string
390                                         '$',
391                                         // RegExp is case insensitive
392                                         'i'
393                                 );
394                         return (null !== mailtxt.match( HTML5_email_regexp ) );
395                 }
396
397         };
398
399         mediaWiki.util.init();
400
401 } )( jQuery, mediaWiki );