Kasutaja:Larus ridibundus/gadget/iw.js
Märkus: võimalik, et pärast avaldamist tuleb muudatuste nägemiseks brauseri puhver tühjendada.
- Firefox / Safari: hoia all Shift-klahvi ja klõpsa Laadi uuesti või vajuta kas Ctrl-F5 või Ctrl-R (Macis ⌘-R).
- Google Chrome: vajuta Ctrl-Shift-R (Macis ⌘-Shift-R).
- Edge: hoia all Ctrl-klahvi ja klõpsa Värskenda või vajuta Ctrl-F5.
( function ( mw, $ ) {
var i18nData = {
'en': {
'box-title': 'Import interwiki',
'box-warning': 'Warning: This script automatically imports languages links from one wiki without a check of conflicts. You have to check all the interwikis in the page of the chosen wiki before uploading them to Wikidata!',
'box-lang': 'from: ',
'box-updateLabels': 'Auto-complete empty labels with the name of the related link.',
'import': 'Import',
'error-api': 'Communication error with the API!',
'error-wiki': 'The selected wiki is unknown!',
'error-page': 'The page does not exist!',
'error-pageNotFound': 'No link found for the selected wiki!',
'error-save': 'Save error: ',
'success-links': 'Links imported!',
'success-labels': 'Labels imported!',
'nolinkstoupdate': 'All the links are already imported. Nothing to do!'
}
};
i18nData.no = i18nData.nb;
var parts = mw.config.get( 'wgUserLanguage' ).split("-");
if( parts[1]=='hans' || parts[1]=='cn' || parts[1]=='sg' || parts[1]=='my' ) {
var lang = 'zh-hans';
} else if ( parts[1]=='hant' || parts[1]=='hk' || parts[1]=='tw' || parts[1]=='mo' ) {
var lang = 'zh-hant';
} else if ( i18nData[parts[0]] ) {
var lang = parts[0];
} else {
var lang = 'en';
}
var notification = mw.util.getParamValue( 'slurpnotif' );
if ( notification !== null ) {
var notifications = notification.split('|');
for( var i in notifications ) {
mw.notify( i18n( notifications[i] ) );
}
}
var itemId = mw.config.get( 'wbEntityId' );
if( !itemId ) {
return;
}
/**
* Return the localized version of a message
*/
function i18n( key ) {
if( i18nData[ lang ][ key ] ) {
return i18nData[ lang ][ key ];
} else {
return i18nData[ 'en' ][ key ];
}
}
/**
* Return the language code from the ID of the Wiki
*/
function getLanguageCodeFromWikiId( wiki ) {
var splited = wiki.match( /^(.*)wiki$/i );
if( !splited[1] ) {
return '';
} else {
return splited[1].replace(/_/g, '-');
}
}
/**
* Create the dialog and add a link in toolBox
*/
function init() {
mw.loader.using( ['jquery.ui'], function() {
var formFind = '<div id="slurpInterwiki" title="' + i18n( 'box-title' ) + '"><form>';
formFind += '<p><label for="slurpInterwiki-lang">' + i18n( 'box-lang' ) + '</label><select name="slurpInterwiki-lang" id="slurpInterwiki-lang"></select></p>';
formFind += '<p><input checked type="checkbox" name="slurpInterwiki-updateLabels" id="slurpInterwiki-updateLabels" /> <label for="slurpInterwiki-updateLabels">' + i18n( 'box-updateLabels' ) + '</label></p>';
formFind += '<p>' + i18n( 'box-warning' ) + '</p>';
formFind += '<p class="error" id="slurpInterwiki-error"></p>';
formFind += '</form></div>';
var messageFind = $( formFind ).appendTo( '#content' );
messageFind.dialog( {
autoOpen: false,
modal: true,
width: 500,
buttons: [ {
id: 'slurpInterwiki-button-import',
text: i18n( 'import' ),
click: function() {
work();
}
} ]
} );
var portletLink = mw.util.addPortletLink( 'p-tb', '#', i18n( 'box-title' ), 't-slurpInterwiki', i18n( 'box-title' ) );
$( portletLink ).click( show );
} );
}
/**
* Show the dialog
*/
function show() {
getItemLinks( function( links ) {
formFind = $( '#slurpInterwiki-lang' );
formFind.empty();
var languagesLabel = mw.config.get('wgULSLanguages') || {};
for( var i in links ) {
var languageCode = getLanguageCodeFromWikiId( links[i].site );
var label = links[i].site;
if( languageCode !== '' ) {
label = languageCode;
if( languagesLabel[languageCode] ) {
label += ' (' + languagesLabel[languageCode] + ')';
}
}
formFind.append( '<option value="' + links[i].site + '">' + label + '</option>' );
}
$( '#slurpInterwiki-error' ).html( '' );
$( 'div#slurpInterwiki' ).dialog( 'open' );
} );
return false;
}
/**
* Called on error
*/
function onError() {
$.removeSpinner( 'slurpInterwiki' );
$( '#slurpInterwiki-button-import' ).button( 'option', 'disabled', false );
}
/**
* Called on API error
*/
function onApiError( jqXHR, textStatus, errorThrown ) {
alert( i18n( 'error-api' ) );
onError();
}
/**
* Update interLanguages links from the wiki selected in the box. Works only for Wikipedias.
*/
function work() {
mw.loader.using( ['jquery.spinner'], function() {
$.createSpinner( {
size: 'large',
type: 'block',
id: 'slurpInterwiki'
} ).appendTo( 'div#slurpInterwiki' );
$( '#slurpInterwiki-button-import' ).button( 'option', 'disabled', true );
getItem( function( item ) {
if( item.sitelinks ) {
links = item.sitelinks;
} else {
links = {};
}
var wiki = $( '#slurpInterwiki-lang' ).val();
if( !links[wiki] ) {
alert( i18n( 'error-pageNotFound' ) );
onError();
return;
}
var page = links[wiki].title;
getLanguageLinks( wiki, page, function( interlangLinks ) {
getItem( function( item ) {
var itemValue = {};
var changed = [];
var itemLinks = {};
if( item.sitelinks ) {
itemLinks = item.sitelinks;
}
var linkChanged = false;
for( var i in interlangLinks ) {
var regex = /^(.*)old$/i;
if( regex.test( interlangLinks[i].lang ) && interlangLinks[i].lang !== 'be-x-old' ) {
mw.log( 'Refused wiki: ' + interlangLinks[i].lang );
} else {
var site = interlangLinks[i].lang.replace(/-/g, '_') + 'wiki';
if( !itemLinks[site] && interlangLinks[i]['*'].indexOf("#") === -1) {
itemLinks[site] = {
'site': site,
'title': interlangLinks[i]['*']
};
linkChanged = true;
}
}
}
if( linkChanged ) {
itemValue.sitelinks = itemLinks;
changed.push( 'sitelinks' );
}
//Update labels
if( $( '#slurpInterwiki-updateLabels' ).attr( 'checked' ) ) {
var labels = {};
if( item.labels ) {
labels = item.labels;
}
var labelChanged = false;
for( var site in itemLinks ) {
var langs = [getLanguageCodeFromWikiId( itemLinks[site].site )];
if( langs[0] == 'simple' ) {
continue;
}
switch( langs[0] ) {
case 'en':
langs = ['en', 'en-ca', 'en-gb'];
break;
/*case 'zh':
langs = ['zh', 'zh-cn', 'zh-tw', 'zh-sg', 'zh-mo', 'zh-hans', 'zh-hant', 'zh-hk', 'zh-my'];
break;*/
case 'zh-yue':
langs = ['zh-yue', 'yue'];
break;
case 'pt':
langs = ['pt', 'pt-br'];
break;
case 'de':
langs = ['de', 'de-ch'];
break;
case 'no':
langs = ['nb'];
break;
}
for( var j in langs ) {
var language = langs[j];
if( !labels[language] ) {
var value = itemLinks[site].title.replace( /\(.*\)/g, '' );
if( language === 'es' || language === 'pt' || language === 'pt-br' ) {
value = value.replace( /^Anexo:/, '' );
}
if( language === 'cs' ) {
value = value.replace( /^Příloha:/, '' );
}
if( language === 'de-ch' ) {
value = value.replace( /ß/g, 'ss' );
}
if( language === 'fa' ) {
value = itemLinks[site].title;//In Farsi () are important
}
labels[language] = {
'language': language,
'value': value
};
labelChanged = true;
}
}
}
if( labelChanged ) {
itemValue.labels = labels;
changed.push( 'labels' );
}
}
//Push changes
if( changed.length != 0 ) {
//Get list of notification and comment
var notif = [];
var comment = '';
if( $.inArray( 'sitelinks', changed ) !== -1 ) {
notif.push( 'success-links' );
comment += 'Update of interwikis from ' + wiki + '.'
}
if( $.inArray( 'labels', changed ) !== -1 ) {
notif.push( 'success-labels' );
comment += ' Update of labels.'
}
setItem( itemValue, changed, function() {
location.href = mw.util.getUrl( mw.config.get( 'wgPageName' ) ) + '?slurpnotif=' + notif.join('|');
}, comment );
} else {
mw.notify( i18n( 'nolinkstoupdate' ) );
$( 'div#slurpInterwiki' ).dialog( 'close' );
onError();
}
} );
} );
} );
} );
}
/**
* Update the item
* @param success function called on success
*/
function updateItem( links ) {
}
/**
* Return the item
* @param success function called on success
*/
function getItem( success ) {
$.ajax( {
url: mw.util.wikiScript( 'api' ),
data: {
'format': 'json',
'action': 'wbgetentities',
'ids': itemId
}
} )
.done(function( data ) {
if( data.success && data.entities[itemId] ) {
success( data.entities[itemId] );
} else {
onApiError();
}
} )
.fail(onApiError);
}
/**
* Return the existings links of a wiki
* @param success function called on success
*/
function getItemLinks( success ) {
getItem( function( item ) {
if( item.sitelinks ) {
success( item.sitelinks );
} else {
success( {} );
}
} );
}
/**
* Return the existings links in a page of a wiki
* @param wiki string id of the wiki. Warning: Currently only Wikipedias are supported.
* @param page string name of the page
* @param success function called on success
*/
function getLanguageLinks( wiki, page, success ) {
var langCode = getLanguageCodeFromWikiId( wiki );
if( !langCode === '' ) {
alert( i18n( 'error-wiki' ) );
onError();
return [];
}
$.ajax( {
url: '//' + langCode + '.wikipedia.org/w/api.php',
data: {
'format': 'json',
'action': 'query',
'titles': page,
'prop': 'langlinks',
'lllimit': 400
},
dataType: 'jsonp'
} )
.done(function( data ) {
if( data.query.pages ) {
for( var id in data.query.pages ) {
if( id == -1 ) {
alert( i18n( 'error-page' ) );
onError();
} else {
if( data.query.pages[id].langlinks ) {
success( data.query.pages[id].langlinks );
} else {
success( [] );
}
}
}
} else {
onApiError();
}
} )
.fail(onApiError);
}
/**
* Set the item links
* @param item array the item
* @param include array of type of changed information (labels, aliases....)
* @param success function called on success
* @param summary string
*/
function setItem( item, include, success, summary ) {
var exclude = ['pageid', 'ns', 'title', 'lastrevid', 'touched', 'aliases', 'labels', 'descriptions', 'sitelinks'];
for( var i in include ) {
exclude.splice( $.inArray(include[i], exclude), 1 );
}
$.ajax( {
type: 'POST',
url: mw.util.wikiScript( 'api' ),
data: {
'format': 'json',
'action': 'wbeditentity',
'id': itemId,
'type': 'item',
'token': mw.user.tokens.get( 'csrfToken' ),
'data': $.toJSON( item ),
'summary': summary,
'exclude': exclude.join('|')
}
} )
.done(function( data ) {
if( data.error && data.error.info ) {
var errorInfo = data.error.info;
errorInfo = errorInfo.replace( /\[\[([^\]]*)\]\]/g, '<a href="' + mw.config.get( 'wgServer' ) + '/wiki/$1">$1</a>' );
errorInfo =errorInfo.replace( /\wiki:/g,':')//correcting wiki link
errorInfo=errorInfo.replace( /\*/g, '<br>*' )//to have each errors in a line
$( '#slurpInterwiki-error' ).html( i18n( 'error-save' ) + errorInfo );
onError();
} else {
success(); //TODO Manage possibles errors
}
} )
.fail(onApiError);
}
$( document ).ready( init );
} ( mediaWiki, jQuery ) );