Upload license preview now uses the API instead of action=ajax
[lhc/web/wiklou.git] / skins / common / upload.js
1 function licenseSelectorCheck() {
2 var selector = document.getElementById( "wpLicense" );
3 var selection = selector.options[selector.selectedIndex].value;
4 if( selector.selectedIndex > 0 ) {
5 if( selection == "" ) {
6 // Option disabled, but browser is broken and doesn't respect this
7 selector.selectedIndex = 0;
8 }
9 }
10 // We might show a preview
11 wgUploadLicenseObj.fetchPreview( selection );
12 }
13
14 function wgUploadSetup() {
15 // Disable URL box if the URL copy upload source type is not selected
16 var e = document.getElementById( 'wpSourceTypeURL' );
17 if( e ) {
18 if( !e.checked ) {
19 var ein = document.getElementById( 'wpUploadFileURL' );
20 if(ein)
21 ein.setAttribute( 'disabled', 'disabled' );
22 }
23 }
24
25 // For MSIE/Mac: non-breaking spaces cause the <option> not to render.
26 // But for some reason, setting the text to itself works
27 var selector = document.getElementById("wpLicense");
28 if (selector) {
29 var ua = navigator.userAgent;
30 var isMacIe = (ua.indexOf("MSIE") != -1) && (ua.indexOf("Mac") != -1);
31 if (isMacIe) {
32 for (var i = 0; i < selector.options.length; i++) {
33 selector.options[i].text = selector.options[i].text;
34 }
35 }
36 }
37
38 // Toggle source type
39 var sourceTypeCheckboxes = document.getElementsByName( 'wpSourceType' );
40 for ( var i = 0; i < sourceTypeCheckboxes.length; i++ ) {
41 sourceTypeCheckboxes[i].onchange = toggleUploadInputs;
42 }
43
44 // AJAX wpDestFile warnings
45 if ( wgAjaxUploadDestCheck ) {
46 document.getElementById( 'wpDestFile' ).onchange = function ( e ) {
47 wgUploadWarningObj.checkNow(this.value);
48 };
49 var optionsTable = document.getElementById( 'mw-htmlform-description' ).tBodies[0];
50 var row = document.createElement( 'tr' );
51 var td = document.createElement( 'td' );
52 td.id = 'wpDestFile-warning';
53 td.colSpan = 2;
54
55 row.appendChild( td );
56 optionsTable.insertBefore( row, optionsTable.children[1] );
57 }
58
59 if ( wgAjaxLicensePreview ) {
60 // License selector check
61 document.getElementById( 'wpLicense' ).onchange = licenseSelectorCheck;
62
63 // License selector table row
64 var wpLicense = document.getElementById( 'wpLicense' );
65 var wpLicenseRow = wpLicense.parentNode.parentNode;
66 var wpLicenseTbody = wpLicenseRow.parentNode;
67
68 var row = document.createElement( 'tr' );
69 var td = document.createElement( 'td' );
70 row.appendChild( td );
71 td = document.createElement( 'td' );
72 td.id = 'mw-license-preview';
73 row.appendChild( td );
74
75 wpLicenseTbody.insertBefore( row, wpLicenseRow.nextSibling );
76 }
77
78
79 // fillDestFile setup
80 for ( var i = 0; i < wgUploadSourceIds.length; i++ )
81 document.getElementById( wgUploadSourceIds[i] ).onchange = function (e) {
82 fillDestFilename( this.id );
83 };
84 }
85
86 /**
87 * Iterate over all upload source fields and disable all except the selected one.
88 *
89 * @param enabledId The id of the selected radio button
90 * @return emptiness
91 */
92 function toggleUploadInputs() {
93 // Iterate over all rows with UploadSourceField
94 var rows;
95 if ( document.getElementsByClassName ) {
96 rows = document.getElementsByClassName( 'mw-htmlform-field-UploadSourceField' );
97 } else {
98 // Older browsers don't support getElementsByClassName
99 rows = new Array();
100
101 var allRows = document.getElementsByTagName( 'tr' );
102 for ( var i = 0; i < allRows.length; i++ ) {
103 if ( allRows[i].className == 'mw-htmlform-field-UploadSourceField' )
104 rows.push( allRows[i] );
105 }
106 }
107
108 for ( var i = 0; i < rows.length; i++ ) {
109 var inputs = rows[i].getElementsByTagName( 'input' );
110
111 // Check if this row is selected
112 var isChecked = true; // Default true in case wpSourceType is not found
113 for ( var j = 0; j < inputs.length; j++ ) {
114 if ( inputs[j].name == 'wpSourceType' )
115 isChecked = inputs[j].checked;
116 }
117
118 // Disable all unselected rows
119 for ( var j = 0; j < inputs.length; j++ ) {
120 if ( inputs[j].type != 'radio')
121 inputs[j].disabled = !isChecked;
122 }
123 }
124 }
125
126 var wgUploadWarningObj = {
127 'responseCache' : { '' : '&nbsp;' },
128 'nameToCheck' : '',
129 'typing': false,
130 'delay': 500, // ms
131 'timeoutID': false,
132
133 'keypress': function () {
134 if ( !wgAjaxUploadDestCheck || !sajax_init_object() ) return;
135
136 // Find file to upload
137 var destFile = document.getElementById('wpDestFile');
138 var warningElt = document.getElementById( 'wpDestFile-warning' );
139 if ( !destFile || !warningElt ) return ;
140
141 this.nameToCheck = destFile.value ;
142
143 // Clear timer
144 if ( this.timeoutID ) {
145 window.clearTimeout( this.timeoutID );
146 }
147 // Check response cache
148 for (cached in this.responseCache) {
149 if (this.nameToCheck == cached) {
150 this.setWarning(this.responseCache[this.nameToCheck]);
151 return;
152 }
153 }
154
155 this.timeoutID = window.setTimeout( 'wgUploadWarningObj.timeout()', this.delay );
156 },
157
158 'checkNow': function (fname) {
159 if ( !wgAjaxUploadDestCheck || !sajax_init_object() ) return;
160 if ( this.timeoutID ) {
161 window.clearTimeout( this.timeoutID );
162 }
163 this.nameToCheck = fname;
164 this.timeout();
165 },
166
167 'timeout' : function() {
168 if ( !wgAjaxUploadDestCheck || !sajax_init_object() ) return;
169 injectSpinner( document.getElementById( 'wpDestFile' ), 'destcheck' );
170
171 // Get variables into local scope so that they will be preserved for the
172 // anonymous callback. fileName is copied so that multiple overlapping
173 // ajax requests can be supported.
174 var obj = this;
175 var fileName = this.nameToCheck;
176 sajax_do_call( 'SpecialUpload::ajaxGetExistsWarning', [this.nameToCheck],
177 function (result) {
178 obj.processResult(result, fileName)
179 }
180 );
181 },
182
183 'processResult' : function (result, fileName) {
184 removeSpinner( 'destcheck' );
185 this.setWarning(result.responseText);
186 this.responseCache[fileName] = result.responseText;
187 },
188
189 'setWarning' : function (warning) {
190 var warningElt = document.getElementById( 'wpDestFile-warning' );
191 var ackElt = document.getElementsByName( 'wpDestFileWarningAck' );
192
193 this.setInnerHTML(warningElt, warning);
194
195 // Set a value in the form indicating that the warning is acknowledged and
196 // doesn't need to be redisplayed post-upload
197 if ( warning == '' || warning == '&nbsp;' ) {
198 ackElt[0].value = '';
199 } else {
200 ackElt[0].value = '1';
201 }
202
203 },
204 'setInnerHTML' : function (element, text) {
205 // Check for no change to avoid flicker in IE 7
206 if (element.innerHTML != text) {
207 element.innerHTML = text;
208 }
209 }
210 }
211
212 function fillDestFilename(id) {
213 if (!wgUploadAutoFill) {
214 return;
215 }
216 if (!document.getElementById) {
217 return;
218 }
219 // Remove any previously flagged errors
220 var e = document.getElementById( 'mw-upload-permitted' );
221 if( e ) e.className = '';
222
223 var e = document.getElementById( 'mw-upload-prohibited' );
224 if( e ) e.className = '';
225
226 var path = document.getElementById(id).value;
227 // Find trailing part
228 var slash = path.lastIndexOf('/');
229 var backslash = path.lastIndexOf('\\');
230 var fname;
231 if (slash == -1 && backslash == -1) {
232 fname = path;
233 } else if (slash > backslash) {
234 fname = path.substring(slash+1, 10000);
235 } else {
236 fname = path.substring(backslash+1, 10000);
237 }
238
239 // Clear the filename if it does not have a valid extension.
240 // URLs are less likely to have a useful extension, so don't include them in the
241 // extension check.
242 if( wgFileExtensions && id != 'wpUploadFileURL' ) {
243 var found = false;
244 if( fname.lastIndexOf( '.' ) != -1 ) {
245 var ext = fname.substr( fname.lastIndexOf( '.' ) + 1 );
246 for( var i = 0; i < wgFileExtensions.length; i++ ) {
247 if( wgFileExtensions[i].toLowerCase() == ext.toLowerCase() ) {
248 found = true;
249 break;
250 }
251 }
252 }
253 if( !found ) {
254 // Not a valid extension
255 // Clear the upload and set mw-upload-permitted to error
256 document.getElementById(id).value = '';
257 var e = document.getElementById( 'mw-upload-permitted' );
258 if( e ) e.className = 'error';
259
260 var e = document.getElementById( 'mw-upload-prohibited' );
261 if( e ) e.className = 'error';
262
263 // Clear wpDestFile as well
264 var e = document.getElementById( 'wpDestFile' )
265 if( e ) e.value = '';
266
267 return false;
268 }
269 }
270
271 // Capitalise first letter and replace spaces by underscores
272 // FIXME: $wgCapitalizedNamespaces
273 fname = fname.charAt(0).toUpperCase().concat(fname.substring(1,10000)).replace(/ /g, '_');
274
275 // Output result
276 var destFile = document.getElementById('wpDestFile');
277 if (destFile) {
278 destFile.value = fname;
279 wgUploadWarningObj.checkNow(fname) ;
280 }
281 }
282
283 function toggleFilenameFiller() {
284 if(!document.getElementById) return;
285 var upfield = document.getElementById('wpUploadFile');
286 var destName = document.getElementById('wpDestFile').value;
287 if (destName=='' || destName==' ') {
288 wgUploadAutoFill = true;
289 } else {
290 wgUploadAutoFill = false;
291 }
292 }
293
294 var wgUploadLicenseObj = {
295
296 'responseCache' : { '' : '' },
297
298 'fetchPreview': function( license ) {
299 if( !wgAjaxLicensePreview ) return;
300 for (cached in this.responseCache) {
301 if (cached == license) {
302 this.showPreview( this.responseCache[license] );
303 return;
304 }
305 }
306 injectSpinner( document.getElementById( 'wpLicense' ), 'license' );
307
308 var title = document.getElementById('wpDestFile').value;
309 if ( !title ) title = 'File:Sample.jpg';
310
311 var url = wgScriptPath + '/api' + wgScriptExtension
312 + '?action=parse&text={{' + encodeURIComponent( license ) + '}}'
313 + '&title=' + encodeURIComponent( title )
314 + '&prop=text&pst&format=json';
315
316 var req = sajax_init_object();
317 req.onreadystatechange = function() {
318 if ( req.readyState == 4 && req.status == 200 )
319 wgUploadLicenseObj.processResult( eval( '(' + req.responseText + ')' ), license );
320 };
321 req.open( 'GET', url, true );
322 req.send( '' );
323 },
324
325 'processResult' : function( result, license ) {
326 removeSpinner( 'license' );
327 this.responseCache[license] = result['parse']['text']['*'];
328 this.showPreview( this.responseCache[license] );
329
330 },
331
332 'showPreview' : function( preview ) {
333 var previewPanel = document.getElementById( 'mw-license-preview' );
334 if( previewPanel.innerHTML != preview )
335 previewPanel.innerHTML = preview;
336 }
337
338 }
339
340 addOnloadHook( wgUploadSetup );