User:Art-top/vector.js

From Wikidata
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
//mw.loader.load('http://www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-CodeEditor.js&action=raw&ctype=text/javascript');

var itemId = mw.config.get( 'wbEntityId' );
var dat={};
$.ajax({
	url: mw.util.wikiScript('api'),
	data:{
		'format': 'json',
		'action': 'wbgetentities',
		'ids': itemId,
		'props': 'labels|descriptions'
	},
	success: function(data){
		for(var id in data.entities[itemId].labels){
			var lang=data.entities[itemId].labels[id].language;
			var label=data.entities[itemId].labels[id].value;
			if(!dat[lang]){
				dat[lang]={
					'label': label,
					'descr': ''
				};
			}else{
				dat[lang]['label']=label;
			}
		}
		for(var id in data.entities[itemId].descriptions){
			var lang=data.entities[itemId].descriptions[id].language;
			var desc=data.entities[itemId].descriptions[id].value;
			if(!dat[lang]){
				dat[lang]={
					'label': '',
					'descr': desc
				};
			}else{
				dat[lang]['descr']=desc;
			}
		}
		$(".wb-sitelinks-siteid").each(function(indx, element){
			if(indx!=1){
				var lang=$.trim($(element).text());
				var lbl="";
				var desc="";
				var text="";//="<div>";
				if(dat[lang]){
					lbl=dat[lang]['label'];
					desc=dat[lang]['descr'];
					if(lbl==""){
						text=+" <b>(нет метки)</b>";
					}else{
						if($.trim($(".wb-sitelinks-link wb-sitelinks-link-"+lang+"wiki").text())!=lbl){
							text+=" ("+lbl+")";
						}
					}
					if(desc!=""){
						text+="<br /><small><i>"+desc+"</i></small>";
					}
				}else{
					text+=" <b>(нет метки)</b>";
				}
//				text+="</div>";
				$(".wb-sitelinks-link wb-sitelinks-link-"+lang+"wiki").append(text);
			}
		});
	}
});

var user_lang = mw.user.options.get( 'language' );
$.ajax({
	url: mw.util.wikiScript('api'),
	data:{
		'format': 'json',
		'action': 'wbgetentities',
		'ids': itemId,
		'props': 'sitelinks'
	},
	success: function(data){
		var cur_user_lang=user_lang.replace(/-/g, '_');
		for(var id in data.entities[itemId].sitelinks){
			var sitelink=data.entities[itemId].sitelinks[id].site;
			var wiki=sitelink.match( /^(.*)wiki$/i )[1];
			var title=data.entities[itemId].sitelinks[id].title;
			if(sitelink===(cur_user_lang+"wiki")){
				$(".wb-firstHeading").append('<small>(<a href=http://'+wiki+'.wikipedia.org/wiki/'+title.replace(/ /g, '_')+' dir=auto target=_blank>ссылка</a>)</small>');
				break;
			}
		}
	}
});
/*
$.ajax({
	url: mw.util.wikiScript('api'),
	data:{
		'format': 'json',
		'action': 'wbsearchentities',
		'search': 'Ивановка',
		'language': user_lang,
		'type': 'item',
		'limit': 20,
	},
	success: function(data){
		var cur_user_lang=user_lang.replace(/-/g, '_');
		for(var id in data.search[itemId].sitelinks){
			var sitelink=data.entities[itemId].sitelinks[id].site;
			var wiki=sitelink.match( /^(.*)wiki$/i )[1];
			var title=data.entities[itemId].sitelinks[id].title;
			if(sitelink===(cur_user_lang+"wiki")){
				$(".wb-firstHeading").append('<small>(<a href=http://'+wiki+'.wikipedia.org/wiki/'+title.replace(/ /g, '_')+' dir=auto target=_blank>ссылка</a>)</small>');
				break;
			}
		}
	}
});
*/
importScript('User:Art-top/autoEditLists.js');

( 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!'
		},
		'ru': {
			'box-title': 'Импорт интервики2',
			'box-warning': 'Внимание: этот скрипт импортирует интервики-ссылки без проверки на конфликты. Вам необходимо самостоятельно проверить все интервики-ссылки и убрать ссылающиеся на неправильные статьи!',
			'box-lang': 'откуда : ',
			'box-updateLabels': 'Автоматическое заполнение пустых меток, основываясь на названиях вики-страниц',
			'import': 'Импорт',
			'error-api': 'Проблема с API!',
			'error-wiki': 'Выбранный раздел Википедии не существует!',
			'error-page': 'Страница не существует!',
			'error-pageNotFound': 'Нет интервик в указанном разделе',
			'error-save': 'Ошибка сохранения: ',
			'success-links': 'Интервики импортированы',
			'success-labels': 'Метки импортированы',
			'nolinkstoupdate': 'Все ссылки уже импортированы ранее'
		}
	};
	i18nData.no = i18nData.nb;

	var parts = mw.user.options.get( 'language' ).split("-");
	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 type="checkbox" checked name="slurpInterwiki-updateLabels" id="slurpInterwiki-updateLabels" /> <label for="slurpInterwiki-updateLabels">' + i18n( 'box-updateLabels' ) + '</label></p>';
			formFind += '<p>' + i18n( 'box-warning' ) + '</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') || {};
var sort_links = [];
for( var i in links ) {
sort_links.push(links[i].site);
}
sort_links=sort_links.sort(
    function(a,b){
		switch(a){
		case "enwiki":
			a="1"+a;
			break;
		case "dewiki":
			a="2"+a;
			break;
		case "ruwiki":
			a="3"+a;
			break;
		default:
			a="9"+a;
			break;
		}

		switch(b){
		case "enwiki":
			b="1"+b;
			break;
		case "dewiki":
			b="2"+b;
			break;
		case "ruwiki":
			b="3"+b;
			break;
		default:
			b="9"+b;
			break;
		}

		if(a>b){
			return 1;
		}
		if(a<b){
			return -1;
		}
		return 0;
	}    
);
			for( var i in sort_links ) {
				var languageCode = getLanguageCodeFromWikiId( sort_links[i] );
				var label = sort_links[i];
				if( languageCode !== '' ) {
					label = languageCode;
					if( languagesLabel[languageCode] ) {
						label += ' (' + languagesLabel[languageCode] + ')';
					}
				}
				formFind.append( '<option value="' + sort_links[i] + '">' + label + '</option>' );
			}
			$( 'div#slurpInterwiki' ).dialog( 'open' );
		} );
	}

	/**
	 * 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 ) ) {
								//mw.log( 'Refused wiki: ' + interlangLinks[i].lang );
							//} else {
								var site = interlangLinks[i].lang.replace(/-/g, '_') + 'wiki';
								if( !itemLinks[site] ) {
									var str = interlangLinks[i]['*'];
									var regex = /(.+)#(.+)/i;
									if(regex.test(str)) {
										continue;
									}
									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 'be-x-old':
										langs = ['be-tarask'];
										break;
								}
								for( var j in langs ) {
									var language = langs[j];
									var value = itemLinks[site].title.replace( /\s\(.+\)\s*$/, '' );
									if( language !== 'ru') {
										if( (language!=='ky') && (language!=='mdf') && (language!=='mhr')  && (language!=='krc') && (language!=='mrj')  && (language!=='os') && (language!=='udm')){
											value = value.replace(/,\s.+\s*$/g,'');
										}
									}else{
										var re = /^\s*([А|Б|В|Г|Д|Е|Ж|З|И|Й|К|Л|М|Н|О|П|Р|С|Т|У|Ф|Х|Ц|Ч|Ш|Щ|Ы|Э|Ю|Я].+),\s([А|Б|В|Г|Д|Е|Ж|З|И|Й|К|Л|М|Н|О|П|Р|С|Т|У|Ф|Х|Ц|Ч|Ш|Щ|Ы|Э|Ю|Я].+)\s*$/;
										value = value.replace(re, "$2 $1");
									}
									if( language === 'be' ) {
										value = value.replace(/^Горад /, '');
										value = value.replace(/^Вёска /, '');
									}
									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( !labels[language] ) {
										labels[language] = {
											'language': language,
											'value': value
										};
										labelChanged = true;
									}else{
										var tmp=labels[language].value;
										labels[language].value = labels[language].value.replace( /\s\(.+\)\s*$/, '' );
										if(language !== 'ru'){
											if( (language!=='ky') && (language!=='mdf') && (language!=='mhr')  && (language!=='krc') && (language!=='mrj')  && (language!=='os') && (language!=='udm')){
												labels[language].value = labels[language].value.replace(/,\s.+\s*$/g,'');
											}
										}
										if(labels[language].value === "" && value !== ""){
//											labels[language].value=value;
										}
										if(language === 'be'){
											labels[language].value = labels[language].value.replace(/^Горад /g, '');
											labels[language].value = labels[language].value.replace(/^Вёска /g, '');
										}
										if(language === 'ru') {
											var re = /^\s*([А|Б|В|Г|Д|Е|Ж|З|И|Й|К|Л|М|Н|О|П|Р|С|Т|У|Ф|Х|Ц|Ч|Ш|Щ|Ы|Э|Ю|Я].+),\s([А|Б|В|Г|Д|Е|Ж|З|И|Й|К|Л|М|Н|О|П|Р|С|Т|У|Ф|Х|Ц|Ч|Ш|Щ|Ы|Э|Ю|Я].+)\s*$/;
											labels[language].value = labels[language].value.replace(re, "$2 $1");
										}
										if(labels[language].value !== tmp){
											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 ) {
				alert( i18n( 'error-save' ) + data.error.info );
				onError();
			} else {
				success(); //TODO Manage possibles errors
			}
		} )
		.fail(onApiError);
	}

	$( document ).ready( init );
} ( mediaWiki, jQuery ) );