Ir al contenido

Usuario:Ggenellina/detectar-redirects.js

De Wikipedia, la enciclopedia libre

Nota: Después de guardar, debes refrescar la caché de tu navegador para ver los cambios. Internet Explorer: mantén presionada Ctrl mientras pulsas Actualizar. Firefox: mientras presionas Mayús pulsas el botón Actualizar, (o presiona Ctrl-Shift-R). Los usuarios de Google Chrome y Safari pueden simplemente pulsar el botón Recargar. Para más detalles e instrucciones acerca de otros exploradores, véase Ayuda:Cómo limpiar la caché.

/*****************************************************************************
 * detectar-redirects.js
 *
 * Una herramienta para detectar y resaltar redirecciones incorrectas.
 *
 * (C) 2013 Gabriel A. Genellina
 *
 * Por la presente se concede permiso, sin cargo, a cualquier persona
 * que obtenga una copia de este software y de los archivos de documentación
 * asociados (el "Software"), para utilizar el Software sin restricciones,
 * incluyendo sin limitación los derechos de usar, copiar, modificar, fusionar,
 * publicar, distribuir, sublicenciar, y/o vender copias del Software, y
 * para permitir a las personas a las que se les proporcione el Software a
 * hacer lo mismo, sujeto a las siguientes condiciones:
 *
 * El aviso de copyright anterior y este aviso de permiso deberán ser incluidas
 * en todas las copias o partes sustanciales del Software.
 *
 * EL SOFTWARE SE PROPORCIONA "TAL CUAL", SIN GARANTÍA DE NINGÚN TIPO, EXPRESA
 * O IMPLÍCITA, INCLUYENDO PERO NO LIMITADO A GARANTÍAS DE COMERCIABILIDAD,
 * IDONEIDAD PARA UN PROPÓSITO PARTICULAR Y NO INFRACCIÓN. EN NINGÚN CASO LOS
 * AUTORES O TITULARES DEL COPYRIGHT SERÁN RESPONSABLES DE NINGUNA RECLAMACIÓN,
 * DAÑOS U OTRAS RESPONSABILIDADES, YA SEA EN UN LITIGIO, AGRAVIO O DE OTRO MODO,
 * QUE SURJA DE O EN CONEXIÓN CON EL SOFTWARE O EL USO U OTRO TIPO DE ACCIONES EN
 * EL SOFTWARE.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *****************************************************************************/

'use strict'

var detectarRedirects = {

  INVALIDREDIRECTMSG: '(El texto de esta redirección es incorrecto y no debería usarse)',
  blacklist: {},

  normalized: function(name) {
        var title = new mw.Title.newFromText(name);
        if (null !== title)
          return ':' + ( title && title.getPrefixedDb ? title.getPrefixedDb() : '???' );
        return null;
  },

  getFile: function(filename) {
    return $.get(mw.config.get('wgScript'), {title: filename, action: 'raw'})
         .done( detectarRedirects.onGetBlacklist )
  },

  onGetBlacklist: function(text) {
    var elems = text.split('\n');
    for (var i=0; i<elems.length; i++) {
      if (elems[i]) {
        var title = detectarRedirects.normalized(elems[i]);
        if (null !== title)
          detectarRedirects.blacklist[title] = 1;
      }
    }
  },

  check: function() {
    var links = $( "a[class~='mw-redirect']" );
    if (links.length==0) return;
    var pagetitleToElem = {};
    for (var i=0; i<links.length; i++) {
      var lnk = links[i];
      var href = decodeURI(lnk.href);
      var idx = href.indexOf('/wiki/'); // @@@
      if (idx<0) continue;
      var normtitle = detectarRedirects.normalized(href.substring(idx+6));
      if (null === normtitle) continue;
      if (pagetitleToElem.hasOwnProperty(normtitle))
        pagetitleToElem[normtitle].push(lnk);
      else
        pagetitleToElem[normtitle] = [lnk];
    }
    if (pagetitleToElem.length==0) return;

    // verificar si esos titulos están en la lista de errores
    var blacklist = detectarRedirects.blacklist;
    for (var pagetitle in pagetitleToElem) {
      if (blacklist.hasOwnProperty(pagetitle)) {
        $(pagetitleToElem[pagetitle])
          .addClass('mw-redirect-invalid')
          .each( function(i, elem) {
            $(elem).prop('title', ($(elem).prop('title') + ' ' + detectarRedirects.INVALIDREDIRECTMSG).trim());
          })
      }
    }
  },

  run: function() {
    detectarRedirects.blacklist = {};
    $.when( detectarRedirects.getFile('Usuario:Ggenellina/redirects-errores-de-ortografía-una-palabra'),
            detectarRedirects.getFile('Usuario:Ggenellina/redirects-errores-de-ortografía-varias-palabras') )
      .done(detectarRedirects.check)
      .fail(function(data) { console.log('fail'); console.log(data); })
      .always(function() { delete detectarRedirects.blacklist; });
  },

}

if (mw.config.get('wgIsArticle') && (mw.config.get('wgNamespaceNumber')>=0)) {
  if ($.inArray(mw.config.get('wgAction'), ['view', 'submit', 'purge']) !== -1) { /* sólo si estoy viendo (no editando) */
    // Make sure the utilities module is loaded (will only load if not already)
    mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.Title'], function () {
      $(document).ready( detectarRedirects.run );
    });
  }
}