MediaWiki:UploadInPage/code.js

/* * @author User:Clear Arrow * @version 0.8.2 (beta) * @type object * Upload files using api by User:Gguigui1 * Features: oasis: 20% (100%), monobook: 100% * Allows to upload files using ajax while editing a page (this function is already in oasis) * Prevents to upload a file without a license (disabled by default) */

window.UploadFile = (function ($, mw) {	var _datalang = {		en: {			updone: "You uploaded the file: ",			duplicate: 'This image is a doublon ',			upcopy: "Copy",			modaltitle: "Upload File",			closemodal: "Close",			defaultOpt: "None selected",			browser: "Please, update your browser!",			desc: "Description: ",			problem: "A problem occured, upload cancelled",			updateform: "Update form",			nolicenses: "We couldn't find the licenses, please see MediaWiki:Licenses",			alreadyname: "There is already a file named like that, please choose another name ",			error: "Error",			imagename: "Image",			licensetext: 'License: ',			uploadfiles: 'Upload all images',			nofile: "You have to choose a file to upload it",			filenamespace: "File:",			licensetitle: "License",			licenseerror: "You need to put a license",			allfiles: "Files uploaded",			filedescription: 'File description',			filename: "Name: ", deleted: "This file was deleted before, are you sure you want to reupload it?" },		es: { updone: "Has subido el archivo: ", duplicate: 'Este archivo es duplicado', upcopy: "Copiar", modaltitle: "Subir Archivo", closemodal: "Cerrar", defaultOpt: 'Ninguna seleccionada', browser: "Por favor, ¡actualiza tu navegador!", desc: "Descripción: ", problem: "Ha ocurrido un problema, subida cancelada", updateform: "Actualizar formulario", nolicenses: "No pudimos encontrar las licencias, por favor revisa MediaWiki:Licenses", alreadyname: "Ya hay un archivo con ese nombre, por favor selecciona otro ", error: "Error", imagename: "Imagen", licensetext: 'Licencia: ', uploadfiles: 'Subir los archivos', nofile: "Tienes que seleccionar un archivo para subirlo", filenamespace: "Archivo:", licensetitle: "Licencia", licenseerror: "Tienes que poner una licencia", allfiles: "Archivos subidos", filedescription: 'Descripción del archivo', filename: "Nombre: ", deleted: "Este archivo fue borrado anteriormente, ¿seguro que quieres resubirlo?" }	},	// Depends on User Language, if it's not here, will be "en" _i18n = $.extend(_datalang['en'], _datalang[(mw.config.get('wgUserLanguage')).split("-")[0]], _datalang[(mw.config.get('wgUserLanguage'))]), _addComment = window.UFdescription || true, // Enabled by default _noLicense = window.needsLicense || false, // Disabled by default _allowMultiUpload = window.allowMultiUpload || true, // Enabled by default _maxFiles = window.maxFiles || 100, // Max files to upload at once _ignoreWarnings = window.ignoreWarnings || 0, // Disabled by default - personal use _showDetails = window.uploadDetails || true, // Enabled by default _useMono = window.UploadFileOasis || false, // Disabled by default - personal use (maybe) _licensesList = function { // Make the list of licenses $.ajax({			type: 'GET',			url: '/api.php?action=query&meta=allmessages&ammessages=Licenses&format=json',			success: function (datos) {				_throwLicenses(datos.query.allmessages[0]['*']);			},			error: function (datos) {				alert(_i18n['nolicenses']);			}		}); },	_throwLicenses = function(lista) { // Make the container of the licenses if (lista != null) { var options = lista.split('\n'); if (options[options.length - 1] == '') { options.splice(-1, 1); }			$('.licencias').replaceWith(' '); $('.licencias').prepend(' ' + _i18n['defaultOpt'] + ' '); for (var i in options) { if (options[i].indexOf('**') == 0) { options[i] = options[i].replace('**', ''); $('.licencias').find('optgroup:last-child').append('' + options[i].split('|')[1] + ' '); }				else { options[i] = options[i].replace('*', ''); $('.licencias').append(' '); }			}		}	}, // This modal contains the form to upload, similar to oasis' form _showModal = function { $.showCustomModal(_i18n['modaltitle'], '  ' + _i18n['updateform'] + ' ', {			id: 'UploadFile',			width: 700,			height: 560,			buttons: [{				defaultButton: true,				id: "CloseModal",				message: _i18n['closemodal'],				handler: function {					$('#UploadFile').closeModal;				}			}]		}); $('#UFdone').on('click', function {			_update;		}) if (_allowMultiUpload) { $('#fileinput').attr('multiple', ''); }	},	_uploadFiles = function(fileToUpload, fileName, license) { // This function is the most important because it uploads the file var lFileName = fileName;

// Create the data var formdata = new FormData; formdata.append('action', 'upload'); formdata.append('filename', lFileName); formdata.append('token', mw.user.tokens.get('editToken')); formdata.append('file', fileToUpload); formdata.append('text', license); formdata.append('format', 'json'); if (_ignoreWarnings == false || _ignoreWarnings == 0) { _ignoreWarnings = 0; }		else { _ignoreWarnings = 1; formdata.append('ignorewarnings', _ignoreWarnings); }		// Send the data $.ajax({			url: mw.util.wikiScript('api'),			contentType: false,			processData: false,			type: "POST",			data: formdata,			dataType: 'json',			async: false,			success: function (data) {				console.log(data.upload.result);				console.log(data.upload.warnings);				if (data.upload.result == 'Warning') {					if (data.upload.warnings.hasOwnProperty('was-deleted')) {						var reUpload = confirm(_i18n['deleted']);						if (reUpload) {							_ignoreWarnings = 1;							lFileName = _uploadFiles(fileToUpload, lFileName, license);						}						else {							console.log(_i18n["error"]);						}					}					else if (data.upload.warnings.hasOwnProperty('duplicate-archive')) { // Change the name to the existing file						alert(_i18n['duplicate']);					}					else if (data.upload.warnings.hasOwnProperty('exists')) {						lFileName = prompt(_i18n['alreadyname'], lFileName);						if (lFileName != null) {							lFileName = _uploadFiles(fileToUpload, lFileName, license); }						else { alert(_i18n['error']); }					}				}				else { console.log(_i18n['updone']); var insertFiles =  + _i18n['filenamespace'] + lFileName + ; _insertAtCaret('wpTextbox1', insertFiles); }			},			error: function (xhr, status, err) { alert(err); }		});	},	_insertAtCaret = function(areaId, text) { // Function to insert the uploaded files in the page		var txtarea = document.getElementById(areaId);		if (!txtarea) { return; }		var scrollPos = txtarea.scrollTop;		var strPos = 0;		var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );		if (br == "ie") {			txtarea.focus;			var range = document.selection.createRange;			range.moveStart ('character', -txtarea.value.length);			strPos = range.text.length;		}		else if (br == "ff") {			strPos = txtarea.selectionStart;		}		var front = (txtarea.value).substring(0, strPos);		var back = (txtarea.value).substring(strPos, txtarea.value.length);		txtarea.value = front + text + back;		strPos = strPos + text.length;		if (br == "ie") {			txtarea.focus;			var ieRange = document.selection.createRange;			ieRange.moveStart ('character', - txtarea.value.length);			ieRange.moveStart ('character', strPos);			ieRange.moveEnd ('character', 0);			ieRange.select;		} 		else if (br == "ff") {			txtarea.selectionStart = strPos;			txtarea.selectionEnd = strPos;			txtarea.focus;		}

txtarea.scrollTop = scrollPos; },	_fileSelect = function { var input = document.getElementById('fileinput'), license; if (!input.files) { alert(_i18n['browser']); $('#fileinput').attr("disabled", false); }		else if (!input.files[0]) { alert(_i18n["problem"]); $('#fileinput').attr("disabled", false); }		else { var numberfiles = $('#UploadFile fieldset').length - 1; var file, filename; if (numberfiles > 0) { for (var i = 0; i < numberfiles; i++) { file = input.files[i]; filename = $('.imagename').eq(i).val || input.files[i].name; if ($('#UploadContainer').find('select:eq(' + i + ')').find('option:selected').val != "none") { license = '==' + _i18n['licensetitle'] + '==\n' + '\n' + $('#UploadDescription').val; }					else if ($('#UploadContainer').find('select:eq(' + i + ')').find('option:selected').val == "none" && _noLicense == false) { license = $('#UploadDescription').val; }					else { alert(_i18n['licenseerror']); return false; }					$('#loading' + (i + 1)).css('display', 'initial'); _uploadFiles(file, filename, license); }				$('#UploadFile').closeModal; alert(_i18n['allfiles']); }		}	},	_update = function { if ($('#UploadFile fieldset').length > 0) { _fileSelect; return false; }		$('#editor').show; $('#fileinput').attr("disabled", true); var input = document.getElementById('fileinput'); $('#editor').html(''); if (input.files.length == 0) { alert(_i18n['nofile']); return false; }		var limit; if (_maxFiles < input.files.length) { limit = _maxFiles; }		else { limit = input.files.length; }		for (var i = 0; i < limit; i++) { $('#editor').append(' ' + _i18n["imagename"] + ' ' + (i + 1) + ' ' + _i18n["filename"] + '    ' + _i18n["licensetext"] + ' '); }		_licensesList; $('#editor').append(' ' + _i18n["filedescription"] + '  '); $('#UFdone').html(_i18n['uploadFiles']); }, // Oasis. _needsLicense = function { // Note: the visual editor auto-selects a license, so isn't necessary to something there var _timer = setInterval(function {			try {				if (_showDetails) {					$('#WMU_div .advanced').css('display', 'block');				}				if ($('#ImageUploadLicenseSpan').find('select').val == '') {					$('#ImageUploadDetails input[type="submit"]').prop('disabled', true);				}				else {					$('#ImageUploadDetails input[type="submit"]').prop('disabled', false);				}				if ($('#ImageUploadDetails') && $('#infoLicences').length < 1) {					$('.modalWrapper .ImageUploadLeft').append(' ' + _i18n["licenseerror"] + ' ');				}			}			catch (err) {				console.warn('This is not an error lol (?)');			}		}, 500); },	_init = function { importStylesheetPage('MediaWiki:UploadOnPage/code.css', 'dev'); if ({ edit:1, submit:1 }[mw.config.get('wgAction')] && mw.config.get('skin') != 'oasis') { mw.loader.using('mediawiki.action.edit', function {				if (mw.toolbar) {					mw.toolbar.addButton( 'https://vignette.wikia.nocookie.net/kirby/images/4/4a/A%C3%B1adirImagen.png/revision/latest?cb=20171020011105&format=original', 'UploadFile', '', // This is useless, but in case the rest of the script doesn't work ,						,						'mw-editbutton-addfile' );				}			});		}		else if ({ edit:1, submit:1 }[mw.config.get('wgAction')] && mw.config.get('skin') == 'oasis' && _noLicense) { WikiaEditor.load("WikiaMiniUpload").done(function {				$(_needsLicense);			}); }		// This is if someone wants to use the window.UploadFile form instead of FANDOM's (the advantages are that you can upload many files at once) if (_useMono && mw.config.get('skin') == 'oasis') { if ({ edit:1, submit:1 }[mw.config.get('wgAction')]) { mw.loader.using('mediawiki.action.edit', function {					if (mw.toolbar) {						mw.toolbar.addButton( 'https://vignette.wikia.nocookie.net/kirby/images/4/4a/A%C3%B1adirImagen.png/revision/latest?cb=20171020011105&format=original', 'UploadFile', '', // This is useless, but in case the rest of the script doesn't work ,							,							'mw-editbutton-addfile' );						$('#mw-editbutton-wmu').remove;					}				}); }		}		$('#mw-editbutton-addfile').on('click', function (event) {			event.preventDefault;			_showModal;		}); };

// Public functions return { uploadFiles: _uploadFiles, throwLicenses: _throwLicenses, licensesList: _licensesList, insertAtCaret: _insertAtCaret, // If someone wants to use this init: _init, update: _update, fileSelect: _fileSelect };

})(jQuery, mw);

(typeof (window.jQuery) == 'function' ? jQuery : addOnloadHook)(window.UploadFile.init);

//