For faster navigation, this Iframe is preloading the Wikiwand page for Utilisateur:Arkanosis/iKiwi.js.

Utilisateur:Arkanosis/iKiwi.js

/*
***************************************************************************
** iKiwi - Permet de récupérer des interwikis sur d'autres Wikipédia
** Compatibilité : MediaWiki
** Support : :fr:Discussion_utilisateur:Arkanosis
** Licence : MIT/X11
**
** Installation : ajouter
**  importScript('User:Arkanosis/iKiwi.js');
** dans le common.js
*/

iKiwiVersion = '0.6.0c';

var iKiwiDefaultDistantWiki = 'en';
if (typeof (iKiwiDistantWikis) == 'undefined')
  var iKiwiDistantWikis = ['de', 'en', 'es', 'fr', 'it', 'ja', 'nl', 'pl', 'pt', 'ru', 'sv'];
else
{
  iKiwiDefaultDistantWiki = iKiwiDistantWikis[0];
}
if (iKiwiDistantWikis.indexOf(mw.config.get('wgContentLanguage')) != -1)
{
  iKiwiDistantWikis[iKiwiDistantWikis.indexOf(mw.config.get('wgContentLanguage'))] = iKiwiDistantWikis[iKiwiDistantWikis.length - 1];
  iKiwiDistantWikis.pop();
}
iKiwiDistantWikis.sort();
if (typeof (iKiwiWatchMain) == 'undefined')
  var iKiwiWatchMain = false;
if (typeof (iKiwiWatchOthers) == 'undefined')
  var iKiwiWatchOthers = false;

if (typeof (iKiwiDisplayPanel) == 'undefined')
  var iKiwiDisplayPanel = true;

var iKiwiInterWiki = new RegExp('^\\s*\\[\\[([a-z][a-z].?(x?-[^\\]]+)?|simple|tokipona):([^\\]]*)\\]\\]\\s*$');
var iKiwiBlank = new RegExp('^\\s*$');
var iKiwiHtmlInterWiki = new RegExp('<a href="/wiki/([^"]+)" title="([^"]+)">fr:([^<]+)</a>');

var iKiwiPanelNextState = 0;
var iKiwiStates = [ 'none', 'block' ];

var iKiwiTranslationId = 0;
var iKiwiTranslations = [];

var iKiwiI18nText = {
  'de': {
    'usertalk': 'Benutzer_Diskussion',
    'redirectfrom': 'Weitergeleitet von',
    'alreadylinked': 'Der remote Artikel ist bereits im Zusammenhang mit',
    'nomoreiw': 'Es gibt kein interWiki mehr zu hinzufügen',
    'noarticle': 'Es gibt kein Artikel mit diesem Name',
    'extpage': 'Remote Artikel:',
    'panel': 'Die interWiki aus einer anderen Version des Artikels hinzufügen',
    'autopreview': 'auto Vorschau',
    'adding': 'Adding',
    'from': 'von',
    'iwadded': 'interWiki',
    'iwsadded': 'interWikis',
    'follow': 'Diese Seite beobachten',
    'preview': 'Vorschau zeigen',
    'publish': 'Seite speichern',
  },
  'en': {
    'usertalk': 'User_talk',
    'redirectfrom': 'Redirected from',
    'alreadylinked': 'The remote article is already linked to ',
    'twolocallinks': 'The local article is linked twice to ',
    'twodistantlinks': 'The distant article is linked twice to ',
    'twolinks': 'The local article and the distant article have different links to ',
    'nomoreiw': 'There is no additional interWiki to add',
    'noarticle': 'There is no article with this name',
    'extpage': 'Remote article:',
    'panel': 'Get the interWikis from another version of the article',
    'autopreview': 'auto preview',
    'adding': 'Adding',
    'from': 'from',
    'iwadded': 'interWiki',
    'iwsadded': 'interWikis',
    'follow': 'Watch this page',
    'preview': 'Show preview',
    'publish': 'Save page',
  },
  'es': {
    'usertalk': 'Usuario_Discusión',
    'redirectfrom': 'Redirigido desde',
    'from': 'desde',
    'follow': 'Vigilar esta página',
    'preview': 'Mostrar previsualización',
    'publish': 'Grabar la página',
  },
  'fr': {
    'usertalk': 'Discussion_utilisateur',
    'redirectfrom': 'Redirigé depuis',
    'alreadylinked': 'L\'article distant est déjà lié à l\'article',
    'twolocallinks': 'L\'article local est lié deux fois à ',
    'twodistantlinks': 'L\'article distant est lié deux fois à ',
    'twolinks': 'L\'article local et l\'article distant ont des liens différents vers ',
    'nomoreiw': 'Il n\'y a pas d\'interWiki supplémentaire à ajouter',
    'noarticle': 'Il n\'y a pas d\'article avec ce nom',
    'extpage': 'Page d\'où récupérer les interWikis :',
    'panel': 'Rapatrier les interWikis d\'une autre version de l\'article',
    'autopreview': 'aperçu automatique',
    'adding': 'Ajout de',
    'from': 'depuis',
    'iwadded': 'interWiki rapatrié',
    'iwsadded': 'interWikis rapatriés',
    'follow': 'Suivre cette page',
    'preview': 'Prévisualiser',
    'publish': 'Publier',
  },
  'it': {
    'usertalk': 'Discussioni_utente',
    'redirectfrom': 'Reindirizzamento da',
    'from': 'da',
    'follow': 'Tieni d\'occhio questa pagina',
    'preview': 'Visualizza anteprima',
    'publish': 'Salva la pagina',
  },
  'ja': {
    'usertalk': '利用者‐会話',
    'redirectfrom': 'から転送',
    'follow': 'ウォッチリストに追加',
    'preview': 'プレビューを表示',
    'publish': '編集を保存',
  },
  'nl': {
    'usertalk': 'Overleg gebruiker',
    'redirectfrom': 'Doorverwezen vanaf',
    'from': 'vanaf',
    'follow': 'Deze pagina volgen',
    'preview': 'Toon bewerking ter controle',
    'publish': 'Pagina opslaan',
  },
  'pl': {
    'usertalk': 'Dyskusja wikipedysty',
    'redirectfrom': 'Przekierowano z',
    'from': 'z',
    'follow': 'Obserwuj',
    'preview': 'Pokaż podgląd',
    'publish': 'Zapisz',
  },
  'pt': {
    'usertalk': 'Usuário_Discussão',
    'redirectfrom': 'Redireccionado de',
    'from': 'de',
    'follow': 'Vigiar esta página',
    'preview': 'Mostrar previsão',
    'publish': 'Gravar página',
  },
  'ru': {
    'usertalk': 'Обсуждение_участника',
    'redirectfrom': 'Перенаправлено с',
    'from': 'c',
    'follow': 'Включить эту страницу в список наблюдения',
    'preview': 'Предварительный просмотр',
    'publish': 'Записать страницу',
  },
  'sv': {
    'usertalk': 'Användardiskussion',
    'redirectfrom': 'Omdirigerad från',
    'from': 'från',
    'follow': 'Bevaka denna sida',
    'preview': 'Visa förhandsgranskning',
    'publish': 'Spara',
  },
};

function iKiwiI18n(lang, message)
{
  if (typeof (iKiwiI18nText[lang]) == 'undefined')
    lang = 'en';
  if (typeof (iKiwiI18nText[lang][message]) == 'undefined')
    return iKiwiI18nText['en'][message];
  return iKiwiI18nText[lang][message];
}

var iKiwiDocPage = iKiwiI18n(mw.config.get('wgContentLanguage'), 'usertalk') + ':Arkanosis/iKiwi.js';

function iKiwiNormalize(string)
{
    return string
      .replace(/[àáâãäåą]/g, 'a')
      .replace(/[æ]/g, 'ae')
      .replace(/[çć]/g, 'c')
      .replace(/[èéêëę]/g, 'e')
      .replace(/[ìíîï]/g, 'i')
      .replace(/[ł]/g, 'l')
      .replace(/[ñ]/g, 'n')
      .replace(/[òóôõöōø]/g, 'o')
      .replace(/[œ]/g, 'oe')
      .replace(/[ś]/g, 's')
      .replace(/[ß]/g, 'ss')
      .replace(/[ùúûü]/g, 'u')
      .replace(/[ýÿ]/g, 'y')
      .replace(/[źż]/g, 'z')

      .replace(/[ÀÁÂÃÄÅĄ]/g, 'A')
      .replace(/[Æ]/g, 'AE')
      .replace(/[ÇĆ]/g, 'C')
      .replace(/[ÈÉÊËĘ]/g, 'E')
      .replace(/[ÌÍÎÏ]/g, 'I')
      .replace(/[Ł]/g, 'L')
      .replace(/[Ñ]/g, 'N')
      .replace(/[ÒÓÔÕÖØ]/g, 'O')
      .replace(/[Œ]/g, 'OE')
      .replace(/[Ś]/g, 'S')
      .replace(/[ÙÚÛÜ]/g, 'U')
      .replace(/[Ý]/g, 'Y')
      .replace(/[ŹŻ]/g, 'Z');
}

var iKiwiTranslationTable =
[
  {
    'de': ['Begriffsklärung'],
    'en': ['disambiguation', 'surname'],
    'es': ['desambiguación'],
    'fr': ['homonymie'],
    'it': ['disambigua'],
    'ja': ['曖昧さ回避'],
    'nl': ['doorverwijspagina'],
    'pl': ['ujednoznacznienie'],
    'pt': ['desambiguação'],
    'ru': ['значения'],
    'sv': ['olika betydelser'],
  },
  {
    'de': ['Film'],
    'en': ['film'],
    'es': ['película'],
    'fr': ['film'],
    'it': ['film'],
    'ja': ['映画'],
    'nl': ['film'],
    'pl': ['film'],
    'pt': ['filme'],
    'ru': ['фильм', 'мультфильм'],
    'sv': ['film'],
  },
  {
    'de': ['Album'],
    'en': ['album', 'soundtrack', 'EP'],
    'es': ['álbum'],
    'fr': ['album'],
    'it': ['album'],
    'ja': ['アルバム'],
    'nl': ['album'],
    'pl': ['album'],
    'pt': ['álbum'],
    'ru': ['альбом'],
    'sv': ['musikalbum', 'album'],
  },
  {
    'de': ['Frankreich'],
    'en': ['France'],
    'es': ['Francia'],
    'fr': ['France'],
    'it': ['Francia'],
    'nl': ['Frankrijk'],
    'pl': ['Francja'],
    'pt': ['França'],
    'ru': ['Франция'],
  },
  {
    'de': ['Fluss'],
    'en': ['river'],
    'fr': ['rivière'],
    'it': ['fiume'],
    'nl': ['rivier'],
    'pl': ['rzeka'],
    'ru': ['река'],
    'sv': ['flod'],
  },
  {
    'de': ['Band'],
    'en': ['band', 'group'],
    'es': ['banda'],
    'fr': ['groupe'],
    'it': ['gruppo musicale'],
    'ja': ['バンド'],
    'nl': ['band'],
    'pl': ['grupa muzyczna'],
    'pt': ['banda'],
    'ru': ['группа'],
    'sv': ['musikgrupp'],
  },
  {
    'de': ['Roman'],
    'en': ['novel'],
    'es': ['novela'],
    'fr': ['roman'],
    'it': ['romanzo'],
    'ja': ['小説'],
    'nl': ['boek', 'roman'],
    'pl': ['powieść'],
    'pt': ['livro'],
    'ru': ['роман'],
    'sv': ['bok'],
  },
  {
    'de': ['Computerspiel'],
    'en': ['video game', 'arcade game'],
    'es': ['videojuego'],
    'fr': ['jeu vidéo'],
    'it': ['videogioco'],
    'ja': ['ゲーム'],
    'nl': ['videospel'],
    'pl': ['gra komputerowa'],
    'pt': ['jogo eletrônico'],
    'ru': ['игра'],
    'sv': ['spel', 'datorspel'],
  },
  {
    'de': ['Lied'],
    'en': ['song', 'instrumental'],
    'es': ['canción'],
    'fr': ['chanson'],
    'it': ['singolo', 'brano musicale'],
    'ja': ['楽曲', '曲'],
    'nl': ['nummer', 'single', 'lied'],
    'pl': ['singel', 'utwór'],
    'pt': ['canção'],
    'ru': ['песня'],
    'sv': ['sång', 'låt'],
  },
  {
    'de': ['Fernsehserie'],
    'en': ['TV series'],
    'es': ['serie de televisión'],
    'fr': ['série télévisée'],
    'it': ['serie televisiva'],
    'ja': ['テレビドラマ'],
    'nl': ['televisieserie'],
    'pl': ['serial telewizyjny', 'serial animowany'],
    'pt': ['série', 'série de TV'],
    'ru': ['телесериал'],
    'sv': ['TV-serie'],
  },
  {
    'de': ['&', 'und'],
    'en': ['&', 'and'],
    'fr': ['&', 'et'],
  },
];


function iKiwiTranslate(from, to, string)
{
  var translations = [string];

  if (['de', 'es', 'fr', 'nl', 'pl', 'pt', 'sv'].indexOf(from) != -1 && ['en', 'es', 'it', 'ja', 'ru'].indexOf(to) != -1)
  {
    var normalizedString = iKiwiNormalize(string);
    if (normalizedString != string)
      translations.push(normalizedString);
  }

  if (/.*\(.+\)/.exec(string))
  {
    // TODO develop an heuristic: it should be better to have the versions without parenthesis at the end
    translations.push(string.replace(/(\s|_)*\([^\)]+\)$/, ''));
    if (translations.length == 3)
    {
      translations.push(translations[1].replace(/(\s|_)*\([^\)]+\)$/, ''));
      if (translations[2] == translations[3])
        translations.pop();
    }
  }

  for (var translationItemId = 0; translationItemId < iKiwiTranslationTable.length; ++translationItemId)
  {
    var originalTokens = iKiwiTranslationTable[translationItemId][from];
    var replacementTokens = iKiwiTranslationTable[translationItemId][to];

    if (typeof (originalTokens) == 'undefined' || typeof (replacementTokens) == 'undefined')
      continue;

    for (var originalTokenId = 0; originalTokenId < originalTokens.length; ++originalTokenId)
    {
      var originalToken = originalTokens[originalTokenId];
      var newTranslations = translations.slice(0);

      for (var currentTranslationId = 0; currentTranslationId < translations.length; ++currentTranslationId)
      {
        var currentTranslation = translations[currentTranslationId];
        if (translations[currentTranslationId].indexOf(originalToken))
          for (var replacementTokenId = 0; replacementTokenId < replacementTokens.length; ++replacementTokenId)
          {
            var replacementToken = replacementTokens[replacementTokenId];
            if (originalToken != replacementToken)
            {
              var newTranslation = currentTranslation.replace(new RegExp('\\b' + originalToken.replace(/[.*+?|()\[\]{}\\]/g, '\\$&') + '\\b', 'g'), replacementToken);
              if (newTranslations.indexOf(newTranslation) == -1)
                newTranslations.push(newTranslation);
            }
          }
      }
      translations = newTranslations;
    }
  }

  return translations.slice(1);
}

// Taken from http://meta.wikimedia.org/wiki/Interwiki_sorting_order
var iKiwiSpecialOrdered = [
  'en', 'pl'
];
var iKiwiSpecialOrder = [
  'ace', 'af', 'ak', 'als', 'am', 'ang', 'ab', 'ar', 'an', 'arc',
  'roa-rup', 'frp', 'as', 'ast', 'gn', 'av', 'ay', 'az', 'bm', 'bn',
  'zh-min-nan', 'nan', 'map-bms', 'ba', 'be', 'be-x-old', 'bh', 'bcl',
  'bi', 'bar', 'bo', 'bs', 'br', 'bg', 'bxr', 'ca', 'cv', 'ceb', 'cs',
  'ch', 'cbk-zam', 'ny', 'sn', 'tum', 'cho', 'co', 'cy', 'da', 'dk',
  'pdc', 'de', 'dv', 'nv', 'dsb', 'dz', 'mh', 'et', 'el', 'eml', 'en',
  'myv', 'es', 'eo', 'ext', 'eu', 'ee', 'fa', 'hif', 'fo', 'fr', 'fy',
  'ff', 'fur', 'ga', 'gv', 'gd', 'gl', 'gan', 'ki', 'glk', 'gu',
  'got', 'hak', 'xal', 'ko', 'ha', 'haw', 'hy', 'hi', 'ho', 'hsb',
  'hr', 'io', 'ig', 'ilo', 'bpy', 'id', 'ia', 'ie', 'iu', 'ik', 'os',
  'xh', 'zu', 'is', 'it', 'he', 'jv', 'kl', 'kn', 'kr', 'pam', 'ka',
  'ks', 'csb', 'kk', 'kw', 'rw', 'ky', 'rn', 'sw', 'kv', 'kg', 'ht',
  'ku', 'kj', 'lad', 'lbe', 'lo', 'la', 'lv', 'lb', 'lt', 'lij', 'li',
  'ln', 'jbo', 'lg', 'lmo', 'hu', 'mk', 'mg', 'ml', 'mt', 'mi', 'mr',
  'arz', 'mzn', 'ms', 'cdo', 'mwl', 'mdf', 'mo', 'mn', 'mus', 'my',
  'nah', 'na', 'fj', 'nl', 'nds-nl', 'cr', 'ne', 'new', 'ja', 'nap',
  'ce', 'pih', 'no', 'nb', 'nn', 'nrm', 'nov', 'ii', 'oc', 'mhr',
  'or', 'om', 'ng', 'hz', 'uz', 'pa', 'pi', 'pag', 'pnb', 'pap', 'ps',
  'km', 'pcd', 'pms', 'tpi', 'nds', 'pl', 'tokipona', 'tp', 'pnt',
  'pt', 'aa', 'kaa', 'crh', 'ty', 'ksh', 'ro', 'rmy', 'rm', 'qu',
  'ru', 'sah', 'se', 'sm', 'sa', 'sg', 'sc', 'sco', 'stq', 'st', 'tn',
  'sq', 'scn', 'si', 'simple', 'sd', 'ss', 'sk', 'cu', 'sl', 'szl',
  'so', 'ckb', 'srn', 'sr', 'sh', 'su', 'fi', 'sv', 'tl', 'ta', 'kab',
  'roa-tara', 'tt', 'te', 'tet', 'th', 'ti', 'tg', 'to', 'chr', 'chy',
  've', 'tr', 'tk', 'tw', 'udm', 'bug', 'uk', 'ur', 'ug', 'za', 'vec',
  'vi', 'vo', 'fiu-vro', 'wa', 'zh-classical', 'vls', 'war', 'wo',
  'wuu', 'ts', 'yi', 'yo', 'zh-yue', 'diq', 'zea', 'bat-smg', 'zh',
  'zh-tw', 'zh-cn'
];

function iKiwiSpecialOrderCompare(first, second)
{
  var firstInterWiki = iKiwiInterWiki.exec(first);
  var secondInterWiki = iKiwiInterWiki.exec(second);

  return iKiwiSpecialOrder.indexOf(firstInterWiki[1]) - iKiwiSpecialOrder.indexOf(secondInterWiki[1]);
}

function iKiwiDistantWiki()
{
  return document.getElementById('iKiwiDistantWiki').value;
}

function iKiwiUrl(wiki, page)
{
  return '//' + wiki + '.wikipedia.org' + mw.config.get('wgScript') + '?title=' + encodeURIComponent(page);
}

function iKiwiLocalUrl(page)
{
  return iKiwiUrl(mw.config.get('wgContentLanguage'), page);
}

function iKiwiDistantUrl(page)
{
  return iKiwiUrl(iKiwiDistantWiki(), page);
}

function iKiwiError(message)
{
  document.getElementById('iKiwiExtPage').setAttribute('style', 'background-color:#D66;');
  with (document.getElementById('iKiwiWarning'))
  {
    innerHTML = ' ' + message;
    setAttribute('style', 'color:red;');
  }
  document.getElementById('iKiwiSubmit').setAttribute('disabled', 'disabled');

  var textarea = document.getElementById('iKiwiText');
  if (textarea)
  {
    textarea.setAttribute('style', 'display:none;');
    document.getElementById('iKiwiDiff').setAttribute('style', 'display:none;');
  }
}

function iKiwiExtractInterWikis(text)
{
  var lines = text.split('\n');
  var interWikis = new Array();
  for (var lineId = 0; lineId < lines.length; ++lineId)
  {
    var interWiki = iKiwiInterWiki.exec(lines[lineId]);
    if (interWiki)
      interWikis.push(interWiki[0].replace(/^\s+/g, '').replace(/\s+$/g, '').replace(/_/g, ' '));
  }
  return interWikis;
}

function iKiwiRemoveInterWikis(text)
{
  var lines = text.split('\n');
  for (var lineId = lines.length - 1; lineId >= 0; --lineId)
    if (!iKiwiInterWiki.exec(lines[lineId]) && !iKiwiBlank.exec(lines[lineId]))
      return lines.slice(0, lineId + 1).join('\n');
  return text;
}

function iKiwiJSONPCallBack(json)
{
  for (var page in json.query.pages)
  {
    if (typeof (json.query.pages[page].missing) == 'undefined')
    {
      var text = json.query.pages[page].revisions[0]['*'];

      if (typeof (json.query.redirects) != 'undefined')
	for (var redirect in json.query.redirects)
	  iKiwiRedirectCallBack(json.query.redirects[redirect].to);
    } else {
      var text = "";
    }
    break;
  }

  if (text)
  {
    if (iKiwiTranslationId)
    {
      iKiwiRedirectCallBack(json.query.pages[page].title);
    }

    iKiwiAddInterWikisCallBack(text);
  } else {
    if (iKiwiTranslationId < iKiwiTranslations.length)
    {
      var translation = iKiwiTranslations[iKiwiTranslationId++];
      iKiwiJSONPRequest(document.getElementById('iKiwiDistantWiki').value, translation);
    } else {
      iKiwiSuggestCallBack();
    }
  }
}

function iKiwiJSONPRequest(distantWiki, page)
{
  var jsonp = document.createElement('script');
  jsonp.setAttribute('src', '//' + distantWiki + '.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&redirects&format=json&titles=' + page + '&callback=iKiwiJSONPCallBack');
  jsonp.setAttribute('type','text/javascript');
  document.getElementsByTagName('head')[0].appendChild(jsonp);
}

function iKiwiGetForm()
{
  var xhr = sajax_init_object();

  xhr.open('GET', mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=' + encodeURIComponent(mw.config.get('wgPageName')) + '&action=edit', false);
  xhr.send('');

  return $(xhr.responseText);
}

function iKiwiPostRequest(request, editForm, text, summary)
{
  var inputs = editForm.find('input');
  for (inputId = 0; inputId < inputs.length; ++inputId)
    switch (inputs[inputId].name)
    {
      case 'wpStarttime':
        var wpStarttime = inputs[inputId].value;
        break;
      case 'wpEdittime':
        var wpEdittime = inputs[inputId].value;
        break;
      case 'wpEditToken':
        var wpEditToken = inputs[inputId].value;
        break;
      default:
        break;
    }

  var parameters = 'wp' + request + '=1'
    + '&wpTextbox1=' + encodeURIComponent(text)
    + '&wpStarttime=' + encodeURIComponent(wpStarttime)
    + '&wpEdittime=' + encodeURIComponent(wpEdittime)
    + '&wpEditToken=' + encodeURIComponent(wpEditToken)
    + '&wpSummary=' + encodeURIComponent('[[' + iKiwiDocPage + '|iKiwi]] : ' + summary)
    + '&wpMinoredit=on';

  if (document.getElementById('iKiwiFollow').checked)
    parameters += '&wpWatchthis=on';

  var xhr = sajax_init_object();

  with (xhr)
  {
    open('POST', mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=' + encodeURIComponent(mw.config.get('wgPageName')) + '&action=submit', false);

    setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    send(parameters);
  }

  return xhr;
}

function iKiwiPreview(editForm, text, summary)
{
  var xhr = iKiwiPostRequest('Diff', editForm, text, summary);
  return $(xhr.responseText);
}

function iKiwiPublish()
{
  iKiwiPostRequest('Save', document.editForm, document.newText, document.summary);
  iKiwiSelectPage();
}

function iKiwiRedirectCallBack(page)
{
  var extPage = document.getElementById('iKiwiExtPage');
  var distantPageName = iKiwiDistantWiki() + ':' + extPage.value;

  var redirect = document.getElementById('iKiwiRedirect');
  redirect.innerHTML = ' ' + iKiwiI18n(mw.config.get('wgUserLanguage'), 'redirectfrom') + ' <a href="' + iKiwiDistantUrl(extPage.value) + '&redirect=no" title="' + distantPageName + '">' + distantPageName + '</a>';
  redirect.setAttribute('style', 'display:inline;');
  extPage.value = page;
}

function iKiwiSuggestCallBack()
{
  // TODO /w/api.php?action=query&list=search&srsearch=<SUBJECT>
  iKiwiError(iKiwiI18n(mw.config.get('wgUserLanguage'), 'noarticle'));
}

function iKiwiAddInterWikisCallBack(text)
{
  var editForm = iKiwiGetForm();

  var originalText = editForm.find('#wpTextbox1')[0].value;

  var newText = iKiwiRemoveInterWikis(originalText);

  var interWikis = [];
  var originalInterWikis = iKiwiExtractInterWikis(originalText);
  var distantInterWikis = iKiwiExtractInterWikis(text);

  var distantPageName = iKiwiDistantWiki() + ':' + document.getElementById('iKiwiExtPage').value;

  interWikis.push('[[' + distantPageName + ']]');

  var distantWikis = [ iKiwiDistantWiki() ];

  for (var originalInterWikiId = 0; originalInterWikiId < originalInterWikis.length; ++originalInterWikiId)
    if (interWikis.indexOf(originalInterWikis[originalInterWikiId]) == -1)
    {
      var interWiki = iKiwiInterWiki.exec(originalInterWikis[originalInterWikiId]);
      if (distantWikis.indexOf(interWiki[1]) != -1) {
          iKiwiError(iKiwiI18n(mw.config.get('wgUserLanguage'), 'twolocallinks') + interWiki[1]);
          return;
      }
      interWikis.push(originalInterWikis[originalInterWikiId]);
      distantWikis.push(interWiki[1]);
    }

  var originalLinksCount = distantWikis.length;

  for (var distantInterWikiId = 0; distantInterWikiId < distantInterWikis.length; ++distantInterWikiId)
    if (interWikis.indexOf(distantInterWikis[distantInterWikiId]) == -1)
    {
      if (distantInterWikis[distantInterWikiId].indexOf('[[' + mw.config.get('wgContentLanguage') + ':') != -1)
      {
        if (distantInterWikis[distantInterWikiId].indexOf('[[' + mw.config.get('wgContentLanguage') + ':' +  mw.config.get('wgPageName').replace(/_/g, ' ')) == -1)
        {
          var interWiki = iKiwiInterWiki.exec(distantInterWikis[distantInterWikiId]);
          iKiwiError(iKiwiI18n(mw.config.get('wgUserLanguage'), 'alreadylinked') + ' <a href="/wiki/' + interWiki[3] + '" title="' + interWiki[3] + '">' + interWiki[3] + '</a>');
          return;
        }
      } else {
        var interWiki = iKiwiInterWiki.exec(distantInterWikis[distantInterWikiId]);
        var distantWikiId = distantWikis.indexOf(interWiki[1]);
        if (distantWikiId != -1) {
            if (distantWikiId < originalLinksCount) {
              iKiwiError(iKiwiI18n(mw.config.get('wgUserLanguage'), 'twolinks') + interWiki[1]);
            } else {
              iKiwiError(iKiwiI18n(mw.config.get('wgUserLanguage'), 'twodistantlinks') + interWiki[1] + ': <a href="' + iKiwiDistantUrl(document.getElementById('iKiwiExtPage').value) + '&redirect=no" title="' + distantPageName + '">' + distantPageName + '</a>');
            }
            return;
        }
        interWikis.push(distantInterWikis[distantInterWikiId]);
        distantWikis.push(interWiki[1]);
      }
    }

  var nbNewInterWikis = interWikis.length - originalInterWikis.length;

  if (!nbNewInterWikis)
  {
    iKiwiError(iKiwiI18n(mw.config.get('wgUserLanguage'), 'nomoreiw'));
    return;
  }

  if (iKiwiSpecialOrdered.indexOf(mw.config.get('wgContentLanguage')) != -1)
    interWikis.sort(iKiwiSpecialOrderCompare);
  else
    interWikis.sort();

  newText += '\n\n'

  for (var interWikiId = 0; interWikiId < interWikis.length; ++interWikiId)
      newText += interWikis[interWikiId] + '\n';

  document.getElementById('iKiwiExtPage').removeAttribute('style');
  with (document.getElementById('iKiwiWarning'))
  {
    if (nbNewInterWikis > 1)
      innerHTML = ' ' + nbNewInterWikis + ' ' + iKiwiI18n(mw.config.get('wgUserLanguage'), 'iwsadded');
    else
      innerHTML = ' ' + nbNewInterWikis + ' ' + iKiwiI18n(mw.config.get('wgUserLanguage'), 'iwadded');
    innerHTML += ' ' + iKiwiI18n(mw.config.get('wgUserLanguage'), 'from') + ' <a href="' + iKiwiDistantUrl(document.getElementById('iKiwiExtPage').value) + '&redirect=no" title="' + distantPageName + '">' + distantPageName + '</a>';
    setAttribute('style', 'color:green;');
  }
  document.getElementById('iKiwiSubmit').removeAttribute('disabled');

  document.editForm = editForm;
  document.newText = newText;
  document.summary = iKiwiI18n(mw.config.get('wgContentLanguage'), 'adding') + ' ' + nbNewInterWikis + ' interWiki' + (nbNewInterWikis > 1 ? 's' : '') + ' ' + iKiwiI18n(mw.config.get('wgContentLanguage'), 'from') + ' [[:' + distantPageName + ']]';

  if (location.href.indexOf('&iKiwiFromPIW') != -1)
    document.summary += ' (Détecté par [[P:IW]])';

  var preview = iKiwiPreview(editForm, newText, document.summary);
  var diff = preview.find('#wikiDiff')[0];
  diff.setAttribute('id', 'iKiwiDiff');

  var textarea = document.getElementById('iKiwiText');
  if (!textarea)
  {
    textarea = document.createElement('textarea');
    with (textarea)
    {
      setAttribute('id', 'iKiwiText');
      setAttribute('rows', 10);
      setAttribute('readonly', 'readonly');
      appendChild(document.createTextNode(text));
    }

    var fieldSet = document.getElementById('iKiwiFieldSet');
    var follow = document.getElementById('iKiwiFollow');

    fieldSet.insertBefore(textarea, follow);
    fieldSet.insertBefore(document.createElement('br'), follow);

    document.getElementsByTagName('head')[0].innerHTML+='<link rel="stylesheet" href="//bits.wikimedia.org/skins-1.5/common/diff.css?257z23" type="text/css" media="all" />';

    fieldSet.insertBefore(diff, follow);
  } else {
    textarea.value = text;
    textarea.setAttribute('style', 'display:block;');

    document.getElementById('iKiwiFieldSet').replaceChild(diff, document.getElementById('iKiwiDiff'));
  }
}

function iKiwiAddInterWikis()
{
  document.getElementById('iKiwiRedirect').setAttribute('style', 'display:none;');

  var distantWiki = document.getElementById('iKiwiDistantWiki').value;
  var page = document.getElementById('iKiwiExtPage').value;
  var follow = document.getElementById('iKiwiFollow').checked;

  iKiwiTranslationId = 0;
  iKiwiTranslations = iKiwiTranslate(mw.config.get('wgContentLanguage'), iKiwiDistantWiki(), page);

  iKiwiJSONPRequest(distantWiki, page);
}

function iKiwiSelectPage(autoPreview)
{
  var iForm = document.getElementById('iKiwiForm');

  if (iForm) {
    iForm.setAttribute('style', 'display:' + iKiwiStates[iKiwiPanelNextState] + ';');
    iKiwiPanelNextState = !iKiwiPanelNextState + 0;
    document.getElementById('iKiwiLinks').setAttribute('style', 'display:' + iKiwiStates[iKiwiPanelNextState] + ';');
  } else {
    document.getElementById('iKiwiLinks').setAttribute('style', 'display:none;');

    iForm = document.createElement('form');
    iForm.setAttribute('id', 'iKiwiForm');

    var fieldSet = document.createElement('fieldset');
    fieldSet.setAttribute('id', 'iKiwiFieldSet');

    var link = document.createElement('a');
    with (link)
    {
      setAttribute('href', 'javascript:iKiwiSelectPage();');
      setAttribute('id', 'iKiwiHidePanel');
      setAttribute('title', 'Masquer le panneau iKiwi');
      appendChild(document.createTextNode('[iKiwi — ' + iKiwiVersion + ']'));
    }

    var doc = document.createElement('a');
    with (doc)
    {
      setAttribute('href', iKiwiLocalUrl(iKiwiDocPage));
      setAttribute('id', 'iKiwiDoc');
      setAttribute('title', 'Documentation');
      appendChild(document.createTextNode('(documentation)'));
    }

    var legend = document.createElement('legend');
    with (legend)
    {
      appendChild(link);
      appendChild(document.createTextNode(' '));
      appendChild(doc);
    }

    var label = document.createElement('label');
    with (label)
    {
      setAttribute('for', 'iKiwiExtPage');
      appendChild(document.createTextNode(iKiwiI18n(mw.config.get('wgUserLanguage'), 'extpage')));
    }

    var distantLanguage = /iKiwiSourceLanguage=([^&]+)/.exec(location.href);
    if (distantLanguage)
    {
      iKiwiDefaultDistantWiki = distantLanguage[1];
      if (iKiwiDistantWikis.indexOf(iKiwiDefaultDistantWiki) == -1)
      {
        iKiwiDistantWikis.push(iKiwiDefaultDistantWiki);
	iKiwiDistantWikis.sort();
      }
    }

    var distantWiki = document.createElement('select');
    distantWiki.setAttribute('id', 'iKiwiDistantWiki');
    for (var wikiId = 0; wikiId < iKiwiDistantWikis.length; ++wikiId)
    {
      var option = document.createElement('option');
      with (option)
      {
        setAttribute('id', 'iKiwiDistantWiki-' + iKiwiDistantWikis[wikiId]);
        setAttribute('value', iKiwiDistantWikis[wikiId]);
        appendChild(document.createTextNode(iKiwiDistantWikis[wikiId]));
      }
      if (iKiwiDistantWikis[wikiId] == iKiwiDefaultDistantWiki)
        option.setAttribute('selected', 'selected');
      distantWiki.appendChild(option);
    }

    // TODO autocomplétion
    var input = document.createElement('input');
    with (input)
    {
      setAttribute('id', 'iKiwiExtPage');
      setAttribute('type', 'text');
      setAttribute('value', mw.config.get('wgPageName').replace(/_/g, ' '));
    }

    var warning = document.createElement('strong');
    with (warning)
    {
      setAttribute('id', 'iKiwiWarning');
      setAttribute('style', 'display:none');
      appendChild(document.createTextNode(''));
    }

    var redirect = document.createElement('em');
    with (redirect)
    {
      setAttribute('id', 'iKiwiRedirect');
      setAttribute('style', 'display:none;');
      appendChild(document.createTextNode(''));
    }

    var follow = document.createElement('input');
    with (follow)
    {
      setAttribute('id', 'iKiwiFollow');
      setAttribute('type', 'checkbox');
      if (!document.getElementById('ca-watch') || iKiwiWatchOthers || iKiwiWatchMain && !mw.config.get('wgNamespaceNumber'))
        setAttribute('checked', 'checked');
    }

    var followLabel = document.createElement('label');
    with (followLabel)
    {
      setAttribute('for', 'iKiwiFollow');
      appendChild(document.createTextNode(iKiwiI18n(mw.config.get('wgUserLanguage'), 'follow')));
    }

    var submit = document.createElement('input');
    with (submit)
    {
      setAttribute('id', 'iKiwiSubmit');
      setAttribute('name', 'iKiwiSubmit');
      setAttribute('type', 'submit');
      setAttribute('value', iKiwiI18n(mw.config.get('wgUserLanguage'), 'publish'));
      setAttribute('disabled', 'disabled');
      setAttribute('onClick', 'javascript:iKiwiPublish(); return false;')
    }

    var preview = document.createElement('input');
    with (preview)
    {
      setAttribute('id', 'iKiwiPreview');
      setAttribute('name', 'iKiwiPreview');
      setAttribute('type', 'submit');
      setAttribute('value', iKiwiI18n(mw.config.get('wgUserLanguage'), 'preview'));
      setAttribute('onClick', 'javascript:iKiwiAddInterWikis(); return false;')
    }

    iForm.appendChild(fieldSet);

    with (fieldSet)
    {
      appendChild(legend);
      appendChild(label);
      appendChild(document.createElement('br'));
      appendChild(distantWiki);
      appendChild(document.createTextNode(' '));
      appendChild(input);
      appendChild(warning);
      appendChild(redirect);
      appendChild(document.createElement('br'));
      appendChild(follow);
      appendChild(followLabel);
      appendChild(document.createElement('br'));
      appendChild(submit);
      appendChild(preview);
    }

    document.getElementById('content').insertBefore(iForm, document.getElementById('firstHeading'));
  }

  if (!iKiwiPanelNextState && typeof (autoPreview) != 'undefined' && autoPreview)
    iKiwiAddInterWikis();
}

function iKiwiAddLinks()
{
  var link1 = document.createElement('a');
  with (link1)
  {
    setAttribute('href', 'javascript:iKiwiSelectPage();');
    setAttribute('id', 'iKiwiDisplayPanel');
    setAttribute('title', iKiwiI18n(mw.config.get('wgUserLanguage'), 'panel'));
    appendChild(document.createTextNode('iKiwi'));
  }

  var link2 = document.createElement('a');
  with (link2)
  {
    setAttribute('href', 'javascript:iKiwiSelectPage(true);');
    setAttribute('id', 'iKiwiDisplayPanel');
    setAttribute('title', iKiwiI18n(mw.config.get('wgUserLanguage'), 'panel') + ' (' + iKiwiI18n(mw.config.get('wgUserLanguage'), 'autopreview') + ')');
    appendChild(document.createTextNode('+'));
  }

  var links = document.createElement('p');
  with (links)
  {
    setAttribute('id', 'iKiwiLinks');
    appendChild(document.createTextNode('['));
    appendChild(link1);
    appendChild(document.createTextNode('|'));
    appendChild(link2);
    appendChild(document.createTextNode(']'));
  }

  document.getElementById('content').insertBefore(links, document.getElementById('firstHeading'));
}

function iKiwiAddPreviewLinks()
{
  var lis = document.getElementsByTagName('li');
  for (var liId = 0; liId < lis.length; ++liId)
  {
    var sourceLanguage = 'en';
    var language = /\/([a-z]{2})fr/.exec(location.href);
    if (language)
      sourceLanguage = language[1];
    // TODO set iKiwiSourceArticle
    // TODO add another iKiwi link for the distant wiki article
    var interWiki = iKiwiHtmlInterWiki.exec(lis[liId].innerHTML);
    if (interWiki)
      lis[liId].innerHTML = lis[liId].innerHTML.replace(iKiwiHtmlInterWiki, interWiki[0] + ' <sup><a href="' + mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/index.php?title=' + interWiki[1] + '&iKiwiAutoPreview&iKiwiFromPIW&iKiwiSourceLanguage=' + sourceLanguage + '" title="' + interWiki[2] + ' (iKiwi)"><img alt="iKiwi" src="//upload.wikimedia.org/wikipedia/commons/e/eb/Demi_kiwi.gif" width="10px" /></a></sup>');
  }
}

function iKiwi()
{
  var autoPreview = location.href.indexOf('&iKiwiAutoPreview') != -1;
  if ((iKiwiDisplayPanel || autoPreview) && [0, 2, 4, 6, 10, 12, 14, 100, 102, 104].indexOf(mw.config.get('wgNamespaceNumber')) != -1)
    iKiwiAddLinks();
  if (autoPreview)
    iKiwiSelectPage(true);
  if (location.href.indexOf('Projet:Interwikification/') != -1)
    iKiwiAddPreviewLinks();
}

$(iKiwi);
{{bottomLinkPreText}} {{bottomLinkText}}
Utilisateur:Arkanosis/iKiwi.js
Listen to this article

This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:

This article was just edited, click to reload
This article has been deleted on Wikipedia (Why?)

Back to homepage

Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}

Install Wikiwand

Install on Chrome Install on Firefox
Don't forget to rate us

Tell your friends about Wikiwand!

Gmail Facebook Twitter Link

Enjoying Wikiwand?

Tell your friends and spread the love:
Share on Gmail Share on Facebook Share on Twitter Share on Buffer

Our magic isn't perfect

You can help our automatic cover photo selection by reporting an unsuitable photo.

This photo is visually disturbing This photo is not a good choice

Thank you for helping!


Your input will affect cover photo selection, along with input from other users.

X

Get ready for Wikiwand 2.0 🎉! the new version arrives on September 1st! Don't want to wait?