Diferencia entre revisiones de «MediaWiki:Gadget-Wikibugs.js»

De Wikipedia, la enciclopedia libre
Contenido eliminado Contenido añadido
Código adicional para que se pueda invocar desde un enlace en la discusión de PatruBOT; ajustes en redacción
Más cambios de uso tradicional
(No se muestran 5 ediciones intermedias del mismo usuario)
Línea 1: Línea 1:
/*
/* <nowiki>
; Original source: //pl.wikipedia.org/wiki/MediaWiki:Wikibugs.js
* Original version: http://pl.wikipedia.org/wiki/MediaWiki:Wikibugs.js (2008-12-17)
; Russian adaptation: [[:ru:User:Александр Сигачёв]], [[:ru:User:Putnik]], [[:ru:User:LEMeZza]]
* Russian version by [[User:Александр Сигачёв]], [[User:Putnik]], [[User:LEMeZza]]
; English adaptation: [[:ru:User:Claymore]]
* Converted to OOjs (2017-05-20) by [[User:Putnik]]
; Spanish adaptation: [[:es:User:Emijrp]]
* Spanish version (2018-03-06) by [[User:Leoncastro]]
*/
( function ( mw, $ ) {
'use strict';


var wb$bugsPage = 'Wikipedia:Informes_de_error';
; Original idea: [[:pl:User:Dodek]], [[:pl:User:Adziura]]
var wb$badPages = [
; Implementation: [[:pl:User:Nux]], [[:pl:User:Saper]], [[:pl:User:Beau]], [[:ru:User:Putnik]]
"Wikipedia:Portada", "Wikipedia:Informes_de_error",
*/
"MSN", "Hotmail", "Facebook", "Twitter", "Skype", "Amazon",
"Windows_Live_Messenger", "Correo_Yahoo!", "Windows_Live", "Internet_Explorer"
];


if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ -1 , 6 , 7 , 8 ]) > -1 ||
// No mostrar en las páginas excluidas, para ello se cargará un CSS que lo ocultará
$.inArray( mw.config.get( 'wgPageName' ), wb$badPages ) > -1 ) {
var paginasExcluidas = [
$( '#n-bug_in_article' ).hide();
"Wikipedia:Portada", "Wikipedia:Informes_de_error",
}
"MSN", "Hotmail", "Facebook", "Twitter", "Skype", "Amazon", "Windows_Live_Messenger", "Correo_Yahoo!", "Windows_Live", "Internet_Explorer"
var wb$link = function ( page ) {
];
return mw.config.get( 'wgArticlePath' ).replace( /\$1/, page.replace( / /g, '_' ) );
};


var wb$i18n = {
if ($.inArray( mw.config.get( 'wgNamespaceNumber' ), [ -1 , 6 , 7 , 8 ]) > -1) {
nsFile: 'Archivo:',
//importStylesheet('MediaWiki:Wikibugs.css')
nsSpecial: 'Especial:',
mw.util.addCSS( 'li#n-bug_in_article { display: none }' );
nsCat: 'Categoría:',
} else {
title: 'Informe de errores',
for (var i=paginasExcluidas.length; i>=0; i--) {
btnFix: 'Voy a arreglarlo',
if (mw.config.get( 'wgPageName' )==paginasExcluidas[i]) {
btnReport: 'Informar del error',
//importStylesheet('MediaWiki:Wikibugs.css')
btnCancel: 'Cancelar',
mw.util.addCSS( 'li#n-bug_in_article { display: none }' );
btnSend: 'Enviar',
break
fldPage: 'Título de la página',
}
fldText: 'Texto del mensaje',
}
fldTextInfo: 'Por favor, danos la máxima información posible acerca del error que has encontrado. ' +
}
'A ser posible indica una referencia o sitio web que permita una verificación del dato.',
fldCaptcha: 'Código de verificación',
fldSign: 'Firma',
alertShort: 'El reporte es demasiado corto, por favor, añade más detalles.',
alertNoPage: 'Introduce el nombre del artículo.',
alertCaptcha: 'Su texto contiene enlaces externos. Por favor,' +
' ingrese el código de la imagen y envíe el mensaje nuevamente.',
alertError: 'Se produjo un error al enviar. Intenta nuevamente.',
msgSign: '\n\nEnviado por:',
newTopic: 'Sección nueva:',
htmlIpWarn: '<p><b>Atención.</b> Tu dirección IP quedará registrada en el historial y podrá verse.' +
' Puedes crearte una <a href="//es.wikipedia.org/w/index.php?title=Especial:Entrar&type=signup"' +
' target="_blank">cuenta de usuario</a>.</p>',
htmlInfo: '<div style="float:right;width:200px;padding:4px 10px;' +
'margin:2px 0px 0px 10px;font-size:90%;border:2px solid #a6170f;' +
'border-radius:3px">' +
'<p><b>No informes</b> de errores en otros sitios ' +
'(como <b>Facebook</b> o <b>Twitter</b>); no lo atenderemos.</p>' +
'<p>Por favor, no informes sobre artículos que faltan; lo correcto es enviar' +
' una <a href="' + wb$link( 'Wikipedia:Artículos_solicitados' ) +
'">solicitud de creación</a>.</p>' +
'</div>' +
'<p><b>Este sistema sirve <u>únicamente</u> para informar sobre' +
'errores en los artículos de Wikipedia</b>.</p>' +
'<p style="margin-top:0">Si has encontrado un error, por favor, intenta arreglarlo tú mismo; la ' +
'<a href="' + wb$link( 'wiki' ) + '" target="_blank">tecnología wiki</a> permite que cualquiera pueda ' +
'<b><a href="' + wb$link( 'Ayuda:Introducción' ) + '" target="_blank">editar artículos</a></b>.' +
'</p>' +
'<p>No dudes en hacerlo, una de las reglas de Wikipedia dice «¡<a href="' +
wb$link( 'Wikipedia:Sé_valiente_al_editar_páginas' ) +
'" target="_blank">sé valiente editando páginas</a>!».' +
'</p>' +
'<p>Si no puedes o no sabes arreglar el error, entonces infórmanos de él usando este formulario.</p>' +
'<p><b>Si el error ya se ha corregido, no lo informes.</b></p>' +
'<p style="color:red"><b><u>No</u> dejes tu número de teléfono ni tu correo electrónico</b>.</p>' +
'<p><a href="' + wb$link( wb$bugsPage ) + '" target="_blank">Ver los informes de error actuales</a>.</p>' +
'<p>Lee los <a href="//wikimediafoundation.org/wiki/Términos_de_Uso"' +
' target="_blank">términos de uso</a> y la ' +
'<a href="//wikimediafoundation.org/wiki/Política_de_privacidad"' +
' target="_blank">política de privacidad</a>.</p>'
};


var wb$isValidPageName = function (name) {
var wb$description = "Por favor, danos la máxima información posible acerca del error que has encontrado. A ser posible indica una referencia o sitio web que permita una verificación del dato."
if ( !name || name.substr( 0, name.indexOf( ':' ) + 1 ) === wb$i18n.nsSpecial ) {
return false;
}
name = name.replace( /_/g, ' ' );
for ( var i = 0; i < wb$badPages.length; i++ ) {
if ( name === wb$badPages[i] ) {
return false;
}
}
return true;
};


var wb$popWikibug = function () {
// Info popup
var canEdit = false,
$editLink = $( '#ca-edit a' );
if ( $editLink.length ) {
canEdit = true;
}


// Prepare messages
$(function()
var $infoHtml = $( '<div>' ).html( $.parseHTML( wb$i18n.htmlInfo ) );
{
if ( !mw.config.get( 'wgUserName' ) ) {
var el = document.getElementById('n-bug_in_article')
$infoHtml.append( $( '<p>' ).html( $.parseHTML( wb$i18n.htmlIpWarn ) ) );
if (el)
}
el.getElementsByTagName('a')[0].onclick = wb$popWikibug


// OOjs window
var el2 = document.getElementById('bug_in_article')
var windowManager = new OO.ui.WindowManager();
if (el2)
var infoDialog = new OO.ui.MessageDialog();
el2.getElementsByTagName('a')[0].onclick = wb$popWikibug
$( 'body' ).append( windowManager.$element );
})
windowManager.addWindows( [ infoDialog ] );
windowManager.openWindow( infoDialog, {
function wb$popWikibug()
title: wb$i18n.title,
{
message: $infoHtml,
var link_wiki = window.mw.config.get( 'wgArticlePath' ).replace(/\$1/, 'wiki')
actions: [
var link_tocreate = window.mw.config.get( 'wgArticlePath' ).replace(/\$1/, 'Wikipedia:Artículos_solicitados')
{ label: wb$i18n.btnFix, action: 'edit', flags: 'progressive' },
var link_bebold = window.mw.config.get( 'wgArticlePath' ).replace(/\$1/, 'Wikipedia:Sé_valiente_editando_páginas')
{ label: wb$i18n.btnReport, action: 'report', flags: 'progressive' },
var link_buglist = window.mw.config.get( 'wgArticlePath' ).replace(/\$1/, 'Wikipedia:Informes_de_error')
{ label: wb$i18n.btnCancel },
],
wb$popBugBoth("Wikipedia:Informes de error", '\
size: 'large',
<p><b>Este sistema sirve <u>únicamente</u> para informar sobre errores en los artículos de Wikipedia</b>.</p>\
} ).then( function ( opened ) {
<div style="float:right;width:200px;padding:4px 10px;margin:2px 0px 0px 10px;font-size:90%;border:2px solid #900"><p><b>No informes</b> de errores en otros sitios (como <b>Facebook</b> o <b>Twitter</b>); no lo atenderemos.</p>\
function ReportDialog( config ) {
<p>Por favor, no informes sobre artículos que faltan; lo correcto es enviar una <a href="' + link_tocreate + '">solicitud de creación</a>.</p></div>\
ReportDialog.parent.call( this, config );
<p style="margin-top:0">Si has encontrado un error, por favor, intenta arreglarlo tú mismo; la <a href="' + link_wiki + '" target="_blank">tecnología wiki</a> permite que cualquiera pueda <strong><a href="//es.wikipedia.org/wiki/Ayuda:Introducción" target="_blank">editar artículos</a></strong>.</p>\
}
<p>No dudes en hacerlo, una de las reglas de Wikipedia dice «¡<a href="' + link_bebold + '" target="_blank">sé valiente editando páginas</a>!».</p>\
opened.then( function ( closing, data ) {
<p>Si no puedes o no sabes arreglar el error, entonces infórmanos de él usando este formulario.</p>\
if ( data && data.action === 'edit' ) {
<p style="color:red"><b><u>No</u> dejes tu número de teléfono ni tu correo electrónico</b>.</p>\
// Go to edit page
<p><a href="' + link_buglist + '" target="_blank">Ver los informes de error actuales</a>.</p>\
var $editLink = $( '#ca-edit a' ),
<p>Lee los <a href="//wikimediafoundation.org/wiki/Términos_de_Uso" target="_blank">términos de uso</a> y la <a href="//wikimediafoundation.org/wiki/Política_de_privacidad" target="_blank">política de privacidad</a>.</p>\
editUrl = mw.config.get( 'wgArticlePath' ).replace( /\$1/, wb$bugsPage );
')
if ( $editLink.length ) {
return false
editUrl = $editLink.attr( 'href' );
}
}
window.location.assign( editUrl );
function wb$getEditToken(page)
{
var objhttp = (window.XMLHttpRequest) ? new XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP')
if (!objhttp)
return
objhttp.onreadystatechange=function() {
if (objhttp.readyState == 4) {
if (objhttp.status == 200) {
var r_sti = /value="(\d+)" name=["']wpStarttime["']/
var r_eti = /value="(\d+)" name=["']wpEdittime["']/
var r_etk = /value="(.*?)" name=["']wpEditToken["']/
var 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("")
}
function wb$isValidPageName(name)
{
if (name=="" || name=="Usuario_discusión:PatruBOT")
return false
else
return true
}
function wb$checkForm(form)
{
var page = form.wpSummary.value
var content = form.wpTextbox1.value


} else if ( data && data.action === 'report' ) {
if ($.inArray( content, [ "" , wb$description ]) > -1|| content.length<20 || !content.match(' ')) {
// Prepare form
alert("El reporte es demasiado corto, por favor, añade más detalles.")
var inputPage = new OO.ui.TextInputWidget( {
form.wpTextbox1.focus()
placeholder: wb$i18n.fldPage,
return false
value: mw.config.get( 'wgPageName' ).replace( /_/g, ' ' ),
}
disabled: wb$isValidPageName( mw.config.get( 'wgPageName' ) ) && !mw.config.get( 'wgNamespaceNumber' ),
} );
page = page.replace(/^https?:\/\/es\.wikipedia\.org\/wiki\/(.+)$/, "$1")
page = page.replace(/_/g, " ")
page = decodeURIComponent(page)
if (page == mw.config.get( 'wgPageName' ).replace(/_/g, " ") && wb$isValidPageName(mw.config.get( 'wgPageName' ))) {
page = page.replace(/^(Categoría:|\/)/, ":$1")
page = "[["+page+"]]"
} else {
page = page.replace(/\[\[([^\[\]\|]+)\|[^\[\]\|]+\]\]/g, "$1")
page = page.replace(/[\[\]\|]/g, "")
page = page.replace(/^\s+/g, "")
page = page.replace(/\s+$/g, "")
if (! wb$isValidPageName(page) ) {
alert("Introduce el nombre del artículo.")
if ( wb$isValidPageName(mw.config.get( 'wgPageName' )) )
form.wpSummary.value = mw.config.get( 'wgPageName' )
else {
form.wpSummary.value = ""
form.wpSummary.focus()
}
return false
}
if (page.indexOf(':') > 0)
page = '[[:'+page+']]'
else
page = '[['+page+']]'
}
form.submit.disabled = 'disabled'
content += '\r\n\r\nEnviado por: --~~~~'


var inputText = new OO.ui.MultilineTextInputWidget( {
form.wpTextbox1.value = content
placeholder: wb$i18n.fldTextInfo,
form.wpSummary.value = page
rows: 5
} );
return true
}
function wb$goToEditPage()
{
var edit_el = document.getElementById('ca-edit')
var edit_href = window.mw.config.get( 'wgArticlePath' ).replace(/\$1/, 'Wikipedia:Informes_de_error')
if (edit_el)
edit_href = edit_el.getElementsByTagName('a')[0].href
window.location = edit_href
}
function wb$popBugBoth(action_page, infoHTML)
{
var glob = document.body
// shadow
var nel = document.createElement('div')
nel.id='specpop-globhidden'
nel.style.cssText = 'background:white;filter:alpha(opacity=75);opacity:0.75;position:absolute;left:0px;top:0px;z-index:2000'
nel.style.width = document.documentElement.scrollWidth+'px'
nel.style.height= document.documentElement.scrollHeight+'px'
glob.appendChild(nel)
// move the dialog
window.scroll(0, 150)
// information
var edit_el = document.getElementById('ca-edit')
if (edit_el)
var can_edit = true
else
var can_edit = false
nel = document.createElement('div')
nel.id='specpop-info'
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
var tmp = Math.floor(glob.clientWidth/2)-300
if (tmp<5)
tmp = 5
nel.style.left = tmp+'px'
nel.innerHTML = infoHTML
if (window.mw.config.get( 'wgUserName' ) == null)
nel.innerHTML = nel.innerHTML + '<p><b>Atención.</b> Tu dirección IP quedará registrada en el historial y podrá verse. Puedes crearte una <a href="//es.wikipedia.org/w/index.php?title=Especial:Entrar&type=signup" target="_blank">cuenta de usuario</a>.</p>'
nel.innerHTML += '<p style="text-align:center;margin-top:15px">\
'+(can_edit ? '<input type="button" value="Voy a arreglarlo" onclick="wb$goToEditPage()" />' : '')+ '\
<input type="button" value="Informar del error" 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 action_url = window.mw.config.get( 'wgServer' ) + window.mw.config.get( 'wgScript' ) + "?title=" +encodeURIComponent(action_page) + "&action=submit"
// form
nel = document.createElement('div')
nel.id = 'specpop-form'
nel.style.cssText = 'background:white;padding:5px 10px;border:1px solid black;position:absolute;width:330px;min-height:300px;top:200px;z-index:2001'
if (nel.style.maxHeight==undefined)
nel.style.height='300px' // IE blah
nel.style.left = (Math.floor(glob.clientWidth/2)-165)+'px'
//nel.style.top = (this.offsetTop-100)+'px'
nel.innerHTML = '<form id="fm1" action="'+action_url+'" method="post" enctype="multipart/form-data" onsubmit="return wb$checkForm(this)">\
Página:<br /><input type="text" name="wpSummary" id="wpSummary" width="320px" /><br />\
<input type="hidden" name="wpSection" value="new" />\
<input type="hidden" name="wpSave" value="Save" />\
<input type="hidden" id="Starttime" name="wpStarttime" value="" />\
<input type="hidden" id="Edittime" name="wpEdittime" value="" />\
<input type="hidden" id="EditToken" name="wpEditToken" value="" />\
<input type="hidden" id="AutoSummary" name="wpAutoSummary" value="" />\
<input type="hidden" name="wpScrolltop" value="0" />\
Mensaje:<br /><textarea id="TextBox" name="wpTextbox1" style="width:320px;height:200px" onfocus="if (this.value == wb$description) {this.value = \'\'}">' + wb$description + '</textarea><br />\
<input type="submit" id="submit" value="Enviar" /> &nbsp; \
<input type="button" value="Cancelar" onclick="wb$elementsRemove(\'specpop-form\',\'specpop-globhidden\',\'specpop-pos\')" />\
</form>'
glob.appendChild(nel)
if (wb$isValidPageName(mw.config.get( 'wgPageName' )))
document.getElementById('wpSummary').value = mw.config.get( 'wgPageName' ).replace(/_/g, " ")
wb$getEditToken(action_page)
}
function wb$elementsRemove()
{
var el
for (var i=arguments.length-1; i>=0; i--) {
el = document.getElementById(arguments[i])
if (el)
el.parentNode.removeChild(el)
}
}


var inputCaptcha = new OO.ui.TextInputWidget( {
// </nowiki>
placeholder: wb$i18n.fldCaptcha,
} );

var panelCaptcha = new OO.ui.FieldLayout( inputCaptcha, {
label: wb$i18n.fldCaptcha,
} );
panelCaptcha.toggle( false );

var imageCaptcha = new OO.ui.ToggleWidget();
imageCaptcha.$element.css( 'text-align', 'right' );
imageCaptcha.$element.append( $( '<img>' )
.attr( 'id', 'wikibugs-captcha-img' )
.attr( 'width', 249 )
.attr( 'height', 63 ) );
imageCaptcha.toggle( false );

var inputSign = new OO.ui.TextInputWidget( {
placeholder: wb$i18n.fldSign,
value: mw.config.get( 'wgUserName' ) ? '~~' + '~~' : '',
disabled: mw.config.get( 'wgUserName' )
} );

var fieldset = new OO.ui.FieldsetLayout( {
classes: [ 'container' ],
} );

fieldset.addItems( [
new OO.ui.FieldLayout( inputPage, {
label: wb$i18n.fldPage,
align: 'top'
} ),
new OO.ui.FieldLayout( inputText, {
label: wb$i18n.fldText,
align: 'top'
} ),
panelCaptcha,
imageCaptcha,
new OO.ui.FieldLayout( inputSign, {
label: wb$i18n.fldSign,
} ),
] );

// Add the FieldsetLayout to a FormLayout.
var form = new OO.ui.FormLayout( {
items: [ fieldset ],
} );

// Open window with report form
OO.inheritClass( ReportDialog, OO.ui.MessageDialog );
ReportDialog.static.name = 'reportDialog';
ReportDialog.prototype.getActionProcess = function ( action ) {
var dialog = this;
if ( action ) {
return new OO.ui.Process( function () {
if ( action === 'send' ) {
dialog.getActions().setAbilities({ send: false });

// Send message
var content = inputText.getValue();
if ( content === '' || content.length < 20 || !content.match( ' ' ) ) {
mw.notify( wb$i18n.alertShort );
inputText.focus();
dialog.getActions().setAbilities({ send: true });
return;
}

var page = inputPage.getValue()
.replace( /^https?:\/\/es\.wikipedia\.org\/wiki\/(.+)$/, '$1' )
.replace( /_/g, ' ' );
page = decodeURIComponent( page );

var section;

if ( page === mw.config.get( 'wgPageName' ).replace( /_/g, ' ' ) &&
wb$isValidPageName( mw.config.get( 'wgPageName' ) )
) {
if ( mw.config.get( 'wgNamespaceNumber' ) === 6 ) {
section = '[[:' + wb$i18n.nsFile + mw.config.get( 'wgTitle' ) + '|' + window.wgTitle + ']]';
content = '[[' + wb$i18n.nsFile + mw.config.get( 'wgTitle' ) +
'|thumb|left|100px]]\n* ' + content + '\n{{clear}}';
} else {
var re = new RegExp( '^('+ wb$i18n.nsCat + '|'+ wb$i18n.nsFile + '|\\/)' );
section = page.replace( re, ':$1' );
section = '[[' + section + ']]';
}
} else {
page = page
.replace( /\[\[([^\[\]\|]+)\|[^\[\]\|]+\]\]/g, '$1' )
.replace( /[\[\]\|]/g, '' )
.replace( /^\s+/g, '' )
.replace( /\s+$/g, '' );

if ( !wb$isValidPageName( page ) ) {
mw.notify( wb$i18n.alertNoPage );
if ( wb$isValidPageName( mw.config.get( 'wgPageName' ) ) ) {
inputPage.setValue( mw.config.get( 'wgPageName' ) );
} else {
inputPage.setValue( '' );
inputPage.focus();
}
dialog.getActions().setAbilities({ send: true });
return;
}
if ( page.indexOf( ':' ) > 0 ) {
section = '[[:' + page + ']]';
} else {
section = '[[' + page + ']]';
}
}

content += wb$i18n.msgSign;
if ( !mw.config.get( 'wgUserName' ) ) {
content += ' ' + inputSign.getValue().trim();
}
content += ' ~~' + '~~';

dialog.getActions().get()[0].pushPending();

var data = {
format: 'json',
action: 'edit',
title: wb$bugsPage,
section: 'new',
sectiontitle: section,
summary: wb$i18n.newTopic + ' /* ' + page + ' */',
text: content.trim(),
token: mw.user.tokens.get( 'editToken' )
};
var captchaId = $( '#wikibugs-captcha-img' ).data( 'id' );
if ( captchaId ) {
data.captchaid = captchaId;
data.captchaword = inputCaptcha.getValue().trim();
}

$.ajax( {
url: '/w/api.php',
type: 'POST',
data: data,
success: function ( xhr ) {
if ( xhr && xhr.edit && xhr.edit.result === 'Success' ) {
// Success
var url = mw.config.get( 'wgArticlePath' )
.replace( /\$1/, wb$bugsPage )
.replace( / /g, '_' );
window.location.href = url + '#' + page;
} else if ( xhr &&
xhr.edit &&
xhr.edit.captcha &&
xhr.edit.captcha.type === 'image'
) {
// Captcha
$( '#wikibugs-captcha-img' )
.attr( 'src', xhr.edit.captcha.url )
.data( 'id', xhr.edit.captcha.id );
imageCaptcha.toggle( true );
inputCaptcha.setValue( '' );
panelCaptcha.toggle( true );
dialog.getActions().get()[0].popPending();
mw.notify( wb$i18n.alertCaptcha );
dialog.getActions().setAbilities({ send: true });
} else {
// Error
dialog.getActions().get()[0].popPending();
mw.notify( wb$i18n.alertError );
dialog.getActions().setAbilities({ send: true });
}
},
error: function() {
dialog.getActions().get()[0].popPending();
mw.notify( wb$i18n.alertError );
dialog.getActions().setAbilities({ send: true });
}
} );
} else {
dialog.close();
}
} );
}
return ReportDialog.parent.prototype.getActionProcess.call( this, action );
};

var reportDialog = new ReportDialog();
windowManager.addWindows( [ reportDialog ] );

windowManager.openWindow( reportDialog, {
title: wb$i18n.title,
message: form.$element,
actions: [
{ label: wb$i18n.btnSend, action: 'send', flags: 'progressive' },
{ label: wb$i18n.btnCancel },
],
size: 'medium',
} );
}
} );
} );
};

// Click event
$( function() {
$( '#n-bug_in_article a' ).click( function ( e ) {
e.preventDefault();
mw.loader.using( [
'mediawiki.api',
'oojs-ui-core',
'oojs-ui-widgets',
'oojs-ui-windows'
] ).then( wb$popWikibug );
} );
} );

}( mediaWiki, jQuery ) );

Revisión del 17:02 8 mar 2018

/*
 * Original version: http://pl.wikipedia.org/wiki/MediaWiki:Wikibugs.js (2008-12-17)
 * Russian version by [[User:Александр Сигачёв]], [[User:Putnik]], [[User:LEMeZza]]
 * Converted to OOjs (2017-05-20) by [[User:Putnik]]
 * Spanish version (2018-03-06) by [[User:Leoncastro]]
 */
( function ( mw, $ ) {
	'use strict';

	var wb$bugsPage = 'Wikipedia:Informes_de_error';
	var wb$badPages = [
		"Wikipedia:Portada", "Wikipedia:Informes_de_error",
		"MSN", "Hotmail", "Facebook", "Twitter", "Skype", "Amazon",
		"Windows_Live_Messenger", "Correo_Yahoo!", "Windows_Live", "Internet_Explorer"
	];

	if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ -1 , 6 , 7 , 8 ]) > -1 ||
		 $.inArray( mw.config.get( 'wgPageName' ), wb$badPages ) > -1 ) {
		$( '#n-bug_in_article' ).hide();
	}
	var wb$link = function ( page ) {
		return mw.config.get( 'wgArticlePath' ).replace( /\$1/, page.replace( / /g, '_' ) );
	};

	var wb$i18n = {
		nsFile: 'Archivo:',
		nsSpecial: 'Especial:',
		nsCat: 'Categoría:',
		title: 'Informe de errores',
		btnFix: 'Voy a arreglarlo',
		btnReport: 'Informar del error',
		btnCancel: 'Cancelar',
		btnSend: 'Enviar',
		fldPage: 'Título de la página',
		fldText: 'Texto del mensaje',
		fldTextInfo: 'Por favor, danos la máxima información posible acerca del error que has encontrado. ' +
			'A ser posible indica una referencia o sitio web que permita una verificación del dato.',
		fldCaptcha: 'Código de verificación',
		fldSign: 'Firma',
		alertShort: 'El reporte es demasiado corto, por favor, añade más detalles.',
		alertNoPage: 'Introduce el nombre del artículo.',
		alertCaptcha: 'Su texto contiene enlaces externos. Por favor,' +
			' ingrese el código de la imagen y envíe el mensaje nuevamente.',
		alertError: 'Se produjo un error al enviar. Intenta nuevamente.',
		msgSign: '\n\nEnviado por:',
		newTopic: 'Sección nueva:',
		htmlIpWarn: '<p><b>Atención.</b> Tu dirección IP quedará registrada en el historial y podrá verse.' +
			' Puedes crearte una <a href="//es.wikipedia.org/w/index.php?title=Especial:Entrar&type=signup"' +
			' target="_blank">cuenta de usuario</a>.</p>',
		htmlInfo: '<div style="float:right;width:200px;padding:4px 10px;' +
			'margin:2px 0px 0px 10px;font-size:90%;border:2px solid #a6170f;' +
			'border-radius:3px">' +
				'<p><b>No informes</b> de errores en otros sitios ' +
					'(como <b>Facebook</b> o <b>Twitter</b>); no lo atenderemos.</p>' +
				'<p>Por favor, no informes sobre artículos que faltan; lo correcto es enviar' +
					' una <a href="' + wb$link( 'Wikipedia:Artículos_solicitados' ) +
					'">solicitud de creación</a>.</p>' +
			'</div>' +
			'<p><b>Este sistema sirve <u>únicamente</u> para informar sobre' +
				'errores en los artículos de Wikipedia</b>.</p>' +
			'<p style="margin-top:0">Si has encontrado un error, por favor, intenta arreglarlo tú mismo; la ' +
				'<a href="' + wb$link( 'wiki' ) + '" target="_blank">tecnología wiki</a> permite que cualquiera pueda ' +
				'<b><a href="' + wb$link( 'Ayuda:Introducción' ) + '" target="_blank">editar artículos</a></b>.' +
			'</p>' +
			'<p>No dudes en hacerlo, una de las reglas de Wikipedia dice «¡<a href="' +
				wb$link( 'Wikipedia:Sé_valiente_al_editar_páginas' ) +
				'" target="_blank">sé valiente editando páginas</a>!».' +
			'</p>' +
			'<p>Si no puedes o no sabes arreglar el error, entonces infórmanos de él usando este formulario.</p>' +
			'<p><b>Si el error ya se ha corregido, no lo informes.</b></p>' +
			'<p style="color:red"><b><u>No</u> dejes tu número de teléfono ni tu correo electrónico</b>.</p>' +
			'<p><a href="' + wb$link( wb$bugsPage ) + '" target="_blank">Ver los informes de error actuales</a>.</p>' +
			'<p>Lee los <a href="//wikimediafoundation.org/wiki/Términos_de_Uso"' +
				' target="_blank">términos de uso</a> y la ' +
				'<a href="//wikimediafoundation.org/wiki/Política_de_privacidad"' +
				' target="_blank">política de privacidad</a>.</p>'
	};

	var wb$isValidPageName = function (name) {
		if ( !name || name.substr( 0, name.indexOf( ':' ) + 1 ) === wb$i18n.nsSpecial ) {
			return false;
		}
		name = name.replace( /_/g, ' ' );
		for ( var i = 0; i < wb$badPages.length; i++ ) {
			if ( name === wb$badPages[i] ) {
				return false;
			}
		}
		return true;
	};

	var wb$popWikibug = function () {
		// Info popup
		var canEdit = false,
			$editLink = $( '#ca-edit a' );
		if ( $editLink.length ) {
			canEdit = true;
		}

		// Prepare messages
		var $infoHtml = $( '<div>' ).html( $.parseHTML( wb$i18n.htmlInfo ) );
		if ( !mw.config.get( 'wgUserName' ) ) {
			$infoHtml.append( $( '<p>' ).html( $.parseHTML( wb$i18n.htmlIpWarn ) ) );
		}

		// OOjs window
		var windowManager = new OO.ui.WindowManager();
		var infoDialog = new OO.ui.MessageDialog();
		$( 'body' ).append( windowManager.$element );
		windowManager.addWindows( [ infoDialog ] );
		windowManager.openWindow( infoDialog, {
			title: wb$i18n.title,
			message: $infoHtml,
			actions: [
				{ label: wb$i18n.btnFix, action: 'edit', flags: 'progressive' },
				{ label: wb$i18n.btnReport, action: 'report', flags: 'progressive' },
				{ label: wb$i18n.btnCancel },
			],
			size: 'large',
		} ).then( function ( opened ) {
			function ReportDialog( config ) {
				ReportDialog.parent.call( this, config );
			}
			opened.then( function ( closing, data ) {
				if ( data && data.action === 'edit' ) {
					// Go to edit page
					var $editLink = $( '#ca-edit a' ),
						editUrl = mw.config.get( 'wgArticlePath' ).replace( /\$1/, wb$bugsPage );
					if ( $editLink.length ) {
						editUrl = $editLink.attr( 'href' );
					}
					window.location.assign( editUrl );

				} else if ( data && data.action === 'report' ) {
					// Prepare form
					var inputPage = new OO.ui.TextInputWidget( {
						placeholder: wb$i18n.fldPage,
						value: mw.config.get( 'wgPageName' ).replace( /_/g, ' ' ),
						disabled: wb$isValidPageName( mw.config.get( 'wgPageName' ) ) && !mw.config.get( 'wgNamespaceNumber' ),
					} );

					var inputText = new OO.ui.MultilineTextInputWidget( {
						placeholder: wb$i18n.fldTextInfo,
						rows: 5
					} );

					var inputCaptcha = new OO.ui.TextInputWidget( {
						placeholder: wb$i18n.fldCaptcha,
					} );

					var panelCaptcha = new OO.ui.FieldLayout( inputCaptcha, {
						label: wb$i18n.fldCaptcha,
					} );
					panelCaptcha.toggle( false );

					var imageCaptcha = new OO.ui.ToggleWidget();
					imageCaptcha.$element.css( 'text-align', 'right' );
					imageCaptcha.$element.append( $( '<img>' )
						.attr( 'id', 'wikibugs-captcha-img' )
						.attr( 'width', 249 )
						.attr( 'height', 63 ) );
					imageCaptcha.toggle( false );

					var inputSign = new OO.ui.TextInputWidget( {
						placeholder: wb$i18n.fldSign,
						value: mw.config.get( 'wgUserName' ) ? '~~' + '~~' : '',
						disabled: mw.config.get( 'wgUserName' )
					} );

					var fieldset = new OO.ui.FieldsetLayout( {
						classes: [ 'container' ],
					} );

					fieldset.addItems( [
						new OO.ui.FieldLayout( inputPage, {
							label: wb$i18n.fldPage,
							align: 'top'
						} ),
						new OO.ui.FieldLayout( inputText, {
							label: wb$i18n.fldText,
							align: 'top'
						} ),
						panelCaptcha,
						imageCaptcha,
						new OO.ui.FieldLayout( inputSign, {
							label: wb$i18n.fldSign,
						} ),
					] );

					// Add the FieldsetLayout to a FormLayout.
					var form = new OO.ui.FormLayout( {
						items: [ fieldset ],
					} );

					// Open window with report form
					OO.inheritClass( ReportDialog, OO.ui.MessageDialog );
					ReportDialog.static.name = 'reportDialog';
					ReportDialog.prototype.getActionProcess = function ( action ) {
						var dialog = this;
						if ( action ) {
							return new OO.ui.Process( function () {
								if ( action === 'send' ) {
									dialog.getActions().setAbilities({ send: false });

									// Send message
									var content = inputText.getValue();
									if ( content === '' || content.length < 20 || !content.match( ' ' ) ) {
										mw.notify( wb$i18n.alertShort );
										inputText.focus();
										dialog.getActions().setAbilities({ send: true });
										return;
									}

									var page = inputPage.getValue()
											.replace( /^https?:\/\/es\.wikipedia\.org\/wiki\/(.+)$/, '$1' )
											.replace( /_/g, ' ' );
									page = decodeURIComponent( page );

									var section;

									if ( page === mw.config.get( 'wgPageName' ).replace( /_/g, ' ' ) &&
										wb$isValidPageName( mw.config.get( 'wgPageName' ) )
									) {
										if ( mw.config.get( 'wgNamespaceNumber' ) === 6 ) {
											section = '[[:' + wb$i18n.nsFile + mw.config.get( 'wgTitle' ) + '|' + window.wgTitle + ']]';
											content = '[[' + wb$i18n.nsFile + mw.config.get( 'wgTitle' ) +
													'|thumb|left|100px]]\n* ' + content + '\n{{clear}}';
										} else {
											var re = new RegExp( '^('+ wb$i18n.nsCat + '|'+ wb$i18n.nsFile + '|\\/)' );
											section = page.replace( re, ':$1' );
											section = '[[' + section + ']]';
										}
									} else {
										page = page
											.replace( /\[\[([^\[\]\|]+)\|[^\[\]\|]+\]\]/g, '$1' )
											.replace( /[\[\]\|]/g, '' )
											.replace( /^\s+/g, '' )
											.replace( /\s+$/g, '' );

										if ( !wb$isValidPageName( page ) ) {
											mw.notify( wb$i18n.alertNoPage );
											if ( wb$isValidPageName( mw.config.get( 'wgPageName' ) ) ) {
												inputPage.setValue( mw.config.get( 'wgPageName' ) );
											} else {
												inputPage.setValue( '' );
												inputPage.focus();
											}
											dialog.getActions().setAbilities({ send: true });
											return;
										}
										if ( page.indexOf( ':' ) > 0 ) {
											section = '[[:' + page + ']]';
										} else {
											section = '[[' + page + ']]';
										}
									}

									content += wb$i18n.msgSign;
									if ( !mw.config.get( 'wgUserName' ) ) {
										content += ' ' + inputSign.getValue().trim();
									}
									content += ' ~~' + '~~';

									dialog.getActions().get()[0].pushPending();

									var data = {
										format: 'json',
										action: 'edit',
										title: wb$bugsPage,
										section: 'new',
										sectiontitle: section,
										summary: wb$i18n.newTopic + ' /* ' + page + ' */',
										text: content.trim(),
										token: mw.user.tokens.get( 'editToken' )
									};
									var captchaId = $( '#wikibugs-captcha-img' ).data( 'id' );
									if ( captchaId ) {
										data.captchaid = captchaId;
										data.captchaword = inputCaptcha.getValue().trim();
									}

									$.ajax( {
										url: '/w/api.php',
										type: 'POST',
										data: data,
										success: function ( xhr ) {
											if ( xhr && xhr.edit && xhr.edit.result === 'Success' ) {
												// Success
												var url = mw.config.get( 'wgArticlePath' )
														.replace( /\$1/, wb$bugsPage )
														.replace( / /g, '_' );
												window.location.href = url + '#' + page;
											} else if ( xhr &&
												xhr.edit &&
												xhr.edit.captcha &&
												xhr.edit.captcha.type === 'image'
											) {
												// Captcha
												$( '#wikibugs-captcha-img' )
													.attr( 'src', xhr.edit.captcha.url )
													.data( 'id', xhr.edit.captcha.id );
												imageCaptcha.toggle( true );
												inputCaptcha.setValue( '' );
												panelCaptcha.toggle( true );
												dialog.getActions().get()[0].popPending();
												mw.notify( wb$i18n.alertCaptcha );
												dialog.getActions().setAbilities({ send: true });
											} else {
												// Error
												dialog.getActions().get()[0].popPending();
												mw.notify( wb$i18n.alertError );
												dialog.getActions().setAbilities({ send: true });
											}
										},
										error: function() {
											dialog.getActions().get()[0].popPending();
											mw.notify( wb$i18n.alertError );
											dialog.getActions().setAbilities({ send: true });
										}
									} );
								} else {
									dialog.close();
								}
							} );
						}
						return ReportDialog.parent.prototype.getActionProcess.call( this, action );
					};

					var reportDialog = new ReportDialog();
					windowManager.addWindows( [ reportDialog ] );

					windowManager.openWindow( reportDialog, {
						title: wb$i18n.title,
						message: form.$element,
						actions: [
							{ label: wb$i18n.btnSend, action: 'send', flags: 'progressive' },
							{ label: wb$i18n.btnCancel },
						],
						size: 'medium',
					} );
				}
			} );
		} );
	};

	// Click event
	$( function() {
		$( '#n-bug_in_article a' ).click( function ( e ) {
			e.preventDefault();
			mw.loader.using( [
				'mediawiki.api',
				'oojs-ui-core',
				'oojs-ui-widgets',
				'oojs-ui-windows'
			] ).then( wb$popWikibug );
		} );
	} );

}( mediaWiki, jQuery ) );