User:Yellowcard/datadrainer.js

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/**********************************************************************************
***********************************************************************************
**                _       _        _____            _                            **
**               | |     | |      |  __ \          (_)                           **
**             __| | __ _| |_ __ _| |  | |_ __ __ _ _ _ __   ___ _ __            **
**            / _` |/ _` | __/ _` | |  | | '__/ _` | | '_ \ / _ \ '__|           **
**           | (_| | (_| | || (_| | |__| | | | (_| | | | | |  __/ |              **
**            \__,_|\__,_|\__\__,_|_____/|_|  \__,_|_|_| |_|\___|_|    v1.0      **
**                                                                               **
** ----------------------------------------------------------------------------- **
**  How to use:                                                                  **
**   Add to your common.js [[Special:MyPage/common.js]],                         **
**   importScript( 'User:Jitrixis/dataDrainer.js' );                             **
**                                                                               **
**  Links:                                                                       **
**    [[User:Jitrixis/dataDrainer.js]]                                           **
**    [[User talk:Jitrixis/dataDrainer.js]]                                      **
**    [[Wikidata:Tools#User:Jitrixis.2FdataDrainer.js]]                          **
**                                                                               **
**  Read me:                                                                     **
**   -This tool allows you to delete the data of an item.                        **
**   -You can choose what you want to delete: labels and/or descriptions and/or  **
**    aliases and or sitelinks                                                   **
**   -When you have chosen your options type the verification code to prevent    **
**    vandalism then click on the "Empty" button.                                **
**   -If you have checked the sitelinks option a dialog ask you if you're really **
**    sure to delete all sitelinks because they can only be once on Wikidata.    **
**   -Then a checklist will show you again the selected options.                 **
**   -Finally a prompt ask you the reason of this deletion.                      **
**                                                                               **
**  Permissions:                                                                 **
**   +----------------------------------------------------------------------+    **
**   |     Groups     |  Labels  |  Descriptions  |  Aliases  |  Sitelinks  |    **
**   +----------------+----------+----------------+-----------+-------------+    **
**   |  sysop         |    OK    |       OK       |    OK     |     OK      |    **
**   |  autopatrolled |    OK    |       OK       |    OK     |     XX      |    **
**   |  user          |    XX    |       XX       |    XX     |     XX      |    **
**   +----------------------------------------------------------------------+    **
**                                                                               **
***********************************************************************************
**********************************************************************************/

( function ( mw, $ ) {
	/*
	**Return item Number.
	*/
	var itemId = mw.config.get( 'wbEntityId' );
 	if( !itemId ) {
		return;
	}
 
	/*
	**Localized message.
	*/
	var transData = {
		'en': {
			'box-title': 'Empty',
			'box-cancel': 'Close',
			'box-deleted': 'Deleted',
			'canceled': 'Deletion canceled',
			'box-captcha': 'Enter the number for emptying:',
			'warning-message': 'Attention! You will fully drain this item. Only administrators and autopatrollers can use this feature. Please check and verify what you want to clear. A verification code is requested to run the script.',
			'labels': 'Labels',
			'descriptions': 'Descriptions',
			'aliases': 'Aliases',
			'sitelinks': 'Sitelinks',
			'unauthorized': 'You\'re not authorized to use this script!',
			'locked-option': 'This option is locked. Ask an administrator!',
			'captcha-wrong': 'The security code is incorrect!',
			'nothing-check': 'There is nothing to do!',
			'sitelinks-check': 'Are you sure you want to delete all sitelinks?',
			'checklist': 'This deletion list will be executed',
			'reason': 'Write here the reason why you want to drain this item:',
			// DO NOT TRANSLATE. ///// If your reading direction is left to right, /////
 			// if not translate by ('floatRight': 'left','floatLeft': 'right') /////////
			'floatRight': 'right', 
			'floatLeft': 'left'
			// DO NOT TRANSLATE. ///////////////////////////////////////////////////////
		},
                'ca': {
			'box-title': 'Buida',
			'box-cancel': 'Tanca',
			'box-deleted': 'Buidat',
			'canceled': 'Supressió anul·lada',
			'box-captcha': 'Introduïu el número per buidar:',
			'warning-message': 'Atenció! Aneu a buidar aquest element. Només els administradors i els patrullers poden utilitzar aquesta funcionalitat. Verifiqueu i seleccioneu el que voleu buidar. Es demana un codi de verificació a fi d\'executar la seqüència.',
			'labels': 'Etiqueta',
			'descriptions': 'Descripcions',
			'aliases': 'Àlies',
			'sitelinks': 'Enllaços',
			'unauthorized': 'No esteu autoritzats fer servir aquesta seqüència!',
			'locked-option': 'Aquesta opció està blocada. Demaneu a un administrador!',
			'captcha-wrong': 'El codi de seguretat no està correcte!',
			'nothing-check': 'No hi ha cap acció marcada!',
			'sitelinks-check': 'Esteu segur voler suprimir tots els enllaços?',
			'checklist': 'Va executar-se aquesta llista de supressió!',
			'reason': 'Introduïu aquí la raó per la qual voleu buidar aquest element:'
		},
                'fi': {
			'box-title': 'Tyhjennä',
			'box-cancel': 'Sulje',
			'box-deleted': 'Poistettu',
			'canceled': 'Poistaminen peruutettu',
			'box-captcha': 'Syötä numero tyhjentääksesi:',
			'warning-message': 'Huomautus! Olet tyhjentämässä tätä kohdetta. Vain ylläpitäjät ja automaattisesti tarkastavat voivat käyttää tätä toimintoa. Tarkista ja valitse mitä haluat tyhjentää. Ennen tyhjentämistä sinulta kysytään varmistuskoodia.',
			'labels': 'Nimet',
			'descriptions': 'Kuvaukset',
			'aliases': 'Aliakset',
			'sitelinks': 'Sivulinkit',
			'unauthorized': 'Sinulla ei ole oikeutta käyttää tätä työkalua!',
			'locked-option': 'Tämä valinta on lukittu. Kysy ylläpitäjää!',
			'captcha-wrong': 'Varmistuskoodi on virheellinen!',
			'nothing-check': 'Mitään ei tehty!',
			'sitelinks-check': 'Oletko varma että haluat poistaa kaikki sivulinkit?',
			'checklist': 'Nämä poistot toteutetaan.',
			'reason': 'Kirjoita tähän syy miksi haluat tyhjentää kohteen:',
		},
                'fr': {
			'box-title': 'Vider',
			'box-cancel': 'Fermer',
			'box-deleted': 'Vidé',
			'canceled': 'Suppression annulée',
			'box-captcha': 'Entrer le numéro pour vider :',
			'warning-message': 'Attention! Vous allez entièrement vider cet item. Seul les administrateurs et les patrouilleurs peuvent utiliser cette fonctionnalité. Veuillez vérifier et cocher ce que vous voulez vider. Un code de vérification est demandé pour exécuter le script.',
			'labels': 'Labels',
			'descriptions': 'Descriptions',
			'aliases': 'Alias',
			'sitelinks': 'Liens',
			'unauthorized': 'Vous n\'êtes pas autorisé à utiliser ce script !',
			'locked-option': 'Cette option est verrouillée. Demander à un administrateur !',
			'captcha-wrong': 'Le code de sécurité saisi n\'est pas le bon!',
			'nothing-check': 'Il n\'y a aucune action de cochée !',
			'sitelinks-check': 'Êtes-vous sûr de vouloir supprimer tous les liens ?',
			'checklist': 'Cette liste de suppression va être exécutée !',
			'reason': 'Écrivez ici la raison pour laquelle vous voulez vider cet item :'
		}
	};
	
	function group(){
		if(true){return "sysop";}
		else if(mw.config.get( 'wgUserGroups' ).indexOf("autopatrolled") != -1){return "patroller";}
		else {return "";}
	}
	
	function booleanI18N( bool ){
		if(bool){
		return "OK" ;
		} else {
		return "XX" ;
		}
	}
 
	/*
	**Check if main language can be translated.
	*/
	var lang = mw.user.options.get( 'language' );
	if( !inArray( lang, ['en', 'fr'] ) ) {
		lang = 'en';
	}
 
	/*
	**Return if the array conain the value.
	*/
	function inArray( value, array ) {
		var contains = false;	
		for (var i = 0; i < array.length; i++) {
			contains = array[i] == value;
			if(contains) {
				break;
			}
		}
		return contains;
	}
 
	/*
	**Return localized message.
	*/
	function translate( key ) {
		if( transData[ lang ][ key ] ) {
			return transData[ lang ][ key ];
		} else {
			return transData[ 'en' ][ key ];
		}
	}
	
	/*
	** Dialog
	*/

	var code;
	var formFind;
	function dataDrainer() {
			mw.loader.using( ['jquery.ui'], function() {
				var disable = "" ; var label = "" ; 
				var disable2 = "" ; var label2 = "" ; 
				formFind = '<div style="font-size:0.85em;text-align:justify;text-justify:inter-word;"><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>' + translate( 'warning-message' ) + '<div><br/><table style="width:100%"><tr><td style="width:50%">';
				formFind += '<input type="checkbox" id="drain-labels" ' + disable + '/><label for="drain-labels" id="tipsy1" ' + label + '> ' + translate( 'labels' ) + '</label><br/>';
				formFind += '<input type="checkbox" id="drain-descriptions" ' + disable + '/><label for="drain-descriptions" id="tipsy2" ' + label + '>' + translate( 'descriptions' ) + '</label><br/>';
				formFind += '<input type="checkbox" id="drain-aliases" ' + disable + '/><label for="drain-aliases" id="tipsy3" ' + label + '>' + translate( 'aliases' ) + '</label><br/>';
				formFind += '<input style="border-color:red" type="checkbox" id="drain-sitelinks" ' + disable2 + '/><label for="drain-sitelinks" id="tipsy4" style="color:red" ' + label2 + '>' + translate( 'sitelinks' ) + '</label>';
				formFind += '</td><td><div style="width:100%;font-size:1em;text-align:center">' + translate( 'box-captcha' ) + '</div><div onselect="return false" oncontextmenu="return false" style="width:100%;font-size:2em;text-align:center;user-select: none;-khtml-user-select: none;-o-user-select: none;user-select: none;-moz-user-select: -moz-none;-webkit-user-select: none;-webkit-touch-callout: none;-ms-user-select: none;font-family:"Lucida Console", Monaco, monospace"><strong><span id="captcha-code">#ERROR#</span></strong></div><input type="text" id="drain-captcha" style="width:100%" ' + disable + ' id="tipsy5" ' + label + '/></td></tr></table>';
				displayFind = '<div id="dataDrainer" title="" style="background:black;color:white">' + formFind + '</div>';
				if(document.getElementById("content")) {
					var messageFind = $( displayFind ).appendTo( '#content' );
				} else {
					var messageFind = $( displayFind ).appendTo( '#mw_content' );
				}
				messageFind.dialog({
					title: '<span style="background:white;padding:2px 5px 2px 5px">' + translate( 'box-title' ) + '</span>',
					autoOpen: false,
					width: 300,
					//height: 270,
                                        show: "blind",
                                        hide: "blind",
                                        draggable: false,
                                        resizable: false,
                                        position: { my: "right top", at: "right top", of: "#bodyContent" },
					buttons: [ {
						text: translate( 'box-title' ),
						click: function() {
							if(true || mw.config.get( 'wgUserGroups' ).indexOf("autopatrolled") != -1){
								run();
							}else{
								mw.notify( translate( 'unauthorized' ), { title: 'dataDrainer.js :', tag: 'datadrainer' } );
							}
						}
					},{
						text: translate( 'box-cancel' ),
						click: function() {
							$( this ).dialog( "close" );
							$( '#dataDrainer' ).empty();
							$( formFind ).appendTo( '#dataDrainer' );
						}
					} ],
					open: function () {
						$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").css('cssText', 'background: url("//upload.wikimedia.org/wikipedia/commons/2/2b/Caution_background.png") !important');
						$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").find(".ui-dialog-titlebar-close").css('cssText', 'background: none repeat scroll 0 0 white');
						$(this).parents(".ui-dialog:first").find(".ui-dialog-buttonpane").css('cssText', 'background: url("//upload.wikimedia.org/wikipedia/commons/2/2b/Caution_background.png") !important');
						code = 100000 + Math.floor(Math.random() * (999999-100000) + 0.5);
						$('#captcha-code').empty();
						$( code ).appendTo( '#captcha-code' );
					}
				} );
				mw.loader.using( 'jquery.tipsy', function () {$('#tipsy1').tipsy({gravity: 'e',fade: true,delayIn: 50});});
				mw.loader.using( 'jquery.tipsy', function () {$('#tipsy2').tipsy({gravity: 'e',fade: true,delayIn: 50});});
				mw.loader.using( 'jquery.tipsy', function () {$('#tipsy3').tipsy({gravity: 'e',fade: true,delayIn: 50});});
				mw.loader.using( 'jquery.tipsy', function () {$('#tipsy4').tipsy({gravity: 'e',fade: true,delayIn: 50});});
				mw.loader.using( 'jquery.tipsy', function () {$('#tipsy5').tipsy({gravity: 'n',fade: true,delayIn: 50});});
				var portletLink = mw.util.addPortletLink( 'p-cactions', '#', translate( 'box-title' ), 't-dataDrainer', translate( 'box-title' ) );
				$(portletLink).click( function() {
					$( 'div#dataDrainer' ).dialog( 'open' );
				} );
			} );
	}

	
	/*
	** Action when submitted
	*/
	
	function run () {
		if(true){
			if(document.getElementById("captcha-code").innerHTML == document.getElementById("drain-captcha").value){
				var labels = document.getElementById("drain-labels").checked;
				var descriptions = document.getElementById("drain-descriptions").checked;
				var aliases = document.getElementById("drain-aliases").checked;
				var sitelinks = document.getElementById("drain-sitelinks").checked;
				if( false ){
					mw.notify( translate( 'locked-option' ), { title: 'dataDrainer.js :', tag: 'datadrainer' } );
				}else{
					if((labels + descriptions + aliases + sitelinks) == 0){
						mw.notify( translate( 'nothing-check' ), { title: 'dataDrainer.js :', tag: 'datadrainer' } );
					}else{
						if(sitelinks){
							if(!confirm(translate( 'sitelinks-check' ))){
								sitelinks = false;
								document.getElementById("drain-sitelinks").checked = false;
							}
						}
						if(!confirm(translate( 'checklist' ) + "\n\n" + translate( 'labels' ) + " : \t\t" + booleanI18N(labels) + "\n" + translate( 'descriptions' ) + " : \t" + booleanI18N(descriptions) + "\n" + translate( 'aliases' ) + " : \t\t" + booleanI18N(aliases) + "\n" + translate( 'sitelinks' ) + " : \t\t" + booleanI18N(sitelinks))){
							mw.notify( translate( 'canceled' ), { title: 'dataDrainer.js :', tag: 'datadrainer' } );
							code = 100000 + Math.floor(Math.random() * (999999-100000) + 0.5);
							$('#captcha-code').empty();
								$( code ).appendTo( '#captcha-code' );
							document.getElementById("drain-captcha").value = "";
							document.getElementById("drain-labels").checked = false;
							document.getElementById("drain-descriptions").checked = false;
							document.getElementById("drain-aliases").checked = false;
							document.getElementById("drain-sitelinks").checked = false;
						}else{
							getValue(labels, descriptions, aliases, sitelinks);
						}
					}
				}
			}else{
				mw.notify( translate( 'captcha-wrong' ), { title: 'dataDrainer.js :', tag: 'datadrainer' } );
				code = 100000 + Math.floor(Math.random() * (999999-100000) + 0.5);
				$('#captcha-code').empty();
				$( code ).appendTo( '#captcha-code' );
				document.getElementById("drain-captcha").value = "";
				document.getElementById("drain-labels").checked = false;
				document.getElementById("drain-descriptions").checked = false;
				document.getElementById("drain-aliases").checked = false;
				document.getElementById("drain-sitelinks").checked = false;
			}
		}else{
			mw.notify( translate( 'unauthorized' ), { title: 'dataDrainer.js :', tag: 'datadrainer' } );
		}
	}
	
	/*
	** Get current Value
	*/
	
	function getValue(labels, descriptions, aliases, sitelinks) {
		$.ajax({
  			url: mw.util.wikiScript( 'api' ),
			data: {
				'format': 'json',
				'action': 'wbgetentities',
				'ids': itemId,
				'props': 'labels|descriptions|sitelinks|aliases'
			},
			success: function( data ) {
				var emlabels = {};
				var emdescriptions = {};
				var emaliases = [];
				var emsitelinks = {};
				for (var id in data.entities[itemId].sitelinks) {
					emsitelinks[id] = "";
				}
				for (var id in data.entities[itemId].labels) {
					emlabels[id] = "";
				}
				for (var id in data.entities[itemId].descriptions) {
					emdescriptions[id] = "";
				}
				for (var id in data.entities[itemId].aliases) {
					for (var nb in data.entities[itemId].aliases[id]) {
						var jsonArray = {};
						jsonArray = {
							"language": id,
							"value": data.entities[itemId].aliases[id][nb].value,
							"remove": "",
						};
						emaliases.push(jsonArray);
					}
				}
				drain(labels, descriptions, aliases, sitelinks, emsitelinks, emlabels, emdescriptions, emaliases);
			},
			error: function() {
				mw.notify( 'API Error', { title: 'dataDrainer.js :', tag: 'datadrainer' } );
				onError();
			}
		});
	}
		
	
	/*
	** Prepare Deleted json format
	*/
	
	function drain(labels, descriptions, aliases, sitelinks, emsitelinks, emlabels, emdescriptions, emaliases){
		var sommaire = "";
		var jsonLabel = [];
		if(labels){
			for (var nb in emlabels) {
					var jsonArray = {};
					jsonArray = {
						"language": nb,
						"value": "",
					};
					jsonLabel.push(jsonArray);
				}
			sommaire += "Labels ";
		}
		var jsonDesc = [];
		if(descriptions){
			for (var nb in emdescriptions) {
					var jsonArray = {};
					jsonArray = {
						"language": nb,
						"value": "",
					};
					jsonDesc.push(jsonArray);
				}
			sommaire += "Descriptions ";
		}
		var jsonAlias = [];
		if(aliases){
			jsonAlias = emaliases;
			sommaire += "Aliases ";
		}
		var jsonSitelinks = [];
		if(sitelinks){
			for (var nb in emsitelinks) {
					var jsonArray = {};
					jsonArray = {
						"site": nb,
						"title": "",
					};
					jsonSitelinks.push(jsonArray);
				}
			sommaire += "Sitelinks";
		}
		setValue( JSON.stringify( { 'labels': jsonLabel, 'descriptions': jsonDesc, 'aliases': jsonAlias, 'sitelinks': jsonSitelinks } ), sommaire )
	}
	
	/*
	** Send Deleted value
	*/
	
	function setValue( item, summary ) {
		var reason = prompt(translate( 'reason' ), "...");
		$.ajax( {
			type: 'POST',
  			url: mw.util.wikiScript( 'api' ),
			data: {
				'format': 'json',
				'action': 'wbeditentity',
				'id': itemId,
				'token': mw.user.tokens.get( 'csrfToken' ),
				'data': item,
				'summary': '[[MediaWiki talk:Gadget-dataDrainer.js|dataDrainer]] Delete all ( ' + summary + ') by ( ' + group() + ' ) reason "' + reason + '"',
				'exclude': 'pageid|ns|title|lastrevid|touched'
			}
		} )
		.done(function( data ) {
			if(data.success == 1){
			mw.notify( translate( 'box-deleted' ) + " : Delete all ( " + summary + ') by ( ' + group() + ' ) reason "' + reason + '"' , { title: 'dataDrainer.js :', tag: 'datadrainer', autoHide: 'false' } ); 
			$( '#dataDrainer' ).dialog( "close" );
			$( '#dataDrainer' ).empty();
			$( formFind ).appendTo( '#dataDrainer' );
			} else {
			mw.notify( 'Error: ' + JSON.stringify( data ), { title: 'dataDrainer.js :', tag: 'datadrainer' } ); 
			}
		} )
		.fail(function( data ) {
			mw.notify( 'Error: ' + JSON.stringify( data.success ), { title: 'dataDrainer.js :', tag: 'datadrainer' } ); 
			} )
	}
	
	$( document ).ready( dataDrainer );
} ( mediaWiki, jQuery ) );