2 * the base Upload Interface for uploading.
4 * this base uploader is optionally extended by firefogg
7 "upload-transcode-in-progress":"Doing Transcode & Upload (do not close this window)",
8 "upload-in-progress": "Upload in Progress (do not close this window)",
9 "upload-transcoded-status": "Transcoded",
10 "uploaded-status": "Uploaded",
12 "wgfogg_wrong_version": "You have firefogg installed but its outdated, <a href=\"http://firefogg.org\">please upgrade</a> ",
13 "upload-stats-fileprogres": "$1 of $2",
15 "mv_upload_completed": "Your upload is complete",
17 "mv_upload_done" : "Your upload <i>should be</i> accessible <a href=\"$1\">here</a>",
18 "upload-unknown-size": "Unknown size",
20 "mv-cancel-confim" : "Are you sure you want to cancel?",
22 "successfulupload" : "Successful Upload",
23 "uploaderror" : "Upload error",
24 "uploadwarning": "Upload warning",
25 "unknown-error": "Unknown Error",
26 "return-to-form": "Return to form",
28 "file-exists-duplicate" : "This file is a duplicate of the following file",
29 "fileexists" : "A file with this name exists already, please check <b><tt>$1</tt></b> if you are not sure if you want to change it.",
30 "fileexists-thumb": "<center><b>Existing file</b></center>",
31 "ignorewarning" : "Ignore warning and save file anyway",
32 "file-thumbnail-no" : "The filename begins with <b><tt>$1</tt></b>",
33 "go-to-resource" : "Go to Resource Page",
34 "upload-misc-error" : "Unknown upload error",
36 "wgfogg_waring_bad_extension" : "You have selected a file with an unsuported extension (<a href=\"http://commons.wikimedia.org/wiki/Commons:Firefogg#Supported_File_Types\">more information</a>).",
38 "cancel-button" : "Cancel",
44 var default_bui_options
= {
46 'parent_uploader':null,
48 'done_upload_cb': null,
49 'target_edit_from':null,
51 //upload_mode can be 'post', 'api' or 'autodetect'. (autodetect issues an api call)
52 'upload_mode': 'autodetect'
55 var mvBaseUploadInterface = function( iObj
){
56 return this.init( iObj
);
58 mvBaseUploadInterface
.prototype = {
59 parent_uploader
:false,
60 formData
:{}, //the form to be submitted
61 warnings_sessionkey
:null,
62 chunks_supported
:false,
63 form_post_override
:false,
67 init: function( iObj
){
70 //inherit iObj properties:
71 for(var i
in default_bui_options
){
75 this[i
] = default_bui_options
[i
];
81 //set up the local pointer to the edit form:
82 _this
.editForm
= _this
.getEditForm();
83 $j(_this
.editForm
).attr('target', 'f_1');
85 //set up the org_onsubmit if not set:
86 if( typeof( _this
.org_onsubmit
) == 'undefined' && _this
.editForm
.onsubmit
)
87 _this
.org_onsubmit
= _this
.editForm
.onsubmit
;
89 //set up the submit action:
90 $j( _this
.editForm
).submit( function(){
92 //run the original onsubmit (if not run yet set flag to avoid excessive chaining )
93 if( typeof( _this
.org_onsubmit
) == 'function' ){
94 if( ! _this
.org_onsubmit() ){
95 //error in org submit return false;
99 //check for post action override:
100 if( _this
.form_post_override
){
101 js_log('form_post_override is true do form proccessing:');
104 //get the input form data in flat json:
105 var tmpAryData
= $j( _this
.editForm
).serializeArray();
106 for(var i
=0; i
< tmpAryData
.length
; i
++){
107 if( tmpAryData
[i
]['name'] )
108 _this
.formData
[ tmpAryData
[i
]['name'] ] = tmpAryData
[i
]['value'];
110 //put into a try catch so we are sure to return false:
112 //get a clean loader:
113 _this
.dispProgressOverlay();
115 //for some unknown reason we have to drop down the #p-search z-index:
116 $j('#p-search').css('z-index', 1);
118 //select upload mode:
119 _this
.detectUploadMode();
124 //don't submit the form we will do the post in ajax
130 detectUploadMode:function( callback
){
132 //check the upload mode:
133 if( _this
.upload_mode
== 'autodetect' ){
134 js_log('detectUploadMode::' + _this
.upload_mode
+ ' api:' + _this
.api_url
);
135 if( ! _this
.api_url
)
136 return js_error( 'Error: can\'t autodetect mode without api url' );
138 'data':{ 'action':'paraminfo','modules':'upload' },
141 if( typeof data
.paraminfo
== 'undefined' || typeof data
.paraminfo
.modules
== 'undefined' )
142 return js_error( 'Error: bad api results' );
143 if( typeof data
.paraminfo
.modules
[0].classname
== 'undefined'){
144 js_log( 'Autodetect Upload Mode: \'post\' ');
145 _this
.upload_mode
= 'post';
147 js_log( 'Autodetect Upload Mode: api ' );
148 _this
.upload_mode
= 'api';
149 //check to see if chunks are supported:
150 for( var i
in data
.paraminfo
.modules
[0].parameters
){
151 var pname
= data
.paraminfo
.modules
[0].parameters
[i
].name
;
152 if( pname
== 'enablechunks' ){
153 js_log( 'this.chunks_supported = true' );
154 _this
.chunks_supported
= true;
159 js_log("do call: doUploadSwitch");
160 _this
.doUploadSwitch();
163 _this
.doUploadSwitch();
166 doUploadSwitch:function(){
168 js_log('mvUPload:doUploadSwitch():' + _this
.upload_mode
);
169 //issue a normal post request
170 if( _this
.upload_mode
== 'post' ) {
171 //we don't support the upload api
172 //trick the browser into thinking the wpUpload button was pressed (there might be a cleaner way to do this)
173 $j(_this
.editForm
).append(
174 '<input type="hidden" name="wpUpload" value="' + $j('input[name=\'wpUpload\']').val() + '"/>'
177 _this
.form_post_override
= true;
179 _this
.editForm
.submit();
181 _this
.upload_mode
=='api' &&
182 ( $j('#wpSourceTypeFile').length
== 0 || $j('#wpSourceTypeFile').get(0).checked
)
184 //@@TODO check for sendAsBinnary to support firefox 3.5 progress
185 //else remap to iframe target
186 var id
= 'f_' + ($j('iframe').length
+ 1);
187 $j("body").append('<iframe src="javascript:false;" id="' + id
+ '" ' +
188 'name="' + id
+ '" style="display:none;" ></iframe>');
189 //set up the done binding
190 $j('#' + id
).load(function(){
191 var iframe
= $j(this).get(0);
192 _this
.proccessIframeResult( iframe
);
194 //set the editForm iframe target
195 //$j(_this.editForm).attr('target', id);
197 //set the action to the api url:
198 $j(_this
.editForm
).attr('action', _this
.api_url
);
200 if( $j(_this
.editForm
).find("[name='action']").length
== 0)
201 $j(_this
.editForm
).append('<input type="hidden" name="action" value="upload">');
204 if( $j(_this
.editForm
).find("[name='format']").length
== 0)
205 $j(_this
.editForm
).append('<input type="hidden" name="format" value="jsonfm">');
207 //add text format type request (IE tries to "run"/download the script otherwise)
208 if( $j(_this
.editForm
).find("[name='ctypetext']").length
== 0)
209 $j(_this
.editForm
).append('<input type="hidden" name="ctypetext" value="true">');
211 //map the form vars to api vars:
212 $j(_this
.editForm
).find('#wpUploadFile').attr('name', 'file');
213 $j(_this
.editForm
).find('#wpDestFile').attr('name', 'filename');
214 $j(_this
.editForm
).find('#wpUploadDescription').attr('name', 'comment');
215 $j(_this
.editForm
).find('#wpEditToken').attr('name', 'token');
216 $j(_this
.editForm
).find('#wpIgnoreWarning').attr('name', 'ignorewarnings');
217 $j(_this
.editForm
).find('#wpWatchthis').attr('name', 'watch');
219 //update the status to 100% progress bar (no status in iframe submit)
220 $j('#up-progressbar' ).progressbar('value', parseInt( 100 ) );
221 $j('#up-status-container').html( gM('upload-in-progress') );
224 js_log('do iframe form submit');
228 _this
.form_post_override
= true;
229 //reset the done with action flag:
230 _this
.action_done
= false;
232 js_log('do the submit');
233 _this
.editForm
.submit();
236 }else if( _this
.upload_mode
== 'api' && $j('#wpSourceTypeURL').get(0).checked
){
237 js_log('doHttpUpload (no form submit) ');
238 //if the api is supported.. && source type is http do upload with http status updates
240 'url' : $j('#wpUploadFileURL').val(),
241 'filename' : $j('#wpDestFile').val(),
242 'comment' : $j('#wpUploadDescription').val(),
243 'watch' : ($j('#wpWatchthis').is(':checked'))?'true':'false'
245 //set up ignore warnings and watch arguments:
246 if( $j('#wpIgnoreWarning').is(':checked') ){
247 httpUpConf
[ 'ignorewarnings'] = 'true';
249 if( $j('#wpWatchthis').is(':checked') ){
250 httpUpConf
[ 'watch'] = 'true';
252 //check for editToken
253 _this
.etoken
= $j("#wpEditToken").val();
254 _this
.doHttpUpload( httpUpConf
);
256 js_error( 'Error: unrecongized upload mode: ' + _this
.upload_mode
);
260 proccessIframeResult:function(iframe
){
262 var doc
= iframe
.contentDocument
? iframe
.contentDocument
: frames
[iframe
.id
].document
;
264 if (doc
.readyState
&& doc
.readyState
!= 'complete'){
268 if (doc
.body
&& doc
.body
.innerHTML
== "false"){
272 if (doc
.XMLDocument
){
273 // response is a xml document IE property
274 response
= doc
.XMLDocument
;
275 } else if (doc
.body
){
277 json_str
= $j(doc
.body
).find('pre').html();
280 response
= window
["eval"]("(" +json_str
+ ")");
285 // response is a xml document
288 //do proccess the api result
289 _this
.processApiResult( response
);
291 doHttpUpload:function( opt
){
293 //set the http box to loading (in case we don't get an update for some time)
294 $j('#dlbox-centered').html( '<h5>' + _this
.getProgressTitle() + '</h5>' +
295 mv_get_loading_img( 'left:40%;top:20%')
300 'asyncdownload' : true //do a s
302 //set config from options:
307 //else try and get a token:
308 if(!_this
.etoken
&& _this
.api_url
){
309 js_log('Error:doHttpUpload: missing token');
311 req
['token'] =_this
.etoken
;
313 //reset the done with action flag:
314 _this
.action_done
= false;
318 'url' : _this
.api_url
320 _this
.processApiResult( data
);
323 doAjaxWarningIgnore:function(){
325 if( !_this
.upload_session_key
)
326 return js_error('missing upload_session_key (can\'t ignore warnigns');
327 //do the ignore warnings submit to the api:
329 'ignorewarnings' : 'true',
330 'sessionkey' :!_this
.upload_session_key
332 //add token if present:
334 req
['token'] = this.etoken
;
340 _this
.processApiResult(data
);
343 doAjaxUploadStatus:function() {
346 //set up the progress display for status updates:
347 _this
.dispProgressOverlay();
350 'httpstatus' : 'true',
351 'sessionkey' : _this
.upload_session_key
353 //add token if present:
355 req
['token'] = this.etoken
;
357 var uploadStatus = function(){
358 //do the api request:
361 'url' : _this
.api_url
363 //@@check if we are done
364 if( data
.upload
['apiUploadResult'] ){
365 //update status to 100%
366 _this
.updateProgress( 1 );
367 if(typeof JSON
== 'undefined'){
368 //we need to load the jQuery json parser: (older browsers don't have JSON.parse
372 var apiResult
= $j
.secureEvalJSON( data
.upload
['apiUploadResult'] );
373 _this
.processApiResult( apiResult
);
378 apiResult
= JSON
.parse ( data
.upload
['apiUploadResult'] ) ;
380 //could not parse api result
381 js_log('errro: could not parse apiUploadResult ')
383 _this
.processApiResult( apiResult
);
388 //@@ else update status:
389 if( data
.upload
['content_length'] && data
.upload
['loaded'] ){
390 //we have content length we can show percentage done:
391 var perc
= data
.upload
['loaded'] / data
.upload
['content_length'];
393 _this
.updateProgress( perc
);
394 //special case update the file progress where we have data size:
395 $j('#up-status-container').html(
396 gM('upload-stats-fileprogres', [
397 formatSize( data
.upload
['loaded'] ),
398 formatSize( data
.upload
['content_length'] )
402 }else if( data
.upload
['loaded'] ){
403 _this
.updateProgress( 1 );
404 js_log('just have loaded (no cotent length: ' + data
.upload
['loaded']);
405 //for lack of content-length requests:
406 $j('#up-status-container').html(
407 gM('upload-stats-fileprogres', [
408 formatSize( data
.upload
['loaded'] ),
409 gM('upload-unknown-size')
414 //(we got a result) set it to 100ms + your server update interval (in our case 2s)
415 setTimeout(uploadStatus
, 2100);
420 apiUpdateErrorCheck:function( apiRes
){
422 if( apiRes
.error
|| ( apiRes
.upload
&& apiRes
.upload
.result
== "Failure" ) ){
423 //gennerate the error button:
425 bObj
[ gM('return-to-form') ] = function(){
426 _this
.form_post_override
= false;
427 $j(this).dialog('close');
430 //@@TODO should be refactored to more specialUpload page type error handling
432 //check a few places for the error code:
434 var errorReplaceArg
='';
435 if( apiRes
.error
&& apiRes
.error
.code
){
436 error_code
= apiRes
.error
.code
;
437 }else if( apiRes
.upload
.code
){
438 if(typeof apiRes
.upload
.code
== 'object'){
439 if(apiRes
.upload
.code
[0]){
440 error_code
= apiRes
.upload
.code
[0];
442 if(apiRes
.upload
.code
['status']){
443 error_code
= apiRes
.upload
.code
['status'];
444 if(apiRes
.upload
.code
['filtered'])
445 errorReplaceArg
=apiRes
.upload
.code
['filtered'];
453 if(typeof apiRes
.error
== 'string')
454 error_msg
= apiRes
.error
;
455 //error space is too large so we don't front load it
456 //this upload error space replicates code in: SpecialUpload.php::processUpload()
457 //would be nice if we refactored that to the upload api.(problem is some need special actions)
458 var error_msg_key
= {
459 '2' : 'largefileserver',
462 '5' : 'illegalfilename'
465 //@@todo: need to write conditionals that mirror SpecialUpload for handling these error types:
466 var error_onlykey
= {
467 '1': 'BEFORE_PROCESSING',
468 '6': 'PROTECTED_PAGE',
469 '7': 'OVERWRITE_EXISTING_FILE',
470 '8': 'FILETYPE_MISSING',
471 '9': 'FILETYPE_BADTYPE',
472 '10': 'VERIFICATION_ERROR',
473 '11': 'UPLOAD_VERIFICATION_ERROR',
474 '12': 'UPLOAD_WARNING',
475 '13': 'INTERNAL_ERROR',
476 '14': 'MIN_LENGHT_PARTNAME'
479 //do a remote call to get the error msg:
480 if(!error_code
|| error_code
== 'unknown-error'){
481 if(typeof JSON
!= 'undefined'){
482 js_log('Error: apiRes: ' + JSON
.stringify( apiRes
) );
484 if( apiRes
.upload
.error
== 'internal-error'){
485 errorKey
= apiRes
.upload
.details
[0];
486 gMsgLoadRemote(errorKey
, function(){
487 _this
.updateProgressWin( gM( 'uploaderror' ), gM( errorKey
), bObj
);
493 _this
.updateProgressWin( gM('uploaderror'), gM('unknown-error') + '<br>' + error_msg
, bObj
);
496 if(apiRes
.error
&& apiRes
.error
.info
){
497 _this
.updateProgressWin( gM('uploaderror'), apiRes
.error
.info
,bObj
);
500 if(typeof error_code
== 'number' && typeof error_msg_key
[error_code
] == 'undefined' ){
501 if(apiRes
.upload
.code
.finalExt
){
502 _this
.updateProgressWin( gM('uploaderror'), gM('wgfogg_waring_bad_extension', apiRes
.upload
.code
.finalExt
) , bObj
);
504 _this
.updateProgressWin( gM('uploaderror'), gM('unknown-error') + ' : ' + error_code
, bObj
);
507 js_log('get key: ' + error_msg_key
[ error_code
])
508 gMsgLoadRemote( error_msg_key
[ error_code
], function(){
509 _this
.updateProgressWin( gM('uploaderror'), gM( error_msg_key
[ error_code
], errorReplaceArg
), bObj
);
517 //check for upload.error type erros.
518 if( apiRes
.upload
&& apiRes
.upload
.error
){
519 js_log(' apiRes.upload.error: ' + apiRes
.upload
.error
);
520 _this
.updateProgressWin( gM('uploaderror'), gM('unknown-error') + '<br>', bObj
);
523 //check for known warnings:
524 if(apiRes
.upload
&& apiRes
.upload
.warnings
){
527 for(var wtype
in apiRes
.upload
.warnings
){
528 var winfo
= apiRes
.upload
.warnings
[wtype
]
533 if(winfo
[1] && winfo
[1].title
&& winfo
[1].title
.mTextform
){
534 wmsg
+= gM('file-exists-duplicate') +' '+
535 '<b>' + winfo
[1].title
.mTextform
+ '</b>';
537 //misc error (weird that winfo[1] not present
538 wmsg
+= gM('upload-misc-error') + ' ' + wtype
;
541 case 'file-thumbnail-no':
542 wmsg
+= gM('file-thumbnail-no', winfo
);
545 wmsg
+= gM('upload-misc-error') + ' ' + wtype
;
551 if( apiRes
.upload
.warnings
.sessionkey
)
552 _this
.warnings_sessionkey
= apiRes
.upload
.warnings
.sessionkey
;
554 bObj
[ gM('ignorewarning') ] = function() {
555 //re-inciate the upload proccess
556 $j('#wpIgnoreWarning').attr('checked', true);
557 $j( '#mw-upload-form' ).submit();
559 bObj
[ gM('return-to-form') ] = function(){
560 $j(this).dialog('close');
561 _this
.form_post_override
= false;
563 _this
.updateProgressWin( gM('uploadwarning'), '<h3>' + gM('uploadwarning') + '</h3>' +wmsg
+ '<p>',bObj
);
569 processApiResult: function( apiRes
){
571 js_log('processApiResult::');
572 //check for upload api error:
573 // {"upload":{"result":"Failure","error":"unknown-error","code":{"status":5,"filtered":"NGC2207%2BIC2163.jpg"}}}
574 if( _this
.apiUpdateErrorCheck(apiRes
) === false){
575 //error returned false (updated and
578 //check for upload_session key for async upload:
579 if( apiRes
.upload
&& apiRes
.upload
.upload_session_key
){
580 //set the session key
581 _this
.upload_session_key
= apiRes
.upload
.upload_session_key
;
583 //do ajax upload status:
584 _this
.doAjaxUploadStatus();
585 js_log("set upload_session_key: " + _this
.upload_session_key
);
589 if( apiRes
.upload
.imageinfo
&& apiRes
.upload
.imageinfo
.descriptionurl
){
590 var url
= apiRes
.upload
.imageinfo
.descriptionurl
;
592 if( _this
.done_upload_cb
&& typeof _this
.done_upload_cb
== 'function'){
594 $j('#upProgressDialog').dialog('close');
596 _this
.done_upload_cb( url
);
599 bObj
[ gM('return-to-form')] = function(){
600 $j(this).dialog('close');
601 _this
.form_post_override
= false;
603 bObj
[ gM('go-to-resource') ] = function(){
604 window
.location
= url
;
606 _this
.action_done
= true;
607 _this
.updateProgressWin( gM('successfulupload'), gM( 'mv_upload_done', url
), bObj
);
608 js_log('apiRes.upload.imageinfo::'+url
);
614 updateProgressWin:function(title_txt
, msg
, buttons
){
617 title_txt
= _this
.getProgressTitle();
619 msg
= mv_get_loading_img( 'left:40%;top:40px;');
620 $j( '#upProgressDialog' ).dialog('option', 'title', title_txt
);
621 $j( '#upProgressDialog' ).html( msg
);
623 $j('#upProgressDialog').dialog('option','buttons', buttons
);
625 //@@todo should convice the jquery ui people to not use object keys as user msg's
627 bObj
[ gM('ok-button') ] = function(){
628 $j(this).dialog('close');
630 $j('#upProgressDialog').dialog('option','buttons', bObj
);
633 getProgressTitle:function(){
634 return gM('upload-in-progress');
636 getEditForm:function(){
637 if( this.target_edit_from
&& $j( this.target_edit_from
).length
!= 0){
638 return $j( this.target_edit_from
).get(0);
640 //just return the first form fond on the page.
641 return $j('form :first').get(0);
643 updateProgress:function( perc
){
644 //js_log('update progress: ' + perc);
645 $j( '#up-progressbar' ).progressbar('value', parseInt( perc
* 100 ) );
646 $j( '#up-pstatus' ).html( parseInt( perc
* 100 ) + '% - ' );
648 /*update to jQuery.ui progress display type */
649 dispProgressOverlay:function(){
651 //remove old instance:
652 if($j('#upProgressDialog').length
!=0){
653 $j('#upProgressDialog').dialog( 'destroy' ).remove();
656 $j('body').append('<div id="upProgressDialog" ></div>');
658 $j('#upProgressDialog').dialog({
659 title
:_this
.getProgressTitle(),
664 beforeclose: function(event
, ui
) {
665 if( event
.button
==0 && _this
.action_done
=== false){
666 return _this
.cancel_action();
668 //click on button (dont do close action);
672 buttons
: _this
.cancel_button()
674 $j('#upProgressDialog').html(
675 //set initial content:
676 '<div id="up-pbar-container" style="width:90%;height:15px;" >' +
677 '<div id="up-progressbar" style="height:15px;"></div>' +
678 '<div id="up-status-container">'+
679 '<span id="up-pstatus">0% - </span> ' +
680 '<span id="up-status-state">' + gM('uploaded-status') + '</span> ' +
684 //setup progress bar:
685 $j('#up-progressbar').progressbar({
688 //just display an empty progress window
689 $j('#upProgressDialog').dialog('open');
692 cancel_button:function(){
694 var cancelBtn
= new Array();
695 cancelBtn
[ gM('cancel-button') ] = function(){
696 return _this
.cancel_action(this)
700 cancel_action : function( dlElm
){
702 if( confirm( gM('mv-cancel-confim') )){
703 //@@todo (cancel the encode / upload)
704 $j(this).dialog('close');