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

(Diferenças entre páginas)
Conteúdo apagado Conteúdo adicionado
pedido pelo Helder na discussão: http://pt.wikipedia.org/w/index.php?diff=24260973&oldid=23916095
 
m Atualização da MediaWiki:Wikibugs.js com base nas atualizações recentes feitas ao original da pl:MediaWiki:Gadget-wikibugs.js por pl:User:Beau
 
Linha 1: Linha 1:
/*
/*
* Fonte original: http://pl.wikipedia.org/wiki/MediaWiki:Wikibugs.js
* Source: [[:pl:MediaWiki:Gadget-wikibugs.js]]
* @author: [[:pl:User:Dodek]] (idea and text)
* Adaptação para o russo: [[:ru:User:Александр Сигачёв]], [[:ru:User:Putnik]], [[:ru:User:LEMeZza]]
* Adaptação para o inglês: [[:ru:User:Claymore]]
* @author: [[:pl:User:Adziura]] (idea and text)
* Adaptação para o espanhol: [[:es:User:Emijrp]]
* @author: [[:pl:User:Nux]] (implementation)
* @author: [[:pl:User:Saper]] (implementation)
* Adaptação para o português: [[:pt:Usuário:ChristianH]]
* @author: [[:pl:User:Beau]] (implementation)
*
* Ideia original: [[:pl:User:Dodek]], [[:pl:User:Adziura]]
* @author: [[:pt:User:ChristianH]] (Portuguese version)
* Implementação: [[:pl:User:Nux]], [[:pl:User:Saper]], [[:pl:User:Beau]], [[:ru:User:Putnik]]
*/
*/
/* Translatable strings */
mw.messages.set( {
'wikibugs-dialog-title': 'Informar um erro',
'wikibugs-open-form-button': 'Informar',
'wikibugs-edit-page-button': 'Editar a página e corrigir o erro',
'wikibugs-cancel-button': 'Cancelar',
'wikibugs-submit-report-button': 'Enviar',
'wikibugs-ip-address-notice': '<b>Observação:</b> Seu endereço de IP' +
' ficará armazenado no histórico de notificações.',
'wikibugs-page-name-label': 'Nome da página:<br/><small>(juntamente com' +
' o prefixo "Imagem:" se estiver informando um erro em uma imagem ou' +
' outro tipo de ficheiro/arquivo</small>',
'wikibugs-report-content-label': 'Detalhes sobre o erro:<br><small>' +
'<u>Não</u> deixe seu número de telefone, e-mail ou qualquer outro dado pessoal</small>',
'wikibugs-report-content-placeholder': 'Explique aqui o problema detalhadamente e,' +
' se possível, indique uma referência onde se possa confirmar a informação',
'wikibugs-signature-label': 'Assinatura:',
'wikibugs-edit-error': 'Ocorreu um erro ao enviar a notificação. Por favor, tente novamente.',
'wikibugs-incomplete-information': 'Descreva detalhadamente qual é o erro. Não coloque informações incompletas.',
'wikibugs-invalid-page': 'Informe um nome válido para a página.',
'wikibugs-reported-by': ' Enviado por: $1',
'wikibugs-file-section-line': '<!-- Erros nas imagens a partir desta linha. Itens mais recentes no topo. -->',
'wikibugs-page-section-line': '<!-- Erros nos artigos a partir desta linha. Itens mais recentes no topo. -->',
'wikibugs-bad-reports-text': '<p>Neste formulário <b>não são aceitos</b> pedidos' +
' para expandir ou criar artigos. Isso deve ser feito na página:</p>' +
'<ul><li><a href="' + mw.util.wikiGetlink('Wikipédia:Artigos pedidos') +
'">Artigos pedidos</a></li></ul><p><b>Não informe</b> erros em outros sites' +
' (como <b>Facebook</b> ou <b>Twitter</b>), pois não serão atendidos.' +
'<p>A Wikipédia não dá conselhos. Se precisa de aconselhamento,' +
' <b>não peça aqui</b>.</p><p>Para informações sobre como contactar a Wikipédia,' +
' consulte:</p><ul><li><a href="' + mw.util.wikiGetlink('Wikipédia:Contato') +
'">Contato</a></li></ul>',
'wikibugs-article-intro': '<p style="margin-top:0px;">É possível avisar' +
' sobre erros encontrados nos artigos da Wikipédia, mas lembre-se de' +
' que ela é uma <a href="' + mw.util.wikiGetlink('Wiki') +
'">wiki</a> e por isso até mesmo o leitor pode <a href="' +
mw.util.wikiGetlink('Wikipédia:Seja audaz') +
'">ser audaz e corrigir um erro</a> encontrado durante a leitura.' +
' No entanto, reconhecemos o fato de que alguns leitores da Wikipédia' +
' tem motivos para não quererem editar e aprimorar os artigos diretamente.</p>' +
'<p><b>Se puder corrigi o problema, não informe-o aqui.</b></p>',
'wikibugs-image-intro': '<p style="margin-top:0px;">Aqui é possível informar' +
' sobre imagens que violam os termos da licença, que possuem versões' +
' melhores no Wikimedia Commons, que estão descritas incorretamente, etc. </p>' +
'<p><b>Se puder corrigi o problema, não informe-o aqui.</b></p>',
'wikibugs-already-reported-notice': '<p><b>Observação:</b> Se informou um problema' +
' e agora ele já não existe, então provavelmente algum editor já o corrigiu.' +
' Consulte:<ul><li><a href="' + mw.util.wikiGetlink('Wikipédia:Informe um erro') +
'">A lista atual de problemas informados</a> e</li><li><a href="' +
mw.util.wikiGetlink('Wikipédia:Informe um erro') +
'?action=history">O histórico de modificações da página.</a></li></ul></p>',
'wikibugs-footer': '<p>Leia os <a href="http://wikimediafoundation.org/wiki/' +
'Condições_de_Uso" target="_blank">termos de uso</a> e a <a href="' +
'http://wikimediafoundation.org/wiki/Política_de_privacidade"' +
' target="_blank">política de privacidade</a> da Wikipédia.</p>'
});
var wikiBugsGadget = {


/**
// As seguintes páginas serão excluídas e o botão não será mostrado
* Version number of this gadget.
paginasExcluidas = new Array(
*/
"Wikipédia:Informe_um_erro"
version: 2,
);
/**
* The page on which are written notification.
*/
reportPage: 'Wikipédia:Informe um erro',
/**
* List of page titles which may not relate to the gadget.
*/
badPages: [
'Wikipédia:Informe um erro'
],
/**
* Define pages where it's not needed or tends to encourage submission of large
* volumes of unrelated errors; instead, these load CSS which hides the "Report A Bug" link
*/
excludedPages: [
// 'Wikipédia:Página principal'
],
/**
* Communication to the pages in the main space.
*/
articleIntro: '<div id="wbBadReports">' +
mw.msg( 'wikibugs-bad-reports-text' ) + '</div>' +
mw.msg( 'wikibugs-article-intro' ) +
mw.msg( 'wikibugs-already-reported-notice' ) +
mw.msg( 'wikibugs-footer' ),


/**
if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [-1, 6, 7, 8] ) > -1 ) {
* Message to the parties in the space of a file.
importStylesheet('MediaWiki:Wikibugs.css');
*/
} else {
imageIntro: '<div id="wbBadReports">' +
for (var i=paginasExcluidas.length; i>=0; i--) {
mw.msg( 'wikibugs-bad-reports-text' ) + '</div>' +
if (mw.config.get( 'wgPageName' )===paginasExcluidas[i]) {
mw.msg( 'wikibugs-image-intro' ) +
importStylesheet('MediaWiki:Wikibugs.css');
mw.msg( 'wikibugs-already-reported-notice' ) +
break;
mw.msg( 'wikibugs-footer' ),
}
}
}


/**
var wb$description = "Que erro encontrou? Descreva-o aqui com o maior detalhe possível. Se possível, indique uma referência onde se possa confirmar a informação";
* Function to check whether it should be accepted a report about the provided page.
function wb$getEditToken(page)
* @param name Page name
{
*/
var objhttp = (window.XMLHttpRequest) ? new XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP');
isValidPageName: function (name) {
if (!objhttp) {
if (name === '') {
return;
return false;
}
}
objhttp.onreadystatechange=function() {
if (name.indexOf( mw.config.get('wgFormattedNamespaces')[ '-1' ] ) === 0) {
if (objhttp.readyState === 4) {
return false;
if (objhttp.status === 200) {
}
var r_sti = /value="(\d+)" name=["']wpStarttime["']/,
name = name.replace(/_/g, ' ');
r_eti = /value="(\d+)" name=["']wpEdittime["']/,
r_etk = /value="(.*?)" name=["']wpEditToken["']/,
r_asm = /name="wpAutoSummary" type="hidden" value="(.*?)"/,
sti = r_sti.exec(objhttp.responseText),
eri = r_eti.exec(objhttp.responseText),
etk = r_etk.exec(objhttp.responseText),
asm = r_asm.exec(objhttp.responseText);
document.getElementById('Starttime').value=sti[1];
document.getElementById('Edittime').value=eri[1];
document.getElementById('EditToken').value=etk[1];
document.getElementById('AutoSummary').value=asm[1];
}
else {
alert(objhttp.status);
}
}
};
objhttp.open('GET', mw.config.get( 'wgServer' )+mw.config.get( 'wgScript' )+"?title="+encodeURIComponent(page)+"&action=edit");
objhttp.send("");
}


return $.inArray( name, this.badPages ) == -1;
function wb$isValidPageName(name)
},
{
if (name==="") {
return false;
} else {
return true;
}
}


/**
function wb$popBugBoth(action_page, infoHTML)
* This function initiates the action of the gadget.
{
*/
var glob = document.body,
init: function() {
can_edit;
var excluded = false,
$link, name, $articleBugLink, $imageBugLink,
that = this;


// Special pages and MediaWiki pages are excluded
// shadow
if ($.inArray( mw.config.get('wgNamespaceNumber'), [ -1 , 8 ]) > -1) {
var nel = document.createElement('div');
excluded = true;
nel.id='specpop-globhidden';
} else {
nel.style.cssText = 'background:white;filter:alpha(opacity=75);opacity:0.75;position:absolute;left:0px;top:0px;z-index:2000';
name = mw.config.get('wgPageName').replace(/_/g, ' ');
nel.style.width = document.documentElement.scrollWidth+'px';
excluded = $.inArray( name, this.excludedPages ) != -1;
nel.style.height= document.documentElement.scrollHeight+'px';
}
glob.appendChild(nel);
// FIXME: This doesn't exists on "standard", "cologneblue" (no ids) and "nostalgia" (no sidebar)
$articleBugLink = $('#n-bug_in_article');
$imageBugLink = $('#n-bad-image');
that = this;


if (excluded) {
// move the dialog
// hide the link
window.scroll(0, 150);
if ($articleBugLink) {
$articleBugLink.hide();
}
if ($imageBugLink) {
$imageBugLink.hide();
}
return;
}
if ($articleBugLink) {
$link = $articleBugLink.find('a')
.attr( 'href', '#' )
.click( function (event) {
that.open(that.articleIntro);
event.preventDefault();
} );
}
if ($imageBugLink) {
$link = $imageBugLink.find('a')
.attr( 'href', '#' )
.click( function (event) {
that.open(that.imageIntro);
event.preventDefault();
} );
}


//link on the report-an-error page itself
// information
$('#report-bug-link a').click(function(event) {
var edit_el = document.getElementById('ca-edit');
that.open(that.articleIntro);
if (edit_el) {
event.preventDefault();
can_edit = true;
});
} else {
importStylesheet('MediaWiki:Gadget-wikibugs.css');
can_edit = false;
}
},
/**
* Move to the edit page.
*/
goToEditPage: function() {
var $editLink = $( '#ca-edit' ).find( 'a' ),
url = $editLink.attr( 'href' ) || mw.util.wikiGetlink( this.reportPage );
window.location = url;
},
/**
* Loads the user interface.
* @param infoHtml Message content.
*/
open: function(infoHtml) {
var that = this;


mw.loader.using('jquery.ui.dialog', function() {
nel = document.createElement('div');
that.openDialog(infoHtml);
nel.id='specpop-info';
}); // FIXME: this should be loaded as gadget dependency
nel.style.cssText = 'font-size:13px;background:white;padding:21px 30px;border:1px solid black;position:absolute;width:520px;min-height:300px;top:200px;z-index:2002';
},
if (nel.style.maxHeight===undefined) {
/**
nel.style.height='300px'; // IE blah
* Shows the dialog.
}
* @param infoHtml Message content.
var tmp = Math.floor(glob.clientWidth/2)-300;
*/
if (tmp<5) {
openDialog: function(infoHtml) {
tmp = 5;
var that = this,
}
edit_el = document.getElementById('ca-edit'),
nel.style.left = tmp+'px';
can_edit = edit_el ? true : false,
$dialog = $('<div id="dialogContent"></div>').append(infoHtml);


if (mw.user.anonymous()) {
nel.innerHTML = infoHTML;
$dialog.append( '<p>' + mw.msg( 'wikibugs-ip-address-notice' ) + '</p>' );
if (mw.config.get( 'wgUserName' ) === null) {
}
nel.innerHTML = nel.innerHTML + '<p><b>Atenção:</b> o seu endereço de IP será registrado e poderá ser visto no histórico. Se quiser, crie uma <a href="http://pt.wikipedia.org/w/index.php?title=Especial:Entrar&type=signup" target="_blank">conta de usuário</a>.</p>';
}
nel.innerHTML += '<p style="text-align:center;margin-top:15px">'
+ (can_edit ? '<input type="button" value="Vou corrigi-lo" onclick="wb$goToEditPage()" />' : '')
+ '<input type="button" value="Informar sobre o erro" onclick="wb$elementsRemove(\'specpop-info\')" />&nbsp;&nbsp;&nbsp;'
+ '<input type="button" value="Cancelar" onclick="wb$elementsRemove(\'specpop-info\',\'specpop-form\',\'specpop-globhidden\',\'specpop-pos\')" />'
+ '</p>';
glob.appendChild(nel);


var buttons = {};
var action_url = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + "?title=" +encodeURIComponent(action_page) + "&action=submit";
buttons[mw.msg( 'wikibugs-cancel-button' )] = function() {
$(this).dialog('close');
};
buttons[mw.msg( 'wikibugs-open-form-button' )] = function() {
that.openForm(this);
};
if (can_edit) {
buttons[mw.msg( 'wikibugs-edit-page-button' )] = function() {
that.goToEditPage();
};
}


$dialog.dialog( {
// form
width: 700,
nel = document.createElement('div');
height: 500,
nel.id = 'specpop-form';
modal: true,
nel.style.cssText = 'background:white;padding:5px 10px;border:1px solid black;position:absolute;width:330px;min-height:300px;top:200px;z-index:2001';
resizable: false,
if (nel.style.maxHeight===undefined) {
draggable: true,
nel.style.height='300px'; // IE blah
closeOnEscape: true,
}
dialogClass: 'reportBugDialog',
nel.style.left = (Math.floor(glob.clientWidth/2)-165)+'px';
title: mw.msg( 'wikibugs-dialog-title' ),
//nel.style.top = (this.offsetTop-100)+'px'
close: function() {
nel.innerHTML = '<form id="fm1" action="'+action_url+'" method="post" enctype="multipart/form-data" onsubmit="return wb$checkForm(this)">'
var $this = $(this);
+ 'Página:<br /><input type="text" name="wpSummary" id="wpSummary" width="320px" /><br />'
$this.dialog('destroy');
+ '<input type="hidden" name="wpSection" value="new" />'
$this.remove();
+ '<input type="hidden" name="wpSave" value="Save" />'
},
+ '<input type="hidden" id="Starttime" name="wpStarttime" value="" />'
buttons: buttons
+ '<input type="hidden" id="Edittime" name="wpEdittime" value="" />'
});
+ '<input type="hidden" id="EditToken" name="wpEditToken" value="" />'
$('div.reportBugDialog button:last').focus();
+ '<input type="hidden" id="AutoSummary" name="wpAutoSummary" value="" />'
},
+ '<input type="hidden" name="wpScrolltop" value="0" />'
/**
+ 'Mensagem:<br /><textarea id="TextBox" name="wpTextbox1" style="width:320px;height:200px" onfocus="if (this.value == wb$description) {this.value = \'\'}">' + wb$description + '</textarea><br />'
* Shows a window with the form.
+ '<input type="submit" id="submit" value="Enviar" /> &nbsp; '
*/
+ '<input type="button" value="Cancelar" onclick="wb$elementsRemove(\'specpop-form\',\'specpop-globhidden\',\'specpop-pos\')" />'
openForm: function(dialog) {
+ '</form>';
var that = this,
glob.appendChild(nel);
buttons = {};
if (wb$isValidPageName(mw.config.get( 'wgPageName' ))) {
$('#dialogContent').empty().append(
document.getElementById('wpSummary').value = mw.config.get( 'wgPageName' ).replace(/_/g, " ");
'<form name="WikibugForm" enctype="multipart/form-data">' +
}
'<fieldset>' +
wb$getEditToken(action_page);
'<label for="wbPageTitle">' + mw.msg( 'wikibugs-page-name-label' ) + '</label>' +
}
'<input id="wbPageTitle" type="text" name="wbPageTitle" class="text ui-widget-content ui-corner-all" />' +
'<label for="wbText">' + mw.msg( 'wikibugs-report-content-label' ) + '</label>' +
'<textarea id="wbText" name="wbText" rows="6" class="text ui-widget-content ui-corner-all">' +
mw.msg( 'wikibugs-report-content-placeholder' ) + '</textarea>' +
'<label for="wbAuthor">' + mw.msg( 'wikibugs-signature-label' ) + '</label>' +
'<input id="wbAuthor" type="text" class="text ui-widget-content ui-corner-all"/>' +
'</fieldset>' +
'<img id="wikibugs-loading-icon" src="http://upload.wikimedia.org/wikipedia/commons/4/49/Linux_Ubuntu_Loader.gif" style="display:none;"/>'+
'</form>'
);


buttons[mw.msg( 'wikibugs-cancel-button' )] = function() {
function wb$popWikibug()
$(this).dialog('close');
{
};
var link_wiki = mw.util.wikiGetlink( 'wiki' ),
buttons[mw.msg( 'wikibugs-submit-report-button' )] = function() {
link_tocreate = mw.util.wikiGetlink( 'Wikipedia:Artigos pedidos' ),
that.submitForm();
link_bebold = mw.util.wikiGetlink( 'Wikipedia:Seja audaz' ),
};
link_buglist = mw.util.wikiGetlink( 'Wikipedia:Informe um erro' );


$(dialog).dialog('option', 'buttons', buttons);
wb$popBugBoth("Wikipedia:Informe_um_erro",
'<p><b>Este formulário deve ser utilizado <u>unicamente</u> para informar erros em páginas da Wikipédia</b>.</p>'
+ '<div style="float:right;width:200px;padding:4px 10px;margin:2px 0px 0px 10px;font-size:90%;border:2px solid #900"><p><b>Não informe</b> erros em outros sites (como <b>Facebook</b> ou <b>Twitter</b>), pois não serão atendidos.</p>'
+ '<p>Por favor, não informe sobre artigos que não existem. Para isto, use a <a href="' + link_tocreate + '">página de artigos pedidos</a>.</p></div>'
+ '<p style="margin-top:0">Se encontrou um erro e tem ideia de como corrigir, tente o fazer, pois a <a href="' + link_wiki + '" target="_blank">tecnologia wiki</a> permite que qualquer pessoa possa <strong><a href="http://pt.wikipedia.org/wiki/Ajuda:Página_principal" target="_blank">editar artigos</a></strong>.</p>'
+ '<p>Não hesite caso encontre alguma informação errada, pois uma das nossas recomendações é para <a href="' + link_bebold + '" target="_blank">ser audaz</a>!</p>'
+ '<p>Se não pode ou não sabe como corrigir o erro, então siga este formulário.</p>'
+ '<p style="color:red"><b><u>Não</u> deixe seu número de telefone, e-mail ou qualquer outro dado pessoal</b>.</p>'
+ '<p><a href="' + link_buglist + '" target="_blank">Ver as notificações de erros atuais</a>.</p>'
+ '<p>Leia os <a href="http://wikimediafoundation.org/wiki/Condições_de_Uso" target="_blank">termos de uso</a> e a <a href="http://wikimediafoundation.org/wiki/Política_de_privacidade" target="_blank">política de privacidade</a>.</p>' );
return false;
}


addOnloadHook(function()
$('#wbText').focus(function() {
if (this.value == mw.msg( 'wikibugs-report-content-placeholder' )) {
{
this.value = '';
var el = document.getElementById('n-bug_in_article');
}
});


if (this.isValidPageName(mw.config.get('wgPageName'))) {
if (el) {
$('#wbPageTitle').val( mw.config.get('wgPageName').replace(/_/g, ' ') );
el.getElementsByTagName('a')[0].onclick = wb$popWikibug;
}
}
});


if ( !mw.user.anonymous() ) {
function wb$checkForm(form)
var author = document.getElementById('wbAuthor');
{
author.value = '~~'+'~~';
var page = form.wpSummary.value,
author.disabled = 'disabled';
content = form.wpTextbox1.value;
}
},
/**
* Sends the contents of the form.
*/
submitForm: function() {
var form = document.forms.WikibugForm,
page = form.wbPageTitle.value,
content = form.wbText.value,
that = this;


if (content==="" || content===wb$description || content.length<20 || !content.match(' ')) {
if (content == mw.msg( 'wikibugs-report-content-placeholder' )
|| content.length < 20
alert("Sua notificação é demasiada curta, por favor, adicione mais detalhes.");
|| !content.match(' ')
form.wpTextbox1.focus();
) {
return false;
// Description too short or unchanged
}
alert(mw.msg( 'wikibugs-incomplete-information' ));
form.wbText.focus();
return;
}
content = $.trim(content);


var pageTitle; // Title of the reported page
page = page.replace(/^http:\/\/pt\.wikipedia\.org\/wiki\/(.+)$/, "$1");
var isFile = false; // Is the reported page a file?
page = page.replace(/_/g, " ");
page = decodeURIComponent(page);


// Signature
if (page === mw.config.get( 'wgPageName' ).replace(/_/g, " ") && wb$isValidPageName(mw.config.get( 'wgPageName' ))) {
if (!mw.user.anonymous()) {
page = page.replace(/^(Categoria:|\/)/, ":$1");
content += mw.msg( 'wikibugs-reported-by', '~~'+'~~' );
page = "[["+page+"]]";
} else {
} else {
content += mw.msg( 'wikibugs-reported-by', form.wbAuthor.value + ' ~~'+'~~' );
page = page.replace(/\[\[([^\[\]\|]+)\|[^\[\]\|]+\]\]/g, "$1");
}
page = page.replace(/[\[\]\|]/g, "");
if (page == mw.config.get('wgPageName') && this.isValidPageName(mw.config.get('wgPageName'))) {
page = page.replace(/^\s+/g, "");
// User hasn't changed the page tilte - we're reporting the current page
page = page.replace(/\s+$/g, "");
pageTitle = mw.config.get('wgPageName');
page = page.replace(/_/g, ' ');
page = '[[:' + pageTitle + '|' + page + ']]';


isFile = (mw.config.get('wgNamespaceNumber') == 6);
if (! wb$isValidPageName(page) ) {
}
alert("Introduza o nome do artigo.");
else {
if ( wb$isValidPageName(mw.config.get( 'wgPageName' )) ) {
// User has changed the page title - we're reporting the manually-specified page
form.wpSummary.value = mw.config.get( 'wgPageName' );
page = page.replace(/_/g, ' ');
} else {
page = page.replace(/[\[\]\|]/g, '');
form.wpSummary.value = "";
page = $.trim(page);
form.wpSummary.focus();
}
return false;
}
if (page.indexOf(':') > 0) {
page = '[[:'+page+']]';
} else {
page = '[['+page+']]';
}
}


if (! this.isValidPageName(page) ) {
form.submit.disabled = 'disabled';
alert( mw.msg( 'wikibugs-invalid-page' ) );
if ( this.isValidPageName(mw.config.get('wgPageName')) ) {
form.wbPageTitle.value = mw.config.get('wgPageName');
} else {
form.wbPageTitle.value = '';
form.wbPageTitle.focus();
}
return;
}


pageTitle = page; // We're reporting the page specified manually by the user
content += '\r\n\r\nEnviado por: ~~'+'~~';
page = '[[:' + page + ']]';


var fileNS = ['File:'];
form.wpTextbox1.value = content;
$.each(mw.config.get('wgNamespaceIds'), function(name,id){
form.wpSummary.value = page;
// Get a list of aliases for "File:" namespace
if (id==6) {
fileNS.push(
$.escapeRE(
name.charAt(0).toUpperCase() + name.substr(1)
) + ':'
);
}
});
// Build a regex which match all aliases for "File:" namespace
var reFile = new RegExp( '^(?:' + fileNS.join('|') + ')' );
// Check if the user has typed a name of a file
isFile = reFile.test( pageTitle );
}


form.submit.disabled = 'disabled';
return true;
var loadingIcon = document.getElementById('wikibugs-loading-icon');
}
loadingIcon.style.display = 'inline';


var toInsert = '=== ' + page + ' ===\n' + content;
function wb$goToEditPage()
{
var edit_el = document.getElementById('ca-edit'),
edit_href = mw.config.get( 'wgArticlePath' ).replace(/\$1/, 'Wikipedia:Informe_um_erro');
if (edit_el) {
edit_href = edit_el.getElementsByTagName('a')[0].href;
}
window.location = edit_href;
}


function wb$elementsRemove()
function processContentOfPage( data ){
var query = data && data.query,
{
pages = query && query.pages,
var el;
pageids = query && query.pageids,
for (var i=arguments.length-1; i>=0; i--) {
sectionLine, firstPage, text;
el = document.getElementById(arguments[i]);
if (el) {
if (!pages || !pageids) {
alert( mw.msg( 'wikibugs-edit-error' ) );
el.parentNode.removeChild(el);
return false;
}
}
}
firstPage = pages[ pageids[0] ];
}
text = (firstPage && firstPage.revisions[0]['*']) || '';
// Process the wikitext of the page
if(isFile) {
sectionLine = mw.msg( 'wikibugs-file-section-line' );
} else {
sectionLine = mw.msg( 'wikibugs-page-section-line' );
}
var newText = text.replace(sectionLine, sectionLine + '\n\n' + toInsert);
if (text == newText) {
// Could not find the section line - simply append;
newText = text + '\n\n' + toInsert;
}
function afterEdit() {
//saved successfully - go to the report page
var reportPage = that.reportPage.replace(/ /g, '_');
window.location = mw.util.wikiGetlink(reportPage) + '#' +
encodeURIComponent(
encodeURI(pageTitle).replace(/%/g, '.')
).replace(/%/g, '.').replace(/\.3A/g, ':').
replace(/\.20/g, '_').
replace(/\(/g, '.28').replace(/\)/g, '.29');

if (mw.config.get('wgPageName') == reportPage) {
//we're already there
window.location.reload();
}
}
function getToken( data ){
var pageInfo;
if ( !data || !data.query || !data.query.pages || !data.query.pageids
|| !data.query.pages[ data.query.pageids[0] ] ) {
alert( mw.msg( 'wikibugs-edit-error' ) );
return false;
}
pageInfo = data.query.pages[ data.query.pageids[0] ];
// Save the new content
$.post(
mw.util.wikiScript( 'api' ), {
action: 'edit',
title: that.reportPage,
text: newText,
minor: false,
summary: 'Nova notificação: ' + page,
//starttimestamp: pageInfo.starttimestamp,
token: pageInfo.edittoken
}, afterEdit
).error(function() {
//handle the error
alert( mw.msg( 'wikibugs-edit-error' ) );
form.submit.disabled = '';
loadingIcon.style.display = 'none';
});
}
// Get a token befoe editing
$.getJSON(
mw.util.wikiScript( 'api' ), {
format: 'json',
action: 'query',
prop: 'info',
indexpageids: '1',
intoken: 'edit',
titles: that.reportPage
}, getToken
).error(function() {
alert( mw.msg( 'wikibugs-edit-error' ) );
});
}

$.getJSON(
mw.util.wikiScript( 'api' ), {
'format': 'json',
'action': 'query',
'titles': that.reportPage,
'prop': 'revisions',
'rvprop': 'content',
'indexpageids': '1'
}, processContentOfPage
);
}
};

$(function() {
wikiBugsGadget.init();
});