MediaWiki:Gadget-FastButtons.js

De Wikipedia

Nota: Llueu de guardar, seique tengas que llimpiar la caché del restolador pa ver los cambeos.

  • Firefox / Safari: Caltén Mayús mentes calques en Recargar, o calca Ctrl-F5 o Ctrl-R (⌘-R nun Mac)
  • Google Chrome: Calca Ctrl-Mayús-R (⌘-Mayús-R nun Mac)
  • Internet Explorer / Edge: Caltén Ctrl mentes calques Refrescar, o calca Ctrl-F5
  • Opera: Calca Ctrl-F5.
/**Especial:Contributions
 * FastButtons de Racso
 * <nowiki>
 */
// Protege contra doble inclusión
if ( window.fastButtons === undefined ) {
	importScript( 'Special:Mypage/FB.js' );
	
	//Checker
	var fastButtons = {
	    FBList: '',
	    ufb: ', usando [[:ast:Wikipedia:FastButtons|FastButtons]]',
	    wikiURL: mw.util.wikiScript( 'index' ) + '?title=',
	    isSysop: false
	};
	
	//Enlaza con window
	window.fastButtons = fastButtons;
	
	//Scope local para no contaminar espacio global
	(function ( $, mw ) {
	    'use strict';
	    //*********************************************************************
	    //Funciones generales
	    //*********************************************************************
	    //readInputButton: ejecuta el código de un botón de acción que lee datos. Lee un dato del usuario.
	    fastButtons.readInputButton = function ( mensaje, buttonType, wikiAction ) {
	        wikiAction = wikiAction || 'edit';
	        var input = window.prompt( decodeURI( mensaje ) );
	        if ( input != null ) {
	            location.href = fastButtons.wikiURL + wikiAction + '&' + buttonType + '=' + encodeURI( input );
	        }
	        return false;
	    };
	
	    //addTemplate: añade una plantilla al inicio de la página, y guarda.
	    function addTemplate( plantilla, resumen, save ) {
	        $( '#wpTextbox1' ).val( plantilla + '\n' + $( '#wpTextbox1' ).val() );
	        $( '#wpSummary' ).val( resumen + fastButtons.ufb );
	        save && $( '#editform' ).submit();
	    }
	
	    //addTemplateEnd: añade una plantilla al final de la página, y guarda.
	    function addTemplateEnd( plantilla, resumen ) {
	        $( '#wpTextbox1' ).val( $( '#wpTextbox1' ).val() + '\n' + plantilla );
	        $( '#wpSummary' ).val( resumen + fastButtons.ufb );
	        $( '#editform' ).submit();
	    }
	
	    //addFastButton: genera la cadena para añadir un botón, tomando ciertos parámetros.
	    function addFastButton( buttonLabel, buttonType, typeParam, wikiAction ) {
	        typeParam = typeParam || buttonLabel;
	        wikiAction = wikiAction || 'edit';
	        return '[<a href="' + fastButtons.wikiURL + wikiAction + '&' + buttonType + '=' +
	            encodeURI( typeParam ) + '">' + buttonLabel + '<\/a>] ';
	    }
	
	    //addActionFastButton: genera la cadena para añadir un botón de acción.
	    function addActionFastButton( buttonLabel, accion ) {
	        return '[<a href="#" onclick="return ' + accion + ';">' + buttonLabel + '<\/a>] ';
	    }
	
	    //addBlockFastButton: genera la cadena para añadir un botón de bloqueo rápido. Es un botón con código más específico,
	    //por lo que se hizo por aparte en vez de complicar las demás funciones generalizándolas tanto.
	    function addBlockFastButton() {
	        var targetName = '',
	            urlHref = location.href;
	        if ( urlHref.match( "Especial:Bloquiar/" ) ) {
	            targetName = decodeURI( urlHref.substring( urlHref.indexOf( "Especial:Bloquiar/" ) + 18 ) );
	        } else if ( urlHref.match( "Especial:Contributions/" ) ) {
	            targetName = decodeURI( urlHref.substring( urlHref.indexOf( "Especial:Contributions/" ) + 24 ) );
	        }
	
	        if ( !targetName ) {
	            return '';
	        }
	
	        return '[<a href="' + mw.util.wikiScript( 'index' ) + '?title=Especial:Bloquiar/' +
	            targetName + '&FBblock=31">31h, vandalismu<\/a>] ';
	    }
	
	    //*********************************************************************
	    //Funciones de carga [por defecto] de los botones.
	    //*********************************************************************
	    //BOTONES PARA NO-SYSOP
	    function loadNoSysop() {
	        var tmp = '';
	
	        tmp += addFastButton( 'Vandalismu', "FBdest" );
	        tmp += addFastButton( 'Pruebes d edición', "FBdest" );
	        tmp += addFastButton( 'Promocional', "FBdest" );
	        if( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 0, 104 ] ) > -1 ) {
	            tmp += addFastButton( 'Non enciclopédicu', "FBdest" );
	            tmp += addFastButton( 'Infraentamu', "FBdest" );
	        }
	        tmp += addActionFastButton( 'Plaxu', "fastButtons.readInputButton( 'URL', 'FBplagio' );" );
	        tmp += addActionFastButton( 'Otru', "fastButtons.readInputButton( 'Motivu', 'FBdest' );" );
	
	        return tmp;
	    }
	
	    //BOTONES PARA SYSOP
	    function loadSysop() {
	        var tmp = '';
	
	        tmp += addFastButton( 'Desaniciáu rápidu', 'FBdelete', 'default', 'delete' );
	        tmp += addActionFastButton( 'Desaniciar', "fastButtons.readInputButton( 'Motivu', 'FBdelete', 'delete' );" );
	        tmp += addFastButton('Llimpiar caché', 'FBcache', 'default', 'purge');
	
	        return tmp;
	    }
	
	    //PLANTILLAS (BOTONES GENERALES)
	    function loadTemplates() {
	        var tmp = '';
	
	        if( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 0, 104 ] ) > -1 ) {
	            tmp += addFastButton( 'Calidá', 'FBplant', '{{calidá|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            //tmp += addFastButton( '1000', 'FBplant', '{{1000}}' );
	            tmp += addFastButton( 'Correxir', 'FBplant', '{{correxir|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            if (!document.querySelector('.revisau')) {
	            	tmp += addFastButton( 'Revisáu', 'FBplant', '{{revisáu|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            }
	            if (!document.querySelector('.ambox a[href="/wiki/Ayuda:Wikificar"]')) {
	            	tmp += addFastButton( 'Wikificar', 'FBplant', '{{wikificar|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            }
	            if (!document.querySelector('.ambox a[href="/wiki/Wikipedia:Verificabilid%C3%A1"]')) {
	            	tmp += addFastButton( 'Referencies', 'FBplant', '{{referencies|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            }
	            //tmp += addFastButton( 'Destacáu', 'FBplant', '{{artículu destacáu}}' );
	            if (!document.getElementById('disambig')) {
	            	tmp += addFastButton( 'Dixebra', 'FBplant', '{{dixebra}}' );
	            }
	            tmp += addFastButton( 'Editándose', 'FBplant', '{{editándose|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            if (!document.querySelector('.ambox a[href="/wiki/Wikipedia:Entamos"]')) {
	            	tmp += addFastButton( 'Entamu', 'FBplant', '{{entamu|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            }
	            //tmp += addFastButton( 'Estandarizar', 'FBplant', '{{estandarizar|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            //tmp += addFastButton( 'Necesítase imaxe', 'FBplant', '{{necesítase imaxe|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            tmp += addFastButton( 'Noneutral', 'FBplant', '{{noneutral|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            tmp += addFastButton( 'Eventu actual', 'FBplant', '{{eventu actual|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            tmp += addFastButton( 'Revref', 'FBplant', '{{revref|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            tmp += addFastButton( 'Desactualizáu', 'FBplant', '{{desactualizáu|t={{subst:CURRENTTIMESTAMP'+'}}}}' );
	            
	            if (!document.querySelector('.mw-authority-control')) {
	            	tmp += addFastButton( 'Control d\'autoridaes', 'FBcontrolautoridaes', "{{control d'autoridaes}}" );
	            }
	        } else if (mw.config.values.wgCanonicalNamespace == 'Category') {
	            if (mw.config.values.wgAction == 'view' && document.querySelector('.wb-otherproject-commons') && !document.querySelector('.plainlinks.commons')) {
	            	tmp += addFastButton('commonscat', 'FBplant', '{{commonscat}}');
	            }
	        }
	        
	
	        return tmp;
	    }
	    
	    function loadTemplatesInfobox() {
	       var tmp = '';
	
	        if ($.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 0, 104 ] ) > -1) {
	        	var haiPlantiaInfobox = document.querySelector('.infobox[class*="plantia-"]');
	        	// si yá hai plantía d'infobox nun tien sentíu amosar botones p'añadir otra plantía infobox
	        	if (haiPlantiaInfobox) {
	        		return null;
	        	}
	        	
	        	if (!document.querySelector('.infobox.plantia-llocalida')) {
	            	tmp += addFastButton( 'Llocalidá', 'FBplant', '{{llocalidá}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-rexon')) {
	            	tmp += addFastButton( 'Rexón', 'FBplant', '{{rexón}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-persona')) {
	            	tmp += addFastButton( 'Persona', 'FBplant', '{{persona}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-organizacion')) {
	            	tmp += addFastButton( 'Organización', 'FBplant', '{{organización}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-edificiu')) {
	            	tmp += addFastButton( 'Edificiu', 'FBplant', '{{edificiu}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-equipu')) {
	            	tmp += addFastButton( 'Equipu', 'FBplant', '{{equipu}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-competicion-deportiva')) {
	            	tmp += addFastButton( 'Competición deportiva', 'FBplant', '{{competición deportiva}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-documentu')) {
	            	tmp += addFastButton( 'Documentu', 'FBplant', '{{documentu}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-comida')) {
	            	tmp += addFastButton( 'Comida', 'FBplant', '{{ficha de comida}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-personaxe')) {
	            	tmp += addFastButton( 'Personaxe', 'FBplant', '{{personaxe}}' );
	        	}
	        	if (!document.querySelector('.infobox.plantia-vehiculu')) {
	            	tmp += addFastButton( 'Vehículu', 'FBplant', '{{vehículu}}' );
	        	}
	        	
	        	tmp += '<a href="" onclick="this.nextElementSibling.style.display=\'inline-block\'; document.getElementById(\'otherInfobox\').focus(); this.remove(); return false;">[Otra plantía]</a>'
	        	tmp += '<div style="display:none"><input type="text" list="infobox" id="otherInfobox" style="background-color: rgba(255,255,255,0.5); color: #000000; border: 1px solid #a2a9b1; border-radius: 2px; padding: 0.4em; font-size: 0.9em;"><datalist id="infobox">';
	        	tmp += getInfoboxTemplatesList().map(function(item) {
	        		return '<option value="' + item + '"/>';
	        	}).join('') + '</datalist>';
	        	tmp += '<button style="cursor:pointer; vertival-align: middle" onclick="var selected = document.getElementById(\'otherInfobox\').value.trim(); if (!selected) { return false; } else { document.location.href=\'' + fastButtons.wikiURL + 'edit&FBplant={{\' + selected + \'}}\'\}">Guardar</button>';
	        	tmp += '</div>';
	    	}
	
	        return tmp;
	    }
	
	    //BOTONES DE VARIAS FUNCIONALIDADES (BOTONES GENERALES)
	    function loadMisc() {
	        var tmp = '',
	            warnMenu = encodeURI( "Avisu:\n: (no disp.)\n0a: (no disp.)\n" +
	                "0b: (no disp.)\n0c: (no disp.)\n2: Ediciones arbitraries\n2a: Blanquéu de páxines\n" +
	                "3: Vandalismu\n4: (no disp.)\n5: (no disp.)" );
	
	        if( mw.config.get( 'wgNamespaceNumber' ) != 3 ) {
	            return tmp;
	        }
	
	        tmp += addActionFastButton( "Alvertencia", "fastButtons.readInputButton(\'" + warnMenu + "\', 'FBwarn' );" );
	        tmp += addFastButton( 'Bienvenida', 'FBplant', "{{bienvenida}}\n~~" + "~~" );
	        return tmp;
	    }
	
	    //*********************************************************************
	    //Añadir los botones
	    //*********************************************************************
	    function cargar() {
	        //Extraer datos de la página
	        var tmp;
	        if ( $.inArray( 'sysop', mw.config.get( 'wgUserGroups' ) ) > -1 ) {
	            fastButtons.isSysop = true;
	        }
	
	        fastButtons.wikiURL = fastButtons.wikiURL + mw.util.wikiUrlencode( mw.config.get( 'wgPageName' ) ) + "&action=";
	
	        //Tiene que ser editable
	        if ( mw.config.get( 'wgNamespaceNumber' ) >= 0 ) {
	            //Botones para bibliotecarios
	            if ( fastButtons.isSysop ) {
	                if ( typeof botonesSysop == 'function' ) {
	                    tmp = botonesSysop();
	                } else {
	                    tmp = loadSysop();
	                }
	                if ( tmp ) {
	                    fastButtons.FBList = fastButtons.FBList + 'Alministradores: ' + tmp + '<br>';
	                }
	            } else { //Botones de destruir. Sólo aparecen a no-bibliotecarios.
	                if ( typeof botonesNoSysop == 'function' ) {
	                    tmp = botonesNoSysop();
	                } else {
	                    tmp = loadNoSysop();
	                }
	                if ( tmp ) {
	                    fastButtons.FBList = fastButtons.FBList + 'Destruyir: ' + tmp + '<br>';
	                }
	            }
	
	            //Plantillas. Aparecen a todos los usuarios.
	            if ( typeof botonesPlantillas == 'function' ) {
	                tmp = botonesPlantillas();
	            } else {
	                tmp = loadTemplates();
	            }
	            
	            if ( tmp != '' ) {
	            	fastButtons.FBList += 'Plantíes: ' + tmp + '<br>';
	            }
	            
	            tmp = loadTemplatesInfobox();
	        	if (tmp) {
	            	fastButtons.FBList += 'Ficha: ' + tmp + '<br>';
	        	}
	        	
				const utils = [
				    {
				        selector: 'a.mw-disambig',
				        key: 'showdisamb',
				        fnc: 'toggleHighlightDixebra',
				        label: 'Solliñar enllaces a dixebra',
				        styles: 'body.showdisamb a.mw-disambig {color: darkblue; background: #cfeaf3} body.showdisamb a.mw-disambig::after { content: url(https://upload.wikimedia.org/wikipedia/commons/thumb/7/72/Disambig.svg/18px-Disambig.svg.png)}'
				    },
				    {
				        selector: 'a.mw-redirect',
				        key: 'showredirect',
				        fnc: 'toggleHighlightRedirect',
				        label: 'Solliñar enllaces a redireiciones',
				        styles: 'body.showredirect a.mw-redirect {color: darkblue; background: #cfeaf3} body.showredirect a.mw-redirect::after { content: url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Symbol_redirect_arrow_blue.svg/18px-Symbol_redirect_arrow_blue.svg.png)}'
				    }
				];
				
				const utilsHTML = utils.map(function (util) {
				    const total = document.querySelectorAll(util.selector).length;
				
				    if (!total) {
				        return;
				    }
				
				    const checked = localStorage.getItem(util.key);
				
				    window[util.fnc] = function () {
				        if (!document.querySelector(util.key)) {
				            const s = document.createElement('style');
				            s.id = util.key;
				            s.textContent = util.styles;
				            document.body.appendChild(s);
				        }
				        const enabled = document.body.classList.contains(util.key);
				        if (enabled) {
				            document.body.classList.remove(util.key);
				            localStorage.removeItem(util.key);
				        } else {
				            document.body.classList.add(util.key);
				            localStorage.setItem(util.key, 1);
				        }
				    };
				
				    if (checked) {
				        window[util.fnc]();
				    }
				
				    return (
				        '<label style="cursor:pointer;color:#3366cc"><input type="checkbox" style="vertical-align:middle" onchange="' +
				        util.fnc +
				        '()" ' +
				        (checked ? 'checked' : '') +
				        ' /> ' +
				        util.label +
				        ' (' +
				        total +
				        ')</label>'
				    );
				});
				
				if (utilsHTML) {
					fastButtons.FBList += 'Utilidaes: ' + utilsHTML.join(' | ');
				}

	
	            //Otros. Aparecen a todos los usuarios.
	            if ( typeof botonesOtros == 'function' ) {
	                tmp = botonesOtros();
	            } else {
	                tmp = loadMisc();
	            }
	            if ( tmp ) {
	                fastButtons.FBList = fastButtons.FBList + 'Otros: ' + tmp;
	            }
	        } else {
	            if ( fastButtons.isSysop ) {
	                if ( typeof botonesBloqueo == 'function' ) {
	                    tmp = botonesBloqueo();
	                } else {
	                    tmp = addBlockFastButton();
	                }
	                if ( tmp ) { //El <br> de más es porque el botón es peligroso y aparece muy pegado a las demás opciones
	                    fastButtons.FBList = fastButtons.FBList + '<br>Bloquéu: ' + tmp;
	                }
	            }
	        }
	    }
	
	    /* Mostrar los botones en la página */
	    function instalar() {
	        var temp;
	        cargar();
	
	        if ( $( '#contentSub' ).html() ) {
	            $( '#contentSub' ).html( $( '#contentSub' ).html() + '<br>' + fastButtons.FBList );
	        } else {
	            $( '#contentSub' ).html( fastButtons.FBList );
	        }
	
	        if ( mw.util.getParamValue( 'FBdest' ) != null ) {
	            temp = mw.util.getParamValue( 'FBdest' );
	            addTemplate( "{{"+"Destruir|1=" + temp + "}}", "Destruyir: " + temp );
	        } else if (mw.util.getParamValue('FBcontrolautoridaes')) {
	        	var element = document.getElementById('wpTextbox1');
	        	// check if template is already in
	        	if (element.value.match(/{{control d'autoridaes}}/i)) {
	        		history.back();
	        	} else {
	            	if (element.value.match(/\[\[categoría:/i)) {
	            		// add template right above first category
	            		element.value = element.value.replace(/(\[\[categoría:)/i, "{{control d'autoridaes}}\n$1")
	            	} else {
	            		// if there are no categories, append the template at the end of the article
	            		element.value = element.value.trim() + "\n{{control d'autoridaes}}";
	            	}
		            document.getElementById('wpSummary').value = "+{{control d'autoridaes}}" + fastButtons.ufb;
	            	document.getElementById('editform').submit();
	        	}
	        } else if ( mw.util.getParamValue( 'FBplant' ) != null ) {
	            temp = mw.util.getParamValue( 'FBplant' );
	            if (temp.indexOf('revisáu') !== -1) {
	            	var content = document.getElementById('wpTextbox1').value;
	            	if (content.match(/{{Tradubot/i)) {
	            		alert('Nun puedes amestar la plantía {{revisáu}} porque l\'artículu entá tien la plantía {{tradubot}}');
	            		return;
	            	}
	            	if (content.match(/Categoría:Wikipedia:Revisar traducción/i)) {
	            		alert('Nun puedes amestar la plantía {{revisáu}} porque l\'artículu ta na categoría "Wikipedia:Revisar traducción"');
	            		return;
	            	}
	            }
	            
	            var autosave = !mw.util.getParamValue('noautosave');
	        	addTemplate(temp, "Plantía: " + temp, autosave);
	        } else if ( mw.util.getParamValue( 'FBplagio' ) != null ) {
	            temp = mw.util.getParamValue( 'FBplagio' );
	            addTemplate( '{{Copyright|1=' + temp + '}}', "Plaxu dende " + temp );
	        } else if ( mw.util.getParamValue( 'FBdelete' ) != null ) {
	            temp = mw.util.getParamValue( 'FBdelete' );
	            if ( temp != 'default' ) {
	                $( '#wpReason' ).val( temp );
	            }
	            $( '#deleteconfirm' ).submit();
	        } else if ( mw.util.getParamValue( 'FBwarn' ) != null ) {
	            temp = mw.util.getParamValue( 'FBwarn' );
	            addTemplateEnd( '{{subst:Avisu prueba' + decodeURI(temp) + '}} ~~' + '~~', 'Avisu a usuariu' );
	        } else if ( mw.util.getParamValue( 'FBblock' ) != null ) {
	            $( '#mw-input-wpExpiry' ).val( '31 hores' );
	            $( '#mw-input-wpReason' ).val( '[[WP:VN|Vandalismu de páxinas]]' );
	            $( '#mw-input-wpDisableUTEdit' ).prop( 'checked', true );
	            $( 'form.visualClear' ).submit();
	        } else if ( mw.util.getParamValue('FBcache') !== null) {
	        	$('#bodyContent button[type=submit]').click();
	        }
	    }
	    
	    function getInfoboxTemplatesList() {
	    	return ["Aereollinia", "Aeropuertu", "Alfabetu", "Bancu", "Banda", "Cantar", "Carretera", "Circuitu", "Comida", "Competición deportiva", "Discu", "Divisa", "Dominiu d'internet", "Economía", "Edificiu", "Empresa", "Equipu", "Estación de tren", "Estadiu", "Ficha d'oxetu celeste", "Ficha de formatu d'archivu", "Ficha de galaxa", "Ficha d'obra artística", "Ficha de taxón", "Glaciar", "Grafema", "Hardware", "Idioma", "Islla", "Llei", "Llocalidá", "Monte", "Orde", "Organización", "Parllamentu", "Partíu políticu", "País", "Película", "Persona", "Personaxe", "Pintura", "Premiu", "Programa de televisión", "Publicación", "Puertu", "Rexón", "Serie", "Sindicatu", "Sitiu web", "Software", "Universidá", "Videoxuegu", "Xeografía"];
	    }
	
	    $( document ).ready( instalar );
	
	})( jQuery, mediaWiki ); // Fin de función anónima
}