לדלג לתוכן

משתמש:מ. רובין/ניסוי.js – הבדלי גרסאות

מתוך חב"דפדיה, אנציקלופדיה חב"דית חופשית
מ. רובין (שיחה | תרומות)
אין תקציר עריכה
מ. רובין (שיחה | תרומות)
אין תקציר עריכה
שורה 1: שורה 1:
*/
/* _____________________________________________________________________________________________________
if ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) $(function(){
* |                                                                                                    |
var titleNoBrackets = /(.+?)( \(|$)/.exec(mw.config.get('wgTitle')), allowedSuffix, allowedPrefix;
* |                    === WARNING: GLOBAL GADGET FILE ===                                             |
if (titleNoBrackets) titleNoBrackets = titleNoBrackets[1];
* |                  Changes to this page affect many users.                                            |
else return;
* | Please discuss changes on the talk page or on [[MediaWiki talk:Gadgets-definition]] before editing. |
* |____________________________________________________________________________________________________ |
*
*/
( function ( mw, $ ) {
'use strict';


// allowedSuffix and allowedPrefix to have strict match for valid words (BOOK => BOOKs and not BOOKmark). default is non strict (which works better for long title)
var itemId = mw.config.get( 'wbEntityId' );
switch ( mw.config.get('wgContentLanguage') ) {
if ( !itemId || mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
case 'he':
!mw.config.get( 'wbIsEditView' ) ||
allowedSuffix = '(?=ים|ות|[^א-ת])';
!mw.config.get( 'wgIsProbablyEditable' )
allowedPrefix = '(?:[כלבמשהו]|[^א-ת])';
) {
break;
return;
default:
}
allowedSuffix = 's?[^a-z]';
allowedPrefix = '';
}


switch (mw.config.get('wgUserLanguage') ) {
var translations = require( './slurpInterwiki-i18n.json' );
case 'he':
mw.messages.set({
'qlinker-edit' : 'עריכה מהירה',
'qlinker-cancel' : 'ביטול',
'linkify-summary': 'הוספת קישור ל[[$1]]',
'qlinker-save-success': 'שמירת $1 בוצעה בהצלחה!',
'qlinker-save-continue': 'שמירה',
'qlinker-skip': 'דילוג דף',
'qlinker-skip-match': 'דילוג מופע',
'qlinker-safe-search': 'חיפוש בטוח',
'qlinker-invoke': 'הוספת בזק של קישורים',
'qlinker-sidelink': 'הוספת קישורים',
'qlinker-no-results': 'לא נמצאו תוצאות',
'qlinker-confirm-masslink': 'לדף זה יש כבר הרבה קישורים, ונדרשת זהירות בהוספת הקישורים. האם נחוצים קישורים נוספים?'
});
break;
default:
mw.messages.set({
'qlinker-edit' : 'Quick edit',
'qlinker-cancel' : 'Cancel',
'linkify-summary': 'Adding link to [[$1]]',
'qlinker-save-success': '$1 has been saved successfully!',
'qlinker-save-continue': 'Save',
'qlinker-skip': 'Skip page',
'qlinker-skip-match': 'Skip match',
'qlinker-safe-search': 'Safe search',
'qlinker-invoke': 'Quickly add links',
'qlinker-sidelink': 'Add links',
'qlinker-no-results': 'No results found',
'qlinker-confirm-masslink': 'This page already has many links. Are you sure?'
});
break;
}


 
var chain = mw.language.getFallbackLanguageChain(),
function createQuickEditorDialog(searchRes, safeMode){
len = chain.length,
function QuickEditorDialog( config ) {
messages = {},
  this.contextRgx = new RegExp('(.[^\\[])(' + mw.util.escapeRegExp(titleNoBrackets) +')((?![^\\[\\{][\\]\\}]).*)', 'ig');
i;
  this.contextRgxLink = new RegExp('(.\\[\\[)([^\\]]+?)\\|(' + mw.util.escapeRegExp(titleNoBrackets) +')(\\]\\].)', 'ig');
for ( i = len - 1; i >= 0; i-- ) {
  this.pageI = -1;
if ( translations.hasOwnProperty( chain[ i ] ) ) {
  this.matchI = 0;
$.extend( messages, translations[ chain[ i ] ] );
  this.searchData = null;
}
  this.curPage = null;
  this.safeMode = safeMode;
  this.skipsCounter = 0;
  this.starttimestamp = null;
  this.timestamp = null;
  QuickEditorDialog.super.call( this, config );
}
}
OO.inheritClass( QuickEditorDialog, OO.ui.ProcessDialog );
mw.messages.set( messages );
 
// Specify a name for .addWindows()
QuickEditorDialog.static.name = 'QuickEditorDialog';
// Specify a title statically (or, alternatively, with data passed to the opening() method).  
QuickEditorDialog.static.title = mw.msg('qlinker-edit');


QuickEditorDialog.static.actions = [
var specialWikis = {
  { action: 'saveContinue', label: mw.msg('qlinker-save-continue'), flags: [ 'other', 'progressive' ], icon: 'link' },
'commonswiki': 'commons',
  { action: 'skipOne', label: mw.msg('qlinker-skip'), flags: [ 'other', 'progressive' ], icon: 'next' },
'metawiki': 'meta',
  { action: 'skipMatch', label: mw.msg('qlinker-skip-match'), flags: [ 'other', 'progressive' ], icon: 'arrowNext' },
'mediawikiwiki': 'mediawiki',
  { action: 'safeSearch', label: mw.msg('qlinker-safe-search'), flags: [ 'other' ], icon: 'search' },
'specieswiki': 'species',
  { label: mw.msg('qlinker-cancel'), flags: 'safe' }
'wikidatawiki': 'wikidata'
];
 
// Customize the initialize() function: This is where to add content to the dialog body and set up event handlers.
QuickEditorDialog.prototype.initialize = function () {
  // Call the parent method
  QuickEditorDialog.super.prototype.initialize.call( this );
  // Create and append a layout and some content.
  this.content = new OO.ui.PanelLayout( { padded: true, expanded: true } );
  this.$body.append( this.content.$element );
};
 
QuickEditorDialog.prototype.getBodyHeight = function () {
  return 400;
};
};


QuickEditorDialog.prototype.getSetupProcess = function ( data ) {
var notification = mw.util.getParamValue( 'slurpnotif' );
  data = data || {};
if ( notification !== null ) {
  return QuickEditorDialog.super.prototype.getSetupProcess.call( this, data )
var notifications = notification.split( '|' );
  .next( function () {
for ( i in notifications ) {
// Set up contents based on data
mw.notify( mw.message( notifications[ i ] ) );
    this.searchData = data.searchData.query;
}
    this.starttimestamp = data.searchData.curtimestamp;
}
this.nextPage();
  }, this );
};


// Use the getActionProcess() method to specify a process to handle the  
/**
// actions (for the 'save' action, in this example).
* Return the language code from the ID of the Wiki
QuickEditorDialog.prototype.getActionProcess = function ( action ) {
*/
  var dialog = this;
function getLanguageCodeFromWikiId( wiki ) {
  switch ( action ) {
var splited = wiki.match( /^(.*)wik[it][a-z]*$/i );
case 'skipOne':
if ( !splited[ 1 ] ) {
return new OO.ui.Process( function () {
return '';
  dialog.skipsCounter++;
} else {
  dialog.nextPage();
return splited[ 1 ].replace( /_/g, '-' );
}, this );
}
case 'skipMatch':
}
return new OO.ui.Process( function () {
  dialog.skipsCounter++;
  dialog.nextMatch();
}, this );
case 'saveContinue':
return new OO.ui.Process( function () {
  dialog.savePage();
}, this );
case 'safeSearch':
return new OO.ui.Process( function () {
  dialog.close()
  protectedSearchQuery(true);
}, this );
  }


  // Fallback to parent handler.
/**
  return QuickEditorDialog.super.prototype.getActionProcess.call( this, action );
* Return the site group from the ID of the Wiki
};
*/
 
function getGroupFromWikiId( wiki ) {
QuickEditorDialog.prototype.savePage = function ( ) {
if ( wiki.match( /^.*wikivoyage$/i ) ) {
if (this.curPage)
return 'wikivoyage';
{
} else if ( wiki.match( /^.*wikisource$/i ) ) {
var api = new mw.Api(), pagename = this.curPage;
return 'wikisource';
api.postWithToken('csrf', {
} else if ( wiki.match( /^.*wikiquote$/i ) ) {
action: 'edit',
return 'wikiquote';
title: this.curPage,
} else if ( wiki.match( /^.*wikinews$/i ) ) {
summary: mw.msg('linkify-summary', mw.config.get('wgTitle')),
return 'wikinews';
minor: 1,
} else if ( wiki.match( /^.*wikibooks$/i ) ) {
basetimestamp: this.timestamp,
return 'wikibooks';
starttimestamp: this.starttimestamp,
} else if ( wiki.match( /^.*wikiversity$/i ) ) {
text: this.text,
return 'wikiversity';
tags: 'quick linker'
} else if ( wiki.match( /^.*wiktionary$/i ) ) {
}).done(function(d) {
return 'wiktionary';
if (d && d.edit && d.edit.result == 'Success') mw.notify(mw.msg('qlinker-save-success', pagename));
} else if ( wiki.match( /^.*wiki$/i ) ) {
});
return 'wikipedia';
} else { // TODO other groups
return '';
}
}
var self = this;
}
if(this.safeMode) setTimeout(function(){ self.nextPage(); }, 5000/(self.skipsCounter+1));
else self.nextPage();
};


QuickEditorDialog.prototype.nextMatch = function ( ) {
/**
var m, contextPre, contextPost, contextInner, contextInnerOld, newContext, context;
* Called on error
this.matchI++;
*/
if (this.searchData.pageids.length <= this.pageI) {
function onError() {
return this.nextPage();
$.removeSpinner( 'slurpInterwiki' );
}
$( '#slurpInterwiki-button-import' ).button( 'option', 'disabled', false );
}


var page = this.searchData.pages[this.searchData.pageids[this.pageI]],
/**
pagecontent = page.revisions[0]['*'];
* Called on API error
if (page.title == mw.config.get('wgTitle')) {
*/
return this.nextPage();
function onApiError( jqXHR, textStatus, errorThrown ) {
}
alert( mw.msg( 'error-api' ) );
onError();
}


if (m = this.contextRgx.exec(pagecontent)) {
/**
contextPost = m[3];
* Return the item
contextInner = (m[2] == mw.config.get('wgTitle')) ? '[['+mw.config.get('wgTitle')+']]' : '[['+mw.config.get('wgTitle')+'|' + m[2] + ']]';
* @param success function called on success
contextInnerOld = '';
*/
}
function getItem( success ) {
else if (m = this.contextRgxLink.exec(pagecontent)) {
new mw.Api().get( {
if(m[2].endsWith(')'))  
formatversion: 2,
{
action: 'wbgetentities',
m = null; // other existing meaning
ids: itemId
} )
.done( function ( data ) {
if ( data.success && data.entities[ itemId ] ) {
success( data.entities[ itemId ] );
} else {
onApiError();
}
}
else
} )
{
.fail( onApiError );
contextPost = m[3] == mw.config.get('wgTitle')? m[4] : '|' + m[3] + m[4];
}
contextInner = mw.config.get('wgTitle');
contextInnerOld = '<s>' + m[2] + (m[3] == mw.config.get('wgTitle')? '|' : '') + '</s>';
}
}


if (!m) return this.nextPage();
/**
 
* Return the existings links of a wiki
context = m[0];
* @param success function called on success
contextPre = m[1];
*/
newContext = contextPre+contextInner+contextPost;
function getItemLinks( success ) {
this.content.$element.html('<h1><a href="/wiki/'+encodeURI(page.title)+'" target="_blank">'+page.title+'</a></h1><p>'+contextPre+contextInnerOld+'<b>'+contextInner+'</b>'+contextPost+'</p>');
getItem( function ( item ) {
this.curPage = page.title;
success( item.sitelinks );
this.text = pagecontent.replace(context, newContext)
} );
this.timestamp = page.revisions[0].timestamp;
}
}


QuickEditorDialog.prototype.nextPage = function ( ) {
/**
var m, contextPre, contextPost, contextInner, contextInnerOld, newContext;
* Return the existings links in a page of a wiki
this.pageI++;
* @param language string language of the wiki.
this.matchI = 0;
* @param group string wiki group like 'wikipedia'
if (this.searchData.pageids.length <= this.pageI)
* @param page string name of the page
{
* @param success function called on success
if(this.curPage === null) {
*/
this.content.$element.html('<h1><a target="_blank" href="/wiki/Special:Search/'+encodeURI('"' + titleNoBrackets +'" -linksto:"'+mw.config.get('wgPageName') + '"')+'">'+mw.msg('qlinker-no-results')+'</a></h1>');
function getLanguageLinks( language, group, page, success ) {
this.actions.setAbilities( {
$.ajax( {
saveContinue: false, skipOne: false
url: '//' + language + '.' + group + '.org/w/api.php',
data: {
format: 'json',
formatversion: 2,
action: 'query',
titles: page,
prop: 'langlinks',
lllimit: 400
},
dataType: 'jsonp',
cache: true // Do not add the parameter _ which generates the warning "Unrecognized parameter: '_'"
} )
.done( function ( data ) {
if ( data.query.pages ) {
$.each( data.query.pages, function ( index, page ) {
if ( page.missing ) {
alert( mw.msg( 'error-page' ) );
onError();
} else {
success( page.langlinks || [] );
}
} );
} );
} else {
} else {
this.close();
onApiError();
}
}
return;
} )
}
.fail( onApiError );
 
this.nextMatch();
}
}


// Make the window.
/**
var qlinkerEditor = new QuickEditorDialog( {
* Set the item links
  size: 'medium'
* @param item array the item
} );
* @param success function called on success
* @param summary string
*/
function setItem( item, success, summary ) {
new mw.Api().postWithEditToken( {
assertuser: mw.config.get( 'wgUserName' ),
formatversion: 2,
action: 'wbeditentity',
id: itemId,
data: JSON.stringify( item ),
summary: summary
} )
.done( success )
.fail( function ( code, data ) {
function link( match, $1, $2 ) {
return mw.html.element( 'a', { href: mw.util.getUrl( $1 ) }, $2 );
}


// Create and append a window manager, which will open and close the window.  
if ( data.error && data.error.info ) {
var windowManager = new OO.ui.WindowManager();
var errorInfo = data.error.info
$( 'body' ).append( windowManager.$element );
.replace( /\[\[(([^\]\|]+))\]\]/g, link )
.replace( /\[\[([^\]\|]+)\|([^\]]*)\]\]/g, link )
.replace( /\wiki:/g, ':' ) // Correcting wiki link
.replace( /\*/g, '<br>*' ); // To have each errors in a line
$( '#slurpInterwiki-error' ).html( mw.message( 'error-save', errorInfo ).parse() );
onError();
} else {
onApiError();
}
} );
}


// Add the window to the window manager using the addWindows() method.
/**
windowManager.addWindows( [ qlinkerEditor ] );
* Update interLanguages links from the wiki selected in the box. Works only for Wikipedias.
*/
function work() {
$.createSpinner( {
size: 'large',
type: 'block',
id: 'slurpInterwiki'
} ).appendTo( 'div#slurpInterwiki' );
$( '#slurpInterwiki-button-import' ).button( 'option', 'disabled', true );


// Open the window!
getItem( function ( item ) {
windowManager.openWindow( qlinkerEditor,  { searchData: searchRes } );
var links = {};
}
if ( item.sitelinks ) {
links = item.sitelinks;
}


function createAddLinksButton(){
var wiki = $( '#slurpInterwiki-lang' ).val();
var addLinksWizard = $(mw.util.addPortletLink(
if ( !links[ wiki ] ) {
'p-tb',
alert( mw.msg( 'error-pageNotFound' ) );
'#',
onError();
mw.msg('qlinker-sidelink'),
't-quicklinker',
mw.msg('qlinker-invoke'),
null,
'#t-whatlinkshere'
));
addLinksWizard.click(function(e){
protectedSearchQuery(false);
e.preventDefault();
});
return addLinksWizard;
}
function protectedSearchQuery(safeSearch)
{
var api = new mw.Api();
api.get( {
action: 'query',
prop: 'linkshere',
lhlimit: 500,
titles: mw.config.get('wgPageName'),
indexpageids: 1
}).done(function(d) {
var isValid = true, safeMode = false;
if(d.query && d.query.pages && d.query.pages[d.query.pageids[0]] && d.query.pages[d.query.pageids[0]].linkshere && d.query.pages[d.query.pageids[0]].linkshere.length > 100)
{
isValid = confirm(mw.msg('qlinker-confirm-masslink'));
safeMode = true;
}
if (!isValid) return;
searchLinksApi(safeSearch).done(function(q){
if (q.error) mw.notify(q.error.info);
if (!q.query || !q.query.pageids || q.query.pageids.length<=1) {
mw.notify(mw.msg('qlinker-no-results'));
return;
return;
}
}
mw.loader.using(['oojs-ui-windows', 'oojs-ui.styles.icons-movement', 'oojs-ui.styles.icons-editing-core'], function() { createQuickEditorDialog(q, safeMode) } );
var page = links[ wiki ].title;
});
var langCode = getLanguageCodeFromWikiId( wiki );
})
var group = getGroupFromWikiId( wiki );
}
if ( specialWikis[ wiki ] || langCode === '' || group === '' ) {
alert( mw.msg( 'error-wiki' ) );
onError();
return [];
}
getLanguageLinks( langCode, group, page, function ( interlangLinks ) {
getItem( function ( item ) {
var itemValue = {};
var changed = [];
 
var itemLinks = {};
if ( item.sitelinks ) {
itemLinks = item.sitelinks;
}
var linkChanged = false;
$.each( interlangLinks, function ( i, link ) {
var regex = /^(.*)old$/i;
if ( regex.test( interlangLinks[ i ].lang ) && link.lang !== 'be-x-old' ) {
mw.log( 'Refused wiki: ' + link.lang );
} else {
var site = link.lang.replace( /-/g, '_' );
site = site === 'nb' ? 'no' : site;
site += ( group === 'wikipedia' ) ? 'wiki' : group;
if ( !itemLinks[ site ] && link.title.indexOf( '#' ) === -1 ) {
itemLinks[ site ] = {
'site': site,
'title': link.title
};
linkChanged = true;
}
}
} );
if ( linkChanged ) {
itemValue.sitelinks = itemLinks;
changed.push( 'sitelinks' );
}
 
// Update labels
if ( $( '#slurpInterwiki-updateLabels' ).prop( 'checked' ) ) {
var labels = {};
if ( item.labels ) {
labels = item.labels;
}
var labelChanged = false;
$.each( itemLinks, function ( site, link ) {
if ( specialWikis[ link.site ] ) {
return;
}
 
var langs = [ getLanguageCodeFromWikiId( link.site ) ];
if ( langs[ 0 ] === 'simple' ) {
return;
}
switch ( langs[ 0 ] ) {
case 'simple':
langs = [ 'en' ];
break;
/*case 'en':
case 'simple':
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' ];
break;
case 'pt':
langs = [ 'pt', 'pt-br' ];
break;
case 'de':
langs = [ 'de', 'de-ch' ];
break;*/
case 'no':
langs = [ 'nb' ];
break;
case 'als':
langs = [ 'gsw' ];
break;
case 'crh':
langs = [ 'crh-latn' ];
break;
case 'bat-smg':
langs = [ 'sgs' ];
break;
case 'be-x-old':
langs = [ 'be-tarask' ];
break;
case 'bh':
langs = [ 'bho' ];
break;
case 'fiu-vro':
langs = [ 'vro' ];
break;
case 'roa-rup':
langs = [ 'rup' ];
break;
case 'zh-classical':
langs = [ 'lzh' ];
break;
case 'zh-min-nan':
langs = [ 'nan' ];
break;
case 'zh-yue':
langs = [ 'yue' ];
break;
}
$.each( langs, function ( j, language ) {
if ( !labels[ language ] ) {
var value = itemLinks[ site ].title; // .replace( /\(.*\)/g, '' )
switch ( language ) {
case 'es':
case 'pt':
case 'pt-br':
value = value.replace( /^Anexo:/, '' );
break;
case 'cs':
value = value.replace( /^Příloha:/, '' );
break;
case 'de-ch':
value = value.replace( /ß/g, 'ss' );
break;
case 'fa':
value = itemLinks[ site ].title; // In Farsi () are important
break;
}
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.';
}


function searchLinksApi(protectPrefixSuffix) {
setItem( itemValue, function () {
var api = new mw.Api(),
location.href = mw.util.getUrl( mw.config.get( 'wgPageName' ) ) + '?slurpnotif=' + notif.join( '|' );
searchRegexPreSufFix = 'insource:/' + allowedPrefix + mw.util.escapeRegExp(titleNoBrackets) + allowedSuffix +'/',
}, comment );
searchRegexNonSafe =  'insource:/' + mw.util.escapeRegExp(titleNoBrackets) +'/',
} else {
searchRegex = protectPrefixSuffix? searchRegexPreSufFix : searchRegexNonSafe,
mw.notify( mw.message( 'nolinkstoupdate' ) );
linkToEscaped = ' -linksto:"'+mw.config.get('wgPageName').replace('"', '\\"')+'"';
$( 'div#slurpInterwiki' ).dialog( 'close' );
onError();
return api.get( {
}
action: 'query',
} );
generator: 'search',
} );
gsrnamespace: 0,
} );
gsrsearch: searchRegex + linkToEscaped,
gsrlimit: 50,
prop: 'revisions',
rvprop: 'content|timestamp',
indexpageids: 1,
curtimestamp: 1
});
}
if ($('.dmbox').length === 0) { // Don't show the tool at Disambiguation pages because it is useless
if ($('.orphanpage, .stub').length>0) {
searchLinksApi().done(function(d){
if (d.query && d.query.pageids && d.query.pageids.length>1) createAddLinksButton().css('font-weight', 'bold')
});
}
}
else {
 
createAddLinksButton();
/**
* Show the dialog
*/
function show() {
getItemLinks( function ( links ) {
var formFind = $( '#slurpInterwiki-lang' );
formFind.empty();
var languagesLabel = mw.config.get( 'wgULSLanguages' ) || {};
$.each( links, function ( i, link ) {
if ( specialWikis[ link.site ] ) {
return;
}
 
var languageCode = getLanguageCodeFromWikiId( link.site );
var label = link.site;
if ( languageCode !== '' ) {
label = languageCode + '.' + getGroupFromWikiId( link.site );
if ( languagesLabel[ languageCode ] ) {
label += ' (' + languagesLabel[ languageCode ] + ')';
}
}
formFind.append(
$( '<option>' )
.attr( 'value', links[ i ].site )
.text( label )
);
} );
$( '#slurpInterwiki-error' ).html( '' );
$( 'div#slurpInterwiki' ).dialog( 'open' );
} );
return false;
}
}
}
 
});
/**
* Create the dialog and add a link in toolBox
*/
function init() {
$( '<div>' ).attr( {
id: 'slurpInterwiki',
title: mw.msg( 'box-title' )
} ).append(
$( '<form>' ).append(
$( '<p>' ).append(
$( '<label for="slurpInterwiki-lang">' )
.text( mw.msg( 'box-lang' ) ),
$( '<select name="slurpInterwiki-lang" id="slurpInterwiki-lang">' )
),
$( '<p>' ).append(
$( '<input checked type="checkbox" name="slurpInterwiki-updateLabels" id="slurpInterwiki-updateLabels">' ),
' ',
$( '<label for="slurpInterwiki-updateLabels">' )
.text( mw.msg( 'box-updateLabels' ) )
),
$( '<p>' ).text( mw.msg( 'box-warning' ) ),
$( '<p class="error" id="slurpInterwiki-error">' )
)
)
.appendTo( '#content' )
.dialog( {
autoOpen: false,
modal: true,
width: 500,
buttons: [ {
id: 'slurpInterwiki-button-import',
text: mw.msg( 'import' ),
click: work
} ]
} );
 
var portletLink = mw.util.addPortletLink( 'p-tb', '#', mw.msg( 'box-title' ), 't-slurpInterwiki', mw.msg( 'box-title' ) );
$( portletLink ).click( show );
}
 
$( init );
} ( mediaWiki, jQuery ) );

גרסה מ־10:53, 21 ביולי 2025

/*  _____________________________________________________________________________________________________
 * |                                                                                                     |
 * |                    === WARNING: GLOBAL GADGET FILE ===                                              |
 * |                  Changes to this page affect many users.                                            |
 * | Please discuss changes on the talk page or on [[MediaWiki talk:Gadgets-definition]] before editing. |
 * |____________________________________________________________________________________________________ |
 *
 */
( function ( mw, $ ) {
	'use strict';

	var itemId = mw.config.get( 'wbEntityId' );
	if ( !itemId || mw.config.get( 'wgNamespaceNumber' ) !== 0 ||
		!mw.config.get( 'wbIsEditView' ) ||
		!mw.config.get( 'wgIsProbablyEditable' )
	) {
		return;
	}

	var translations = require( './slurpInterwiki-i18n.json' );

	var chain = mw.language.getFallbackLanguageChain(),
		len = chain.length,
		messages = {},
		i;
	for ( i = len - 1; i >= 0; i-- ) {
		if ( translations.hasOwnProperty( chain[ i ] ) ) {
			$.extend( messages, translations[ chain[ i ] ] );
		}
	}
	mw.messages.set( messages );

	var specialWikis = {
		'commonswiki': 'commons',
		'metawiki': 'meta',
		'mediawikiwiki': 'mediawiki',
		'specieswiki': 'species',
		'wikidatawiki': 'wikidata'
	};

	var notification = mw.util.getParamValue( 'slurpnotif' );
	if ( notification !== null ) {
		var notifications = notification.split( '|' );
		for ( i in notifications ) {
			mw.notify( mw.message( notifications[ i ] ) );
		}
	}

	/**
	 * Return the language code from the ID of the Wiki
	 */
	function getLanguageCodeFromWikiId( wiki ) {
		var splited = wiki.match( /^(.*)wik[it][a-z]*$/i );
		if ( !splited[ 1 ] ) {
			return '';
		} else {
			return splited[ 1 ].replace( /_/g, '-' );
		}
	}

	/**
	 * Return the site group from the ID of the Wiki
	 */
	function getGroupFromWikiId( wiki ) {
		if ( wiki.match( /^.*wikivoyage$/i ) ) {
			return 'wikivoyage';
		} else if ( wiki.match( /^.*wikisource$/i ) ) {
			return 'wikisource';
		} else if ( wiki.match( /^.*wikiquote$/i ) ) {
			return 'wikiquote';
		} else if ( wiki.match( /^.*wikinews$/i ) ) {
			return 'wikinews';
		} else if ( wiki.match( /^.*wikibooks$/i ) ) {
			return 'wikibooks';
		} else if ( wiki.match( /^.*wikiversity$/i ) ) {
			return 'wikiversity';
		} else if ( wiki.match( /^.*wiktionary$/i ) ) {
			return 'wiktionary';
		} else if ( wiki.match( /^.*wiki$/i ) ) {
			return 'wikipedia';
		} else { // TODO other groups
			return '';
		}
	}

	/**
	 * Called on error
	 */
	function onError() {
		$.removeSpinner( 'slurpInterwiki' );
		$( '#slurpInterwiki-button-import' ).button( 'option', 'disabled', false );
	}

	/**
	 * Called on API error
	 */
	function onApiError( jqXHR, textStatus, errorThrown ) {
		alert( mw.msg( 'error-api' ) );
		onError();
	}

	/**
	 * Return the item
	 * @param success function called on success
	 */
	function getItem( success ) {
		new mw.Api().get( {
			formatversion: 2,
			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 ) {
			success( item.sitelinks );
		} );
	}

	/**
	 * Return the existings links in a page of a wiki
	 * @param language string language of the wiki.
	 * @param group string wiki group like 'wikipedia'
	 * @param page string name of the page
	 * @param success function called on success
	 */
	function getLanguageLinks( language, group, page, success ) {
		$.ajax( {
			url: '//' + language + '.' + group + '.org/w/api.php',
			data: {
				format: 'json',
				formatversion: 2,
				action: 'query',
				titles: page,
				prop: 'langlinks',
				lllimit: 400
			},
			dataType: 'jsonp',
			cache: true // Do not add the parameter _ which generates the warning "Unrecognized parameter: '_'"
		} )
		.done( function ( data ) {
			if ( data.query.pages ) {
				$.each( data.query.pages, function ( index, page ) {
					if ( page.missing ) {
						alert( mw.msg( 'error-page' ) );
						onError();
					} else {
						success( page.langlinks || [] );
					}
				} );
			} else {
				onApiError();
			}
		} )
		.fail( onApiError );
	}

	/**
	 * Set the item links
	 * @param item array the item
	 * @param success function called on success
	 * @param summary string
	 */
	function setItem( item, success, summary ) {
		new mw.Api().postWithEditToken( {
			assertuser: mw.config.get( 'wgUserName' ),
			formatversion: 2,
			action: 'wbeditentity',
			id: itemId,
			data: JSON.stringify( item ),
			summary: summary
		} )
		.done( success )
		.fail( function ( code, data ) {
			function link( match, $1, $2 ) {
				return mw.html.element( 'a', { href: mw.util.getUrl( $1 ) }, $2 );
			}

			if ( data.error && data.error.info ) {
				var errorInfo = data.error.info
				.replace( /\[\[(([^\]\|]+))\]\]/g, link )
				.replace( /\[\[([^\]\|]+)\|([^\]]*)\]\]/g, link )
				.replace( /\wiki:/g, ':' ) // Correcting wiki link
				.replace( /\*/g, '<br>*' ); // To have each errors in a line
				$( '#slurpInterwiki-error' ).html( mw.message( 'error-save', errorInfo ).parse() );
				onError();
			} else {
				onApiError();
			}
		} );
	}

	/**
	 * Update interLanguages links from the wiki selected in the box. Works only for Wikipedias.
	 */
	function work() {
		$.createSpinner( {
			size: 'large',
			type: 'block',
			id: 'slurpInterwiki'
		} ).appendTo( 'div#slurpInterwiki' );
		$( '#slurpInterwiki-button-import' ).button( 'option', 'disabled', true );

		getItem( function ( item ) {
			var links = {};
			if ( item.sitelinks ) {
				links = item.sitelinks;
			}

			var wiki = $( '#slurpInterwiki-lang' ).val();
			if ( !links[ wiki ] ) {
				alert( mw.msg( 'error-pageNotFound' ) );
				onError();
				return;
			}
			var page = links[ wiki ].title;
			var langCode = getLanguageCodeFromWikiId( wiki );
			var group = getGroupFromWikiId( wiki );
			if ( specialWikis[ wiki ] || langCode === '' || group === '' ) {
				alert( mw.msg( 'error-wiki' ) );
				onError();
				return [];
			}
			getLanguageLinks( langCode, group, page, function ( interlangLinks ) {
				getItem( function ( item ) {
					var itemValue = {};
					var changed = [];

					var itemLinks = {};
					if ( item.sitelinks ) {
						itemLinks = item.sitelinks;
					}
					var linkChanged = false;
					$.each( interlangLinks, function ( i, link ) {
						var regex = /^(.*)old$/i;
						if ( regex.test( interlangLinks[ i ].lang ) && link.lang !== 'be-x-old' ) {
							mw.log( 'Refused wiki: ' + link.lang );
						} else {
							var site = link.lang.replace( /-/g, '_' );
							site = site === 'nb' ? 'no' : site;
							site += ( group === 'wikipedia' ) ? 'wiki' : group;
							if ( !itemLinks[ site ] && link.title.indexOf( '#' ) === -1 ) {
								itemLinks[ site ] = {
									'site': site,
									'title': link.title
								};
								linkChanged = true;
							}
						}
					} );
					if ( linkChanged ) {
						itemValue.sitelinks = itemLinks;
						changed.push( 'sitelinks' );
					}

					// Update labels
					if ( $( '#slurpInterwiki-updateLabels' ).prop( 'checked' ) ) {
						var labels = {};
						if ( item.labels ) {
							labels = item.labels;
						}
						var labelChanged = false;
						$.each( itemLinks, function ( site, link ) {
							if ( specialWikis[ link.site ] ) {
								return;
							}

							var langs = [ getLanguageCodeFromWikiId( link.site ) ];
							if ( langs[ 0 ] === 'simple' ) {
								return;
							}
							switch ( langs[ 0 ] ) {
								case 'simple':
									langs = [ 'en' ];
									break;
								/*case 'en':
								case 'simple':
									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' ];
									break;
								case 'pt':
									langs = [ 'pt', 'pt-br' ];
									break;
								case 'de':
									langs = [ 'de', 'de-ch' ];
									break;*/
								case 'no':
									langs = [ 'nb' ];
									break;
								case 'als':
									langs = [ 'gsw' ];
									break;
								case 'crh':
									langs = [ 'crh-latn' ];
									break;
								case 'bat-smg':
									langs = [ 'sgs' ];
									break;
								case 'be-x-old':
									langs = [ 'be-tarask' ];
									break;
								case 'bh':
									langs = [ 'bho' ];
									break;
								case 'fiu-vro':
									langs = [ 'vro' ];
									break;
								case 'roa-rup':
									langs = [ 'rup' ];
									break;
								case 'zh-classical':
									langs = [ 'lzh' ];
									break;
								case 'zh-min-nan':
									langs = [ 'nan' ];
									break;
								case 'zh-yue':
									langs = [ 'yue' ];
									break;
							}
							$.each( langs, function ( j, language ) {
								if ( !labels[ language ] ) {
									var value = itemLinks[ site ].title; // .replace( /\(.*\)/g, '' )
									switch ( language ) {
										case 'es':
										case 'pt':
										case 'pt-br':
											value = value.replace( /^Anexo:/, '' );
											break;
										case 'cs':
											value = value.replace( /^Příloha:/, '' );
											break;
										case 'de-ch':
											value = value.replace( /ß/g, 'ss' );
											break;
										case 'fa':
											value = itemLinks[ site ].title; // In Farsi () are important
											break;
									}
									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, function () {
							location.href = mw.util.getUrl( mw.config.get( 'wgPageName' ) ) + '?slurpnotif=' + notif.join( '|' );
						}, comment );
					} else {
						mw.notify( mw.message( 'nolinkstoupdate' ) );
						$( 'div#slurpInterwiki' ).dialog( 'close' );
						onError();
					}
				} );
			} );
		} );
	}

	/**
	 * Show the dialog
	 */
	function show() {
		getItemLinks( function ( links ) {
			var formFind = $( '#slurpInterwiki-lang' );
			formFind.empty();
			var languagesLabel = mw.config.get( 'wgULSLanguages' ) || {};
			$.each( links, function ( i, link ) {
				if ( specialWikis[ link.site ] ) {
					return;
				}

				var languageCode = getLanguageCodeFromWikiId( link.site );
				var label = link.site;
				if ( languageCode !== '' ) {
					label = languageCode + '.' + getGroupFromWikiId( link.site );
					if ( languagesLabel[ languageCode ] ) {
						label += ' (' + languagesLabel[ languageCode ] + ')';
					}
				}
				formFind.append(
					$( '<option>' )
					.attr( 'value', links[ i ].site )
					.text( label )
				);
			} );
			$( '#slurpInterwiki-error' ).html( '' );
			$( 'div#slurpInterwiki' ).dialog( 'open' );
		} );
		return false;
	}

	/**
	 * Create the dialog and add a link in toolBox
	 */
	function init() {
		$( '<div>' ).attr( {
			id: 'slurpInterwiki',
			title: mw.msg( 'box-title' )
		} ).append(
			$( '<form>' ).append(
				$( '<p>' ).append(
					$( '<label for="slurpInterwiki-lang">' )
					.text( mw.msg( 'box-lang' ) ),
					$( '<select name="slurpInterwiki-lang" id="slurpInterwiki-lang">' )
				),
				$( '<p>' ).append(
					$( '<input checked type="checkbox" name="slurpInterwiki-updateLabels" id="slurpInterwiki-updateLabels">' ),
					' ',
					$( '<label for="slurpInterwiki-updateLabels">' )
					.text( mw.msg( 'box-updateLabels' ) )
				),
				$( '<p>' ).text( mw.msg( 'box-warning' ) ),
				$( '<p class="error" id="slurpInterwiki-error">' )
			)
		)
		.appendTo( '#content' )
		.dialog( {
			autoOpen: false,
			modal: true,
			width: 500,
			buttons: [ {
				id: 'slurpInterwiki-button-import',
				text: mw.msg( 'import' ),
				click: work
			} ]
		} );

		var portletLink = mw.util.addPortletLink( 'p-tb', '#', mw.msg( 'box-title' ), 't-slurpInterwiki', mw.msg( 'box-title' ) );
		$( portletLink ).click( show );
	}

	$( init );
} ( mediaWiki, jQuery ) );