MediaWiki:Gadget-fastbuttons.js e Ajuda:Página de testes/1: diferenças entre as páginas

Origem: Wikipédia, a enciclopédia livre.
(Diferenças entre páginas)
Conteúdo apagado Conteúdo adicionado
ThiagoRuiz (discussão | contribs)
 
m version: '~~~~~': Remoção do código que deixou de ser necessário quando a rev:96466 foi copiada para os servidores da Wikipédia
 
Linha 8: Linha 8:
window.fb = {
window.fb = {
//Replace this string by 5~ before saving:
//Replace this string by 5~ before saving:
version: '14h47min de 19 de agosto de 2011 (UTC)',
version: '14h17min de 8 de setembro de 2011 (UTC)',
ns: mw.config.get('wgNamespaceNumber'),
ns: mw.config.get('wgNamespaceNumber'),
title: mw.config.get('wgTitle'),
title: mw.config.get('wgTitle'),
Linha 576: Linha 576:
'action': 'edit',
'action': 'edit',
'fastb': code
'fastb': code
},
};
param = [];
if( extraText ){
if( extraText ){
data.fbtxt = extraText;
data.fbtxt = extraText;
}
}
$.each( data, function( key, value){
param.push( key + '=' + encodeURIComponent( value ) );
})
$patrol = mw.util.$content.find('span.patrollink a').first();
$patrol = mw.util.$content.find('span.patrollink a').first();
rcid = mw.util.getParamValue( 'rcid', $patrol.attr('href') || '' );
rcid = mw.util.getParamValue( 'rcid', $patrol.attr('href') || '' );
if ( rcid ) {
if ( rcid ) {
fb.patrolRevision( rcid, function(){
fb.patrolRevision( rcid, function(){
location.href = url + param.join( '&' );
location.href = url + $.param( data );
} );
} );
} else{
} else{
location.href = url + param.join( '&' );
location.href = url + $.param( data );
}
}
break;
break;

Revisão das 14h17min de 8 de setembro de 2011

/** FastButtons

* @author:  (versão original do script, na Wikipédia em espanhol)
* @author:  (versão adaptada para a Wikipédia inglesa)
* @author: Outros editores que aparecem no histórico
* @source:  (https://secure.wikimedia.org/wikipedia/en/w/index.php?oldid=230473471)
* @source: 
*/

window.fb = { //Replace this string by 5~ before saving: version: '14h17min de 8 de setembro de 2011 (UTC)', ns: mw.config.get('wgNamespaceNumber'), title: mw.config.get('wgTitle'), catScanUrl: 'http://toolserver.org/~daniel/WikiSense/CategoryIntersect.php' + $.param( { 'wikilang': mw.config.get('wgContentLanguage'), 'wikifam': '.wikipedia.org', 'userlang': mw.config.get('wgUserLanguage'), 'basecat': mw.config.get('wgTitle'), 'basedeep': '1', 'go': 'Examinar', 'format': 'html', 'mode': } ), submenu: {},

$menu: $( '

' ), $submenu: $( '

' )

};

// TODO: Mover estas variáveis para o escopo em que são realmente utilizadas var esbText = , esbText2 = ;

/* Cria os links que ativam a função fb.run()

* @param {string} func
* @param {string} text Text for link
* @param {string} title Title for link
* @param {string=} promptMsg Text for prompt message (optional)
* @return {string} The HTML string of the link
* FIXME: Usar jQuery em vez de onClick, para melhor compatiblidade (mw:RL/MGU#Event_binding)
*/

fb.button = function ( data ) { var action = data.action; if( data.disable ) { return '' + data.text + ''; } else { if (action.indexOf( 'ER' ) === 0) { action = 'var obs=prompt(\'Se necessário, coloque uma observação.\');' + 'fb.run(\ + action + '\',obs)'; } else if (data.prompt) { action = 'var obs=prompt(\ + data.prompt + '\');fb.run(\ + action + '\',obs)'; } else { action = 'fb.run(\ + action + '\')'; } return '<a class="fb-button fb-action-button" title="' + data.title + '" onClick="' + action + '">' + data.text + '</a>'; } };

fb.submenu = { /*** Submenu [ER] ***/ ER: 'Regra: ' + [ fb.button({ action: 'ER|1', text: '1', title: '???', disable: true }), fb.button({ action: 'ER|5', text: '5', title: 'Aparecimento recorrente (se o conteúdo for igual ao eliminado por votação)' }), fb.button({ action: 'ER|6', text: '6', title: 'Título é SPAM', disable: $.inArray(fb.ns, [0, 102]) === -1 }), fb.button({ action: 'ER|7', text: '7', title: 'Próprio criador reconhece que se enganou' }), fb.button({ action: 'ER|8', text: '8', title: 'Eliminações temporárias sem perda de histórico para resolver problemas técnicos', disable: $.inArray('sysop', mw.config.get('wgUserGroups')) === -1 }), fb.button({ action: 'ER|9', text: '9', title: 'Eliminar redirect, página sem histórico relevante' + ' (mover página redirecionada para cá)' }), fb.button({ action: 'ER|10', text: '10', title: 'Namespaces que não existem (WikipÉdia, AjUda)', disable: fb.ns !== 0 }), fb.button({ action: 'ER|11', text: '11', title: 'Má configuração do teclado (Página, Usuário:Sicrano)' }), fb.button({ action: 'ER|12', text: '12', title: 'Imagens, somente por quem a carregou', disable: fb.ns !== 6 }), fb.button({ action: 'ER|13', text: '13', title: 'Páginas sem histórico relevante que são violações flagrantes de' + ' direitos autorais de outras páginas na internet.', disable: $.inArray(fb.ns, [0, 102]) === -1 }), fb.button({ action: 'ER|14', text: '14', title: 'Ficheiros (arquivos) duplicados', disable: fb.ns !== 6 }), fb.button({ action: 'ER|17', text: '17', title: 'Salto de domínio' }), fb.button({ action: 'ER|18', text: '18', title: 'Discussão cujos artigos não existem', disable: fb.ns !== 1 }), fb.button({ action: 'ER|19', text: '19', title: 'Ficheiros (domínio Ficheiro:) que não são som, imagem ou vídeo', disable: fb.ns !== 6 }), fb.button({ action: 'ER|20', text: '20', title: 'Impróprio' }), fb.button({ action: 'ER|21', text: '21', title: 'Página de eliminação de um artigo antes de passados 6 meses da última votação', disable: mw.config.get('wgPageName').indexOf('Wikipédia:Páginas_para_eliminar/') !== 0 }), fb.button({ action: 'ER|A1', text: 'A1', title: 'Páginas com o título malformatado, absurdo, com palavras que não' + ' o são, com erros devidos à má configuração do teclado, com codificação' + ' incorreta do sistema ou que expressem domínios que não existem.', disable: $.inArray(fb.ns, [0, 102]) === -1 }), fb.button({ action: 'ER|C1', text: 'C1', title: 'Categorias vazias, desnecessárias ou substituídas', disable: fb.ns !== 14 }), fb.button({ action: 'ER|D1', text: 'D1', title: 'Discussões de páginas inexistentes', disable: fb.ns % 2 === 0 }), fb.button({ action: 'ER|D2', text: 'D2', title: 'Discussões de páginas para eliminação ou com histórico irrelevante', disable: fb.ns % 2 === 0 }), fb.button({ action: 'ER|U1', text: 'U1', title: 'Uso impróprio da página de usuário', disable: $.inArray(fb.ns, [2, 3]) === -1 }), fb.button({ action: 'ER|U2', text: 'U2', title: 'Página de usuário criada por outro usuário', disable: fb.ns !== 2 }), fb.button({ action: 'ER|P1', text: 'P1', title: 'Predefinições vazias, desnecessárias ou substituídas', disable: fb.ns !== 10 }), fb.button({ action: 'ER|R1', text: 'R1', title: 'Redirecionamento indevido, desnecessário, sem afluentes,' + ' para páginas inexistente ou eliminadas' }), fb.button({ action: 'ER|R2', text: 'R2', title: 'Redirecionamento de página de discussão', disable: fb.ns % 2 === 0 }) ].join(' '), /*** Submenu [ESR] ***/ ESR: [ fb.button({ action: 'subst:ESR-banda|1=~~' + '~~', text: 'banda', title: 'Artigo sobre banda sem fontes e sem notoriedade' }), fb.button({ action: 'subst:ESR-bio|1=~~' + '~~', text: 'biografia', title: 'Biografia sem fontes e sem notoriedade' }), fb.button({ action: 'subst:ESR-empresa|1=~~' + '~~', text: 'empresa', title: 'Empresa sem fontes e sem notoriedade' }), // FIXME: Usar jQuery em vez de onKeyPress e onMouseDown, para melhor compatiblidade (mw:RL/MGU#Event_binding) 'outra: <input type="text" id="fb-esr-input" onKeyPress="fb.ok(event, \'ESR\')" size=55/>', '<input type="button" onMouseDown="fb.ok(\'ok\', \'ESR\')" value="OK"/>' ].join(), /*** Submenu [esboço] ***/ esb: fb.button({ action: 'mínimo', text: 'mínimo', title: 'Artigo com apenas uma frase' }) + ' ' + fb.button({ action: 'esboço', text: 'esboço', title: 'Artigo ainda pouco desenvolvido' }) + // FIXME: Usar jQuery em vez de onkeyup, onKeyPress e onMouseDown, para melhor compatiblidade (mw:RL/MGU#Event_binding) ' esboço-' + '<input id="fb-esb-input" onkeyup="fb.callAPI(\'esb\')"' + ' onKeyPress="fb.ok(event, \'esb\')" size=14/>' + '<input type="button" onMouseDown="fb.ok(\'ok\', \'esb\')" value="OK"/>', /*** Submenu [manuteção] ***/ man: [ fb.button({ action: 'subst:wkf', text: 'wikificar', title: 'Não está formatado de acordo com o livro de estilo' }), fb.button({ action: 'subst:s-fontes', text: 'sem fontes', title: 'Página não cita nenhuma fonte ou referência' }), fb.button({ action: 'sem cat', text: 'sem cat', title: 'Página não está em nenhuma categoria' }), fb.button({ action: 'subst:rec', text: 'reciclagem', title: 'Página precisa ser reciclada de acordo com o livro de estilo' }), fb.button({ action: 'parcial', text: 'parcial', title: 'Artigo possui passagens que não respeitam o princípio da imparcialidade' }), fb.button({ action: 'subst:ctx', text: 'contexto', title: 'Página carece de contexto' }), fb.button({ action: 'controverso|artigo', text: 'controverso', title: 'controverso devido às disputas sobre o seu conteúdo' }), fb.button({ action: 'subst:f-referências', text: 'formatar referências', title: 'Artigo contém referências que necessitam de formatação' }), fb.button({ action: 'subst:m-notas', text: 'mais notas', title: 'Página cita fontes fiáveis, mas não cobre todo o texto' }), fb.button({ action: 'subst:s-notas', text: 'sem notas', title: 'Existem fontes no final da página, mas não são citadas no corpo do artigo' }), fb.button({ action: 'subst:s-fontes-bpv', text: 'bpv sem fontes', title: 'Biografia de pessoa viva que não cita nenhuma fonte' }), fb.button({ action: 'subst:fpr', text: 'fonte primária', title: 'Artigo necessita de fontes secundárias fiáveis publicadas por terceiros' }) ].join(' '), /*** Submenu [busca] ***/ search: [ '<a href="http://www.google.com/search?&as_eq=wikipedia&as_epq=', '" class="external text">Google</a> — <a href="http://news.google.com/archivesearch?&as_src=-newswire+-wire+-presswire+-PR+-press+-release&as_epq=', '" class="external text">notícias</a>, <a href="http://books.google.com/books?&as_brr=0&as_epq=', '" class="external text">livros</a>, <a href="http://scholar.google.com/scholar?as_epq=', '" class="external text">acadêmico</a> — <a href="http://www.scirus.com/srsapp/search?q=', '&t=all&sort=0&g=s" class="external text">Scirus</a>' ].join( encodeURIComponent( ( fb.title.indexOf( ' ' ) > -1 ) ? '"' + fb.title + '"': fb.title ) ),

/*** Submenu [aviso] ***/ warn: [ fb.button({ action: 'subst:bem-vindo IP', text: 'BV-IP', title: 'Boas-vindas para usuário(a) não registrado(a)' }), fb.button({ action: 'subst:bem-vindo', text: 'BV', title: 'Bem-vindo(a) à Wikipédia' }), fb.button({ action: 'subst:bem-vinda', text: 'BVª', title: 'Bem-vinda à Wikipédia' }), fb.button({ action: 'subst:bv-av', text: 'av-BV-IP', title: 'Aviso sobre erro em artigo e boas-vindas para usuário(a) não registrado(a)', prompt: 'Aviso sobre qual artigo?' }), fb.button({ action: 'subst:bv-av-registrado', text: 'av-BV', title: 'Aviso sobre erro em artigo e boas-vindas para usuário(a) registrado', prompt: 'Aviso sobre qual artigo?' }), fb.button({ action: 'subst:aviso-ER', text: 'av-ER', title: 'Aviso sobre eliminação rápida', prompt: 'Qual página foi proposta para eliminação?' }), fb.button({ action: 'subst:av-bv-ER', text: 'av-BV-ER', title: 'Aviso sobre eliminação rápida + boas-vindas', prompt: 'Qual página foi proposta para eliminação?' }), fb.button({ action: 'subst:aviso-ESR', text: 'av-ESR', title: 'Aviso sobre eliminação semirrápida', prompt: 'Qual página foi proposta para eliminação?' }), fb.button({ action: 'subst:aviso-PE', text: 'av-PE', title: 'Aviso sobre eliminação por votação', prompt: 'Qual página foi proposta para eliminação?' }), fb.button({ action: 'subst:aviso-PE-criador', text: 'av-PE-criador', title: 'Aviso ao criador sobre eliminação por votação', prompt: 'Qual página foi proposta para eliminação?' }), fb.button({ action: 'subst:bv-propaganda', text: 'prop-BV', title: 'Caro editor,por favor não faça propaganda, [...] Apesar disso, bem-vindo à Wikipédia' }), fb.button({ action: 'subst:propaganda', text: 'prop', title: 'Caro editor, por favor não faça propaganda...', prompt: 'Em que página foi feita propaganda?' }), fb.button({ action: 'subst:aviso', text: 'av', title: 'Aviso sobre erro em artigo', prompt: 'Aviso sobre qual artigo?' }), fb.button({ action: 'subst:aviso2', text: 'av2', title: 'Aviso sobre vandalismo', prompt: 'Qual página foi vandalizada?' }), fb.button({ action: 'subst:BSRE', text: 'BSRE', title: 'Aviso de biografia sem relevo enciclopédico', prompt: 'Qual artigo?' }), fb.button({ action: 'subst:cópia', text: 'cópia', title: 'Aviso sobre artigo copiado de fonte externa/VDA', prompt: 'Preencha usando \'|2=\' como separador: página da Wikipédia|2=url da página copiada' }), fb.button({ action: 'subst:linguagem incorreta', text: 'linguagem', title: 'Não insulte nem use linguagem inadequada em artigos ou discussões' }), fb.button({ action: 'subst:ortografia', text: 'ortografia', title: 'Não mude a versão da língua' }), fb.button({ action: 'subst:mostrar previsão', text: 'salvamento sucessivo', title: 'Não faça salvamentos sucessivos, utilize o botão \'Mostrar previsão\, prompt: 'Em que artigo foram feitos salvamentos sucessivos?' }), fb.button({ action: 'subst:Av-boas vindas', text: 'aviso-BV', title: 'Não dê boas-vindas a usuários que não contribuíram com pelo menos uma edição válida' }), fb.button({ action: 'subst:Av-página de usuário', text: 'av-PU', title: 'Considere refazer a página de usuário(a)' }), fb.button({ action: 'subst:Aviso/Página pessoal', text: 'av-PU-outro', title: 'Não edite páginas de outros usuários', prompt: 'Qual página de outro(a) usuário(a) foi editada?' }), fb.button({ action: 'subst:não remova', text: 'não remova', title: 'Não remova marcações de eliminação das páginas', prompt: 'Qual página em que a marcação de eliminação foi removida?' }), fb.button({ action: 'subst:autobiografia', text: 'autobiografia', title: 'Não crie autobiografias', prompt: 'Qual autobiografia foi criada?' }) ].join(' '), /** Submenu [CatScan] **/ cat: 'Procurar nesta categoria: ' + [ '<a class="fb-button" href="' + fb.catScanUrl + 'ts&templates=Sem-fontes">sem fontes</a>', '<a class="fb-button" href="' + fb.catScanUrl + 'ts&templates=Revis%C3%A3o&go=">revisão</a>', '<a class="fb-button" href="' + fb.catScanUrl + 'ts&templates=Wikifica%C3%A7%C3%A3o&go=">wikificação</a>', '<a class="fb-button" href="' + fb.catScanUrl + 'ss&size=1000&stubop=or&links=4&go=">menos de 1 000 bytes ou 4 links</a>', '<a class="fb-button" href="' + fb.catScanUrl + 'ss&size=500&stubop=or&links=2&go=">menos de 500 bytes ou 2 links</a>' ].join(' ') };

// TODO: Consider using jQuery: $('#target').keypress() fb.ok = function( evt, option ) { if (window.event && window.event.keyCode == 13) { evt = 'ok'; } else if (evt && evt.which == 13) { evt = 'ok'; } if (evt == 'ok') { if ( option == 'esb' ) { fb.run('esboço-' + $( '#fb-esb-input').val()); } else if ( option == 'ESR' ) { fb.run('subst:ESR', $( '#fb-esr-input').val() + ' ~~' + '~~'); } } };

/* Patrol the edit currently displayed

* @param {function()} succes Callback function to be executed after the edit is pattroled
*/

fb.patrolRevision = function ( rcid, success ) { $.getJSON( mw.util.wikiScript( 'api' ), { format: 'json', action: 'query', list: 'recentchanges', rctoken: 'patrol', rcprop: , rclimit: '1' }, function( data ) { var query = data.query, rc = query && query.recentchanges, token = rc && rc[ 0 ] && rc[ 0 ].patroltoken; if ( !token ) { mw.log( 'Não foi possível obter um token para patrulhar a edição.' ); return false; } else if ( !rcid ) { mw.log( 'Não foi possível identificar a edição a ser patrulhada.' ); return false; } $.post( mw.util.wikiScript( 'api' ), { action: 'patrol', format: 'json', token: token, rcid: rcid }, function( data ) { if ( data.error ) { mw.log( 'Não foi possível patrulhar a edição: ' + data.error.info ); return false; } else { if ( $.isFunction( success ) ){ success(); } mw.log( 'A edição foi marcada como patrulhada.' ); return true; } } ).error(function() { alert( 'Houve um erro inesperado ao usar a API do MediaWiki.' ); return false; }); } ).error(function() { alert( 'A API retornou um erro ao tentar obter um token para patrulhar a edição.' ); return false; }); };

/* Função de edição

* @param: {string} code A template name, possibly preceded by "subst:",
*                         and optionally followed by "|" and some parameter(s)
* @param: {(string|null)=} extraText Extra text for templates and redirects (optional)
* @return: {boolean} Returns false if the user canceled or the page already has a template
*/

fb.run = function (code, extraText) { var $patrol, rcid, $textBox = $('#wpTextbox1'), summaries = { 'subst:VDA': 'Página marcada como VDA', 'subst:apagar': 'Página proposta para [[Wikipedia:Eliminação' + ' por votação|eliminação por votação]]', 'subst:s-fontes': 'Página marcada como sem fontes', 'subst:wkf': 'Página marcada para wikificação', 'subst:rec': 'Página marcada para reciclagem', 'parcial': 'Página marcada como parcial', 'subst:ctx': 'Página marcada como sem contexto', 'controverso|artigo': 'Marcado como controverso', 'subst:f-referências': 'Marcado que existem referências sem formatação', 'subst:m-notas': 'Marcado que carece de mais fontes', 'subst:s-notas': 'Página marcada como sem notas', 'subst:s-fontes-bpv': 'Marcado como biografia de pessoa' + ' viva sem fontes', 'subst:fpr': 'Página marcada como sem fontes secundárias fiáveis', 'subst:ESR': 'Página proposta para eliminação semirrápida' }; if (extraText === null) { // Do nothing if the user canceled the prompt box return false; } switch (mw.config.get('wgAction')) { case 'view': var url = mw.util.wikiGetlink( mw.config.get('wgPageName') ) + '?', data = { 'action': 'edit', 'fastb': code }; if( extraText ){ data.fbtxt = extraText; } $patrol = mw.util.$content.find('span.patrollink a').first(); rcid = mw.util.getParamValue( 'rcid', $patrol.attr('href') || ); if ( rcid ) { fb.patrolRevision( rcid, function(){ location.href = url + $.param( data ); } ); } else{ location.href = url + $.param( data ); } break; case 'edit': var value = $textBox.val(); var summary = ' (usando FastButtons)'; if ( value.match(/\{\{(?:ER|ESR2|Usuário\:Salebot\/Impróprio)\|/i) ) { alert('Já existe uma predefinição de eliminação nesta página.'); return false; } if (code.indexOf('ER') === 0) { extraText = extraText? '|3=' + extraText: ; extraText = '{' + '{' + code + '|2=~~' + '~~' + extraText + '}}\n\n'; $textBox.val( extraText + value ); if (this.salve) { document.editform.wpSummary.value = 'Página proposta para' + ' eliminação rápida (regra ' + code.substring(3) + ')' + summary; } } else if (code == 'redirect') { if (mw.config.get('wgNamespaceNumber') == 14) { if (extraText) { $textBox.val( '{' + '{redirecionamento de categoria|' + extraText + '}}' ); } if (this.salve) { document.editform.wpSummary.value = 'Redirecionando para' + ' a ' + summary; } } else { if (extraText) { $textBox.val( '#Redirecionamento ' + extraText + '' ); } } } else { extraText = extraText? '|1=' + extraText: ; extraText = '{' + '{' + code + extraText + '}}'; if (mw.config.get('wgNamespaceNumber') == 3) { value += '\n\n' + extraText + ' ~~' + '~~'; } else if (code == 'mínimo' || code.indexOf('esboço') === 0) { if (value.match(/\n\n\[\[/)) { value = value.substring(0, value.search(/\n\n\[\[/)) + '\n\n' + extraText + value.substring(value.search(/\n\n\[\[/)); } else { value += '\n\n' + extraText; } this.salve = (code == 'mínimo') ? 'Página marcada como mínimo' : 'Página marcada como esboço'; } else if ($.inArray( code, [ 'subst:VDA' , 'subst:matrad' ]) > -1) { value = extraText; } else { value = extraText + '\n\n' + value; } $textBox.val(value ); if (this.salve) { if (mw.config.get('wgNamespaceNumber') == 3) { this.salve = 'Adicionando aviso'; } else { if ( code.indexOf( 'subst:ESR' ) === 0 ) { code = 'subst:ESR'; } this.salve = summaries[ code ] || 'Adicionando marcação'; } document.editform.wpSummary.value = this.salve + summary; } } if (this.salve) { document.editform.submit(); } break; } };

/* Changes the content of the submenu

* @param {string} html The HTML code for the new submenu
*/

fb.changeSubmenu = function ( html ) { fb.$submenu.html( html ); mw.loader.using( 'jquery.tipsy', function() { $('#fb-submenu').find( 'a' ).tipsy(); } ); };

/* Callback function for API calls

* @param {string} code An abreviation such as "esb", "afl", "PV",
*/

fb.callAPI = function ( code ) { var user, that = this, esb, apiParams = { 'esb': { 'list': 'allpages', 'aplimit': '1', 'apnamespace': '10' }, 'afl': { 'list': 'backlinks', 'bllimit': '1', 'blfilterredir': 'nonredirects', 'blnamespace': '0', 'bltitle': mw.config.get('wgPageName') }, 'PV': { 'list': 'watchlist', 'wlprop': 'user|comment|title|sizes', 'wlexcludeuser': mw.config.get('wgUserName') }, 'PN': { 'list': 'recentchanges', 'rctype': 'new', 'rcnamespace': '0', 'rcshow': '!patrolled', 'rcprop': 'user|comment|title|sizes|ids' }, 'MR': { 'list': 'recentchanges', 'rctype': 'edit', 'rcnamespace': '0', 'rcshow': 'anon', 'rcprop': 'user|comment|title|sizes' }, 'usu': { 'list': 'allusers', 'aulimit': '1', 'auprop': 'editcount|registration', 'aufrom': mw.config.get('wgTitle').split('/')[0] } }; if ( 'esb' == code ) { esb = $( '#fb-esb-input' ).val(); if ( $.inArray( esb, [ esbText, esbText2 ] ) !== -1 ) { return; } esbText = esb; if (esbText == esb.substr(0, (esb.length - 1))) { return; } apiParams.esb.apprefix = 'Esboço-' + esb; } apiParams[ code ].format = 'json'; apiParams[ code ].action = 'query'; $.getJSON( mw.util.wikiScript( 'api' ), apiParams[ code ], function( data ) { that.processAPI( code, data ); } ); };

/* Callback function for API calls

* @param {string} code An abreviation such as "esb", "afl", "PV",
* @param {Object} data JSON content returned by API
*/

fb.processAPI = function (code, data) { var i, title, length, comment, user, quality, query = data && data.query, pages = [], charnum = 0, that = this;

/** Processamento da resposta do API **/ switch ( code ) { case 'afl': var backlinks, info = '('; info += (document.getElementById('Refer.C3.AAncias') || document.getElementById('Notas_e_refer.C3.AAncias')) ? 'ref' : 'ref'; var catLine = document.getElementById( 'mw-normal-catlinks' ); // FIXME: Não usar 'screen scraping' para obter esta informação! if (catLine && catLine.innerHTML.indexOf( '><a href="' + mw.config.get('wgArticlePath').replace('$1', )) > -1) { info += ' · cat'; } else { info += ' · cat'; } info += ( $( '#p-lang' ).length ) ? ' · iw' : ' · iw';

// Afluentes backlinks = query && query.backlinks; if ( !backlinks ) { mw.log( 'The backlinks query returned no data.' ); } else if ( backlinks.length ) { info += ' · <a href="' + mw.util.wikiGetlink( 'Especial:Páginas afluentes/' + mw.config.get('wgPageName') ) + '" title="afluentes">afl</a>)'; } else { info += ' · afl)'; } this.changeSubmenu( info ); if ( $( '#ca-talk' ).hasClass('new') ) { $.getJSON( mw.util.wikiScript( 'api' ), { 'format': 'json', 'action': 'query', 'prop': 'categories', 'indexpageids': '1', 'titles': mw.config.get('wgFormattedNamespaces')[ mw.config.get('wgNamespaceNumber') + 1 ] + ':' + mw.config.get('wgTitle') }, function( data ) { that.processAPI( 'qualidade', data ); } ); } else { var $hiddenCats = $('#mw-hidden-catlinks'); if ( $hiddenCats.length ) { quality = $hiddenCats.html(); if (quality.indexOf('!Artigos de qualidade') > -1) { quality = quality.substr(quality.indexOf('!Artigos de qualidade') + 22, 1); if (quality == 'd') { quality = '?'; } this.changeSubmenu( this.$submenu.html() + ' Q-' + quality + '' ); } } } break; case 'qualidade': var cats, cat, pageids; if ( query ) { cats = query.pages; pageids = query.pageids; if ( cats && pageids && pageids.length ) { cats = cats[ pageids[0] ].categories; if ( !cats ){ mw.log( 'The categories query returned incomplete data.' ); return false; } } else { mw.log( 'The categories query returned incomplete data.' ); return false; } } else { mw.log( 'The categories query returned no data.' ); return false; } // Qualidade do artigo for (i = 0; i < cats.length; i++) { cat = cats[i].title; if ( cat && cat.indexOf( '!Artigos de qualidade' ) > -1 ){ // Categoria:!Artigos de qualidade 1 sobre ... // ^ quality = cat.substr( 32, 1 ); if (quality == 'd') { quality = '?'; } this.changeSubmenu( this.$submenu.html() + ' Q-' + quality + '' ); break; } } break; case 'esb': var template, esb = document.getElementById( 'fb-esb-input' ); if ( query ) { template = query.allpages && query.allpages[0] && query.allpages[0].title; if ( !template ) { mw.log( 'The categories query returned incomplete data.' ); return false; } template = template.replace( /^Predefinição:Esboço-/gi, ); } else { mw.log( 'The categories query returned no data.' ); return false; } if ((esb.setSelectionRange || esb.createTextRange || typeof (esb.selectionStart) != 'undefined' && typeof (esb.selectionEnd) != 'undefined' ) && esb.value == template.substr(0, esb.value.length) ) { // Exibe sugestões. Baseado no script do HotCat var start = esb.value.length; esb.value = template; esbText2 = template; if (esb.setSelectionRange) { esb.setSelectionRange(start, template.length); } else if (esb.createTextRange) { var sel = esb.createTextRange(); sel.move( 'character', start ); sel.moveEnd( 'character', template.length - start ); sel.select(); } else { esb.selectionStart = start; esb.selectionEnd = template.length; } } break; case 'PN': case 'MR': // Mudanças recentes case 'PV': // Páginas vigiadas var item, j, listName = { 'PV': 'watchlist', 'MR': 'recentchanges', 'PN': 'recentchanges' }, summaryChanges = { 'PV' : [ [ '', ], [ '/*', '→' ], [ '*/', ':' ] ], 'MR' : [ [ '/*', '→' ], [ '*/', ':' ] ], 'PN' : [ [ '? ', ] ] }, urlParam = { 'PV': 'diff=last', 'MR': 'diff=last', 'PN': 'redirect=no&rcid=' }, list = query[ listName[ code ] ], max = ( list.length < 10 )? list.length : 10;

for ( i = 0; i < max; i++ ) { item = list[ i ]; if ( !item ){ continue; } title = item.title; charnum += title.length; if (charnum > 180) { break; } length = item.newlen - item.oldlen; if (length > 0) { length = '+' + length; } comment = item.comment || ; for ( j=0; j < summaryChanges[ code ].length; j++ ){ comment = comment.replace( summaryChanges[ code ][0], summaryChanges[ code ][1] ); } if (comment) { comment = '(' + comment + ')'; } if ( code === 'PN' ){ urlParam[ code ] += item.rcid; } pages.push( '<a href="' + mw.util.wikiGetlink( title ) + '?' + urlParam[ code ] + '" title="(' + length + ') ' + item.user + ' ' + comment + '">' + title + '</a>' ); }

this.changeSubmenu( '

' + pages.join( ' ' ) + '

' );

break; case 'usu': // Informações do(a) usuário(a) if ( !query ) { mw.log( 'The categories query returned no data.' ); return false; } user = query.allusers && query.allusers[0]; if ( user ) { // Ex.: YYYY-MM-DDThh:mm:ssZ var regDate = user.registration; regDate = regDate.substr(8, 2) + '/' + regDate.substr(5, 2) + '/' + regDate.substr(0, 4); var encUser = encodeURI( user.name ); this.changeSubmenu( [ user.editcount + ' edições desde ' + regDate + '.', '<a class="fb-button" href="' + mw.util.wikiGetlink( 'Especial:Contribuições/' ) + encUser + '" title="Abrir a lista de contribuições deste editor" >contribuições</a>', '<a class="fb-button" href="' + mw.util.wikiGetlink( 'Especial:Registo/' ) + encUser + '" title="Abrir a lista de registros deste editor" >registros</a>', '<a class="fb-button" href="' + mw.util.wikiGetlink( 'Especial:Registo' ) + '?type=block&page=User%3A' + encUser + '" title="Abrir a lista de registros de bloqueio deste editor">registros de bloqueio</a>', '<a class="external text fb-button"' + 'title="Abrir a contagem de edições deste editor"' + ' href="http://toolserver.org/~river/cgi-bin/count_edits?user=' + encUser + '&dbname=' + mw.config.get('wgDBname') + '_p">contador de edições</a>' ].join( ' ' ) ); } else { return; } break; } };

/* Initialize the gadget */ fb.init = function () { var inUserNS, param = mw.util.getParamValue('fastb'); if ($.inArray(mw.config.get('wgAction'), ['view', 'edit']) !== -1) { fb.changeSubmenu( ); /*** Menu Principal ***/ if (mw.config.get('wgNamespaceNumber') > -1) { inUserNS = $.inArray(mw.config.get('wgNamespaceNumber'), [2, 3]) > -1 && mw.config.get('wgTitle').indexOf(mw.config.get('wgUserName')) === 0; if (inUserNS) { fb.$menu.html( fb.button({ action: 'ER|1', text: 'ER1', title: 'Marcar subpágina do próprio usuário para eliminação' }) ); } else { // FIXME: Usar jQuery em vez de onClick, para melhor compatiblidade (mw:RL/MGU#Event_binding) fb.$menu.html( '<a class="fb-button fb-menu-button" title="Exibir regras' + ' para a eliminação rápida" onClick="fb.changeSubmenu(fb.submenu.ER)">ER</a>' ); } } if ($.inArray(mw.config.get('wgNamespaceNumber'), [0, 102]) !== -1) { fb.$menu.html( fb.$menu.html() + [ '<a class="fb-button fb-menu-button" title="Exibir regras para a eliminação semi-rápida"' + ' onClick="fb.changeSubmenu(fb.submenu.ESR)">ESR</a>', fb.button({ action: 'subst:apagar', text: 'PE', title: 'Marcar para eliminação por votação' }), '<a class="fb-button fb-action-button"' + ' title="Marcar como cópia ou violação de direito autoral"' + ' onClick="obs=prompt(\'Informe o url da página copiada\',' + ' \'http://\');fb.run(\'subst:VDA\',obs)">VDA</a>', fb.button({ action: 'subst:suspeito', text: 'susp', title: 'Marcar como suspeito de violação de direitos autorais' }), fb.button({ action: 'subst:matrad', text: 'trad', title: 'Marcar esta tradução como sendo de baixa qualidade', prompt: 'De qual língua a página foi maltraduzida (ca, de, en, es,' + ' fr, it, ja, nl, no, pl, ru, sv, zh)?' }), fb.button({ action: 'redirect', text: '#R', title: 'Redirecionar para outro título', prompt: 'Redirecionar para qual página?' }), '<a class="fb-button fb-menu-button" title="Exibir predefinições para manutenção"' + ' onClick="fb.changeSubmenu(fb.submenu.man)">manutenção</a>', '<a class="fb-button fb-menu-button" title="Exibir predefinições para esboços"' + ' onClick="fb.changeSubmenu(fb.submenu.esb)">esboço</a>', '<a class="fb-button fb-menu-button" title="Exibir opções para a busca de fontes"' + ' onClick="fb.changeSubmenu(fb.submenu.search)">busca</a>' ].join() ); if (mw.config.get('wgAction') === 'view') { fb.callAPI('afl'); } } else { if ($.inArray(mw.config.get('wgNamespaceNumber'), [2, 10]) !== -1) { fb.$menu.html( fb.$menu.html() + fb.button({ action: 'subst:apagar', text: 'PE', title: 'Marcar para eliminação por votação' }) ); } if (mw.config.get('wgNamespaceNumber') % 2 === 0) { fb.$menu.html( fb.$menu.html() + fb.button({ action: 'redirect', text: '#R', title: 'Redirecionar para outro título', prompt: 'Redirecionar para qual página?' }) ); } if (mw.config.get('wgNamespaceNumber') === 14) { // FIXME: Usar jQuery em vez de onClick, para melhor compatiblidade (mw:RL/MGU#Event_binding) fb.$menu.html( fb.$menu.html() + '<a class="fb-button fb-menu-button"' + ' title="Exibir opções do CatScan para procurar páginas nesta categoria"' + ' onClick="fb.changeSubmenu(fb.submenu.cat)">CatScan</a>' ); } } if (mw.config.get('wgNamespaceNumber') === 3) { // FIXME: Usar jQuery em vez de onClick, para melhor compatiblidade (mw:RL/MGU#Event_binding) fb.$menu.html( fb.$menu.html() + '<a class="fb-button fb-menu-button"' + ' title="Exibir lista de predefinições para avisos"' + ' onClick="fb.changeSubmenu(fb.submenu.warn)">aviso</a>' ); } if ($.inArray(mw.config.get('wgNamespaceNumber'), [2, 3]) !== -1) { // FIXME: Usar jQuery em vez de onClick, para melhor compatiblidade (mw:RL/MGU#Event_binding) fb.$menu.html( fb.$menu.html() + '<a class="fb-button fb-menu-button" title="Exibir informações sobre esta conta"' + ' onClick="fb.callAPI(\'usu\')">sobre a conta</a>' ); } } // FIXME: Usar jQuery em vez de onClick, para melhor compatiblidade (mw:RL/MGU#Event_binding) fb.$menu.html( fb.$menu.html() + [ '<a class="fb-button fb-menu-button"' + ' title="Exibir páginas vigiadas que foram alteradas recentemente" onClick="fb.callAPI(\'PV\')">PV</a>', '<a class="fb-button fb-menu-button"' + ' title="Exibir páginas novas que ainda não foram patrulhadas"' + ' onClick="fb.callAPI(\'PN\')">PN</a>', '<a class="fb-button fb-menu-button"' + ' title="Exibir mudanças recentes feitas por IPs em páginas do domínio principal"' + ' onClick="fb.callAPI(\'MR\')">MR</a>' ].join() ); if( mw.config.get('skin') == 'modern' ){ $( '#contentSub' ).before( fb.$menu ).before( fb.$submenu ); } else { $( 'h1' ).first().after( fb.$submenu ).after( fb.$menu ); }

switch (mw.config.get('wgAction')) { case 'edit': fb.salve = (param !== null); if (fb.salve) { fb.run(param, mw.util.getParamValue('fbtxt') || ); } break; case 'markpatrolled': if (param !== null) { location.href = mw.util.wikiGetlink( mw.config.get('wgPageName') ) + '?action=edit&fastb=' + param; } break; default: // Não faz nada nas demais ações } mw.loader.using( 'jquery.tipsy', function() { $('#fb-menu').find( 'a' ).tipsy(); } ); };

/* Executes the gadget when document is ready */ $( fb.init );