MediaWiki:Gadget-diffTools.js

Nota: Depois de publicar, poderá ter de contornar a cache do seu navegador para ver as alterações.

  • Firefox / Safari: Pressione Shift enquanto clica Recarregar, ou pressione Ctrl-F5 ou Ctrl-R (⌘-R no Mac)
  • Google Chrome: Pressione Ctrl-Shift-R (⌘-Shift-R no Mac)
  • Internet Explorer / Edge: Pressione Ctrl enquanto clica Recarregar, ou pressione Ctrl-F5
  • Opera: Pressione Ctrl-F5.
/**
 * Ferramentas para diffs (Reversão e avisos)
 *
 * Em páginas de comparação de 2 edições, inclui atalhos de reverter e avisar o usuário.
 * @source: [[:en:Wikipedia:WikiProject_User_scripts/Scripts/Revert_tools]]
 * @see: [[Wikipedia:Software/Scripts/Reversão e avisos]]
 * @author: [[:en:User:Lorian]]
 * @author: Helder (https://github.com/he7d3r)
 */
window.diffTools = (function () {

	/* Private Members */
	var	that = this,
		user1 = $('#mw-diff-otitle2').find('a').first().html(),
		user2 = $('#mw-diff-ntitle2').find('a').first().html(),
		$patrolLink;
	var options = {
	'revert': {
		'description': false,
		'Opções': {
			'Reverter': {
				'desc': 'Reverte o artigo para a versão mostrada' +
					' à esquerda',
				'sum': 'Reversão de uma ou mais' +
					' [[Special:Contribs/$2|edições de $2]] para a' +
					' versão $3, com [[w:WP:RA|Reversão e avisos]]'
			},
			'+comentário': {
				'desc': 'Reverte o artigo para a versão mostrada' +
					' à esquerda, mas permite incluir informações' +
					' extras no sumário de edição',
				'url': function () {
					var	sum = 'Reversão de uma ou mais [[Special:Contribs/$2|edições de $2]]' +
							' para a versão $3, com [[w:WP:RA|Reversão e avisos]]',
						oldid = mw.util.getParamValue(
							'oldid',
							$('#mw-diff-otitle1').find('a').first().attr('href')
						),
						text = prompt( 'Comentário a acrescentar ao sumário da reversão:', 'inadequado' );
					if (text){
						sum += ' (' + text + ')';
					that.revert(
						mw.config.get( 'wgPageName' ),
						oldid,
						sum
					);
                                        }
				}
			}
		}
	},
	'warn': {
		'description': 'Usuário: ',
		'Boas-vindas': {
			'bv': {
				'desc': 'Envia uma mensagem de boas-vindas ao novo usuário',
				'subst': 'boas-vindas',
				'sum': 'Mensagem de boas-vindas'
			},
			'bv-anon': {
				'desc': 'Envia uma mensagem de boas-vindas ao usuário anônimo',
				'subst': 'bv-ip',
				'sum': 'Mensagem de boas-vindas'
			}
		},
		'Avisos 1': {
			'av-reg': {
				'desc': 'Envia um aviso ao editor registrado, para' +
					' que não coloque informações erradas ou sem' +
					' sentido, nem apague conteúdo dos módulos',
				'subst': 'lixousuario',
				'sum': 'Edição não construtiva'
			},
			'av-anon': {
				'desc': 'Envia um aviso ao editor anônimo, para' +
					' que não coloque informações erradas ou sem' +
					' sentido, nem apague conteúdo dos módulos',
				'subst': 'lixoanonimo',
				'sum': 'Edição não construtiva'
			},
			'bv & av': {
				'desc': 'Envia uma mensagem de boas-vindas e um aviso ao' +
					' editor para que não coloque informações erradas' +
					' ou sem sentido, nem apague conteúdo dos módulos',
				'subst': 'Bv-av',
				'sum': 'Mensagem de boas-vindas e aviso'
			}
		},
		'Avisos 2': {
			'ortografia': {
				'desc': 'Envia um aviso ao editor sobre mudança de ortografia',
				'subst': 'Ort',
				'sum': 'Ortografia'
			},
			'teste': {
				'desc': 'Envia um aviso ao editor sobre um teste em local inapropriado',
				'subst': 'TestsOnlyHere',
				'sum': 'Testes'
			}
		},
		'Imagens': {
			'img com vda': {
				'desc': 'Envia um aviso ao editor, sobre o envio de' +
					' uma imagem que viola os direitos de autor',
				'subst': 'AVDA',
				'sum': 'Imagem com violação de direitos autorais'
			},
			'img sem licença': {
				'desc': 'Envia um aviso ao editor, para que informe' +
					' a licença de uma imagem que enviou',
				'subst': 'AISDL-U',
				'sum': 'Imagem sem licença'
			}
		}
	}
	};

	/* Public Methods */

	// AjaxPatrolLinks is obsolete, feature is now in MediaWiki core. 
	// Stats: [[File:Krinkle_AjaxPatrolLinks.js]]
	this.ajaxPatrolLinks = function() {};

	this.revert = function ( page, oldid, summary ){
		mw.notify( $.parseHTML(
			'Consultando o histórico da página "<a href="' +
			mw.util.getUrl( page ) + '">' + page.replace(/_/g, ' ') + '</a>"...'
		) );
		// TODO: Patrulhar automaticamente as edições revertidas!
		// [[meta:User:Krinkle/Scripts/AjaxPatrolLinks.js]]
		$.ajax({
			url: mw.util.wikiScript( 'api' ),
			dataType: 'json',
			data: {
				'format': 'json',
				'action': 'query',
				'titles': page,
				'prop': 'revisions',
				'rvprop': 'user|content|ids',
				'rvstartid': oldid,
				'rvlimit': 1,
				'indexpageids': true
			},
			success: function( data ) {
				var rev;
				if ( 'error' in data ) {
					alert( 'Erro da API: ' + data.error.code + '. ' + data.error.info );
				} else if ( data.query && data.query.pages && data.query.pageids ) {
					rev = data.query.pages[ data.query.pageids[0] ];
					if( rev.missing === '' ) {
						mw.notify( $(
							'A página "<a href="' +
							mw.util.getUrl( page ) + '">' + page + '</a> não existe!'
						) );
					} else {
						rev = rev.revisions[0];
						that.editPage(
							page,
							rev['*'],
							summary.replace( /\$1/g, rev.user)
								.replace( /\$2/g, user2)
								.replace( /\$3/g, rev.revid)
						);
						$patrolLink.click();
					}
				} else {
					alert( 'Houve um erro inesperado ao usar a API do MediaWiki.' );
				}
			},
			error: function() {
				alert( 'Houve um erro ao usar AJAX para consultar o conteúdo da página.' );
			}
		});
	};
	this.editPage = function( page, text, summary, section ){
		mw.notify(
			'Preparando a edição da página "' + page.replace(/_/g, ' ') + '"...'
		);
		var data = {
			format: 'json',
			action: 'edit',
			minor: true,
			title: page,
			text: text,
			summary: summary,
			token: mw.user.tokens.get( 'csrfToken' )
		};
		if ( typeof section !== 'undefined' ){
			data.section = section;
		}
		$.ajax({
			url: mw.util.wikiScript( 'api' ),
			type: 'POST',
			dataType: 'json',
			data: data,
			success: function( data ) {
				if ( data && data.edit && data.edit.result && data.edit.result == 'Success' ) {
					mw.notify(
						'A página "' + page.replace(/_/g, ' ') + '" <a href="' +
						mw.util.getUrl( page ) + '?diff=0">foi editada</a> (<a href="' +
						mw.util.getUrl( page ) + '">abrir</a>).'
					);
				} else {
					alert( 'Houve um erro ao requisitar a edição da página.' );
				}
			},
			error: function() {
				alert( 'Houve um erro ao usar AJAX para editar a página.' );
			}
		});
	};

	this.getLink = function ( text, data, action ) {
		var $link = $( '<a href="#" title="' + data.desc + '">' + text + '</a>' );
		if (typeof data.url === 'string') {
			$link.attr( 'href', data.url );
		} else {
			$link.click( function( e ){
				e.preventDefault(); // avoid jumping to the top (href=#)
				if ( $.isFunction( data.url ) ) {
					data.url();
				} else if ( action === 'revert'){
					that.revert(
						mw.config.get( 'wgPageName' ),
						mw.util.getParamValue(
							'oldid',
							$('#mw-diff-otitle1').find('a').first().attr('href')
						),
						data.sum
					);
				} else if ( action === 'warn'){
					// edit user talk
					that.editPage(
						mw.config.get( 'wgFormattedNamespaces' )[3] + ':' + user2,
						'{' + '{subst:' + data.subst + '}} ~~' + '~~',
						data.sum, // = section title
						'new'
					);
				}
			} );
		}

		return $link;
	};

	/**
	 * Inserts additional tools on diff pages
	 */
	this.addOptions = function () {
		var	$html = $( '<span id="diff-tools"></span>' ),
			$ulSections = $( '<ul></ul>' );

		$.each( options, function( section, list ){
			var	$liSection = $( '<li class="diff-tools-section"></li>' ),
				$ulSubSections = $( '<ul></ul>' );
			$.each( list, function( subsection, sublist ){
				var	$ulItems = $( '<ul></ul>' ),
					$liSubSection = $( '<li class="diff-tools-subsection"></li>' );
				if ( subsection == 'description' ) {
					$liSection.prepend( sublist || '' );
				} else {
					$.each( sublist, function( text, data ){
						var $item = $( '<li></li>' );
						$item.append( that.getLink( text, data, section ) );
						$ulItems.append( $item );
					} );
					$liSubSection.append( $ulItems );
					$ulSubSections.append( $liSubSection );
				}
			} );
			$liSection.append( $ulSubSections );
			$ulSections.append( $liSection );
		} );
		$html.append( $ulSections );
		$('#contentSub').prepend($html);
	};

	/**
	 * Prepare and execute the tools
	 */
	this.run = function () {
		if ( mw.config.get('wgNamespaceNumber') < 0 || !mw.util.getParamValue('diff') ) {
			return;
		}
		that.addOptions();
	};

	// Executes the script when page is ready
	$(this.run);
})();

// [[Categoria:Gadgets|rev e avisos.js]]
// [[Categoria:Scripts do Wikilivros|rev e avisos.js]]