User:Fomafix/MediaWiki:Gadget-FindRedirectsForAliases.js

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.
// Find a list of redirects, allowing the user to select some of them to add as aliases.
// "Find redirects" button gets placed in submenu next to the "Watch" button.
// Author : [[User:Yair rand]]
// License : CC-BY-SA
// From : [[User:Yair rand/FindRedirectsForAliases.js]]

// Find a list of redirects, allowing the user to select some of them to add as aliases.
// "Find redirects" button gets placed in submenu next to the "Watch" button.
( function ( mw, $, wb ) {
	var translate = {
		ar: {
			FindRedirects: 'ابحث عن التحويلات',
			FRTooltip: 'إضافة ألقاب حسب التحويلات',
			loading: 'جار التحميل…',
			dialogtitle: 'إضافة ألقاب حسب التحويلات',
			error: 'خطأ: ',
			nonefound: 'لم يتم العثور علي تحويلة.',
			dialogintro: 'اختار التحويلة التي تريد استخدامها كلقب: ',
			add: 'أضافة',
			policynote: '(تنبيه : لايمكن استخدام كل التحويلات كألقاب. رجاء اقراء [[Help:Aliases/ar]] لمزيد من المعلومات.)'
		},
		bn: {
			FindRedirects: 'পুননির্দেশনা খুঁজুন',
			FRTooltip: 'উইকিপিডিয়া থেকে উপনামের পুননির্দেশনা যোগ করুন',
			loading: 'লোড হচ্ছে…',
			dialogtitle: 'পুননির্দেশনা থেকে উপনাম যোগ',
			error: 'ত্রুটি: ',
			nonefound: 'পুননির্দেশনাটি পাওয়া যায় নি।',
			dialogintro: 'উপনাম হিসাবে যোগ করার জন্য পুনঃনির্দেশ নির্বাচন করুন: ',
			add: 'যোগ',
			policynote: '(উল্লেখ্য যে অনেকগুলি পুননির্দেশনা উপনাম হিসাবে গ্রহণযোগ্য হয় না। আরও তথ্যের জন্য অনুগ্রহ করে পড়ুন [[Help:Aliases/bn]]।)'
		},
		ca: {
			FindRedirects: 'Cerca redireccions',
			FRTooltip: 'Afegeix àlies des de les redireccions de Viquipèdia',
			loading: 'Encarregant…',
			dialogtitle: 'Afegeix àlies des de les redireccions.',
			error: 'Error: ',
			nonefound: 'Cap redirecció trobada.',
			dialogintro: 'Selecciona les redireccions a afegir com a àlies: ',
			add: 'Afegeix',
			policynote: '(Teniu en compte que no s\'accepten moltes redireccions com a àlies. Llegiu [[Help:Aliases/ca]] per més informacions.)'
		},
		de: {
			FindRedirects: 'Finde Weiterleitungen',
			FRTooltip: 'Füge Wikipedia-Weiterleitungen als Alias hinzu',
			loading: 'Lädt…',
			dialogtitle: 'Füge Weiterleitungen als Alias hinzu',
			error: 'Fehler: ',
			nonefound: 'Keine Weiterleitung gefunden.',
			dialogintro: 'Wähle eine Weiterleitung um sie als Alias hinzuzufügen: ',
			add: 'Hinzufügen',
			policynote: '(Bitte beachte, dass viele Weiterleitungen als Alias ungeeignet sind. Bitte lies [[Help:Aliases/de]] für mehr Informationen.)'
		},
		en: {
			FindRedirects: 'Find redirects',
			FRTooltip: 'Add aliases from Wikipedia redirects',
			loading: 'Loading…',
			dialogtitle: 'Adding aliases from redirects',
			error: 'Error: ',
			nonefound: 'No redirects found.',
			dialogintro: 'Select redirects to add as aliases: ',
			add: 'Add',
			policynote: '(Note that many redirects are not acceptable as aliases. Please read [[Help:Aliases]] for more information.)'
		},
		es: {
			FindRedirects: 'Encontrar redirecciones',
			FRTooltip: 'Añadir alias desde las redirecciones de Wikipedia',
			loading: 'Cargando…',
			dialogtitle: 'Añadiendo alias desde las redirecciones',
			error: 'Error: ',
			nonefound: 'No se han encontrado redirecciones.',
			dialogintro: 'Selecciona las redirecciones a añadir como alias: ',
			add: 'Añadir',
			policynote: '(Ten en cuenta que no se aceptan muchas redirecciones como alias. Lee [[Help:Aliases/es]] para más información.)'
		},
		fa: {
			FindRedirects: 'یافتن تغییرمسیرها',
			FRTooltip: 'افزودن لقب‌ها بر پایه تغییرمسیرها',
			loading: 'بارگیری…',
			dialogtitle: 'افزودن لقب‌ها بر پایه تغییرمسیرها',
			error: 'خطا: ',
			nonefound: 'تغییرمسیری یافت نشد.',
			dialogintro: 'تغییرمسیری را که می خواهید به عنوان لقب از آن استفاده کنید را انتخاب کنید: ',
			add: 'افزودن',
			policynote: '(توجه کنید همه تغییرمسیرها نمی‌توانند به عنوان لقب قابل استفاده باشند. لطفاً [[Help:Aliases/fa]] را برای اطلاعات بیشتر مطالعه نمائید.)'
		},
		fi: {
			FindRedirects: 'Löydä ohjaussivut',
			FRTooltip: 'Lisää aliakset Wikipedian ohjaussivuista',
			loading: 'Ladataan…',
			dialogtitle: 'Lisätään aliakset ohjaussivuista',
			error: 'Virhe: ',
			nonefound: 'Ohjaussivuje ei löytynyt.',
			dialogintro: 'Valitse ohjaussivut, jotka haluat lisätä aliaksiksi: ',
			add: 'Lisää',
			policynote: '(Huomioi että monet ohjaussivut eivät ole hyväksyttäviä aliaksiksi. Lue lisää sivulta [[Help:Aliases/fi]].)'
		},
		fr: {
			FindRedirects: 'Recherche des redirections',
			FRTooltip: 'Ajoute des alias depuis les redirections de Wikipédia',
			loading: 'Chargement…',
			dialogtitle: 'Ajoute des alias depuis les redirections.',
			error: 'Erreur: ',
			nonefound: 'Aucune redirection trouvée.',
			dialogintro: 'Sélectionnez les redirections à ajouter comme alias: ',
			add: 'Ajouter',
			policynote: '(Remarquez que de nombreux redirects ne constituent pas des alias acceptables, veuillez lire [[Help:Aliases/fr]] pour plus d\'information.)'
		},
		gl: {
			FindRedirects: 'Atopar redireccións',
			FRTooltip: 'Engadir alias dende as redireccións de Wikipedia',
			loading: 'Cargando…',
			dialogtitle: 'Engadindo alias dende as redireccións',
			error: 'Erro: ',
			nonefound: 'Non se atoparon redireccións.',
			dialogintro: 'Selecciona as redirecciones a engadir como alias: ',
			add: 'Engadir',
			policynote: '(Ten en conta que non se aceptan moitas redireccións como alias. Le [[Help:Aliases/gl]] para máis información.)'
		},
		id: {
			FindRedirects: 'Temukan pengalihan',
			FRTooltip: 'Tambahkan nama lain dari pengalihan',
			loading: 'Loading…',
			dialogtitle: 'Menambahkan nama lain',
			error: 'Error: ',
			nonefound: 'Tidak ditemukan pengalihan.',
			dialogintro: 'Pilih pengalihan sebagai nama lain: ',
			add: 'Tambahkan',
			policynote: '(Perhatikan bahwa banyak pengalihan yang tidak diterima sebagai nama lain. Silahkan baca [[Help:Aliases/id]] untuk informasi lebih lanjut.)'
		},
		it: {
			FindRedirects: 'Trova redirect',
			FRTooltip: 'Aggiungi alias dai redirect di Wikipedia',
			loading: 'Caricamento in corso…',
			dialogtitle: 'Aggiunta alias dai redirect',
			error: 'Errore: ',
			nonefound: 'Nessun redirect trovato.',
			dialogintro: 'Seleziona i redirect da aggiungere come alias: ',
			add: 'Aggiungi',
			policynote: 'Note: [[Help:Aliases/it]]'
		},
		ja: {
			FindRedirects: 'リダイレクト取得',
			FRTooltip: 'ウィキペディアのリダイレクト(転送)から別名を追加する',
			loading: '読み込み中…',
			dialogtitle: 'リダイレクトから別名を追加',
			error: 'エラー:',
			nonefound: 'リダイレクトがありません',
			dialogintro: '別名として追加するリダイレクトを選んでください:',
			add: '追加',
			policynote: '(リダイレクトの多くは別名として許容されないことにご注意ください。詳しくは [[Help:Aliases/ja]] をご覧ください。)'
		},
		min: {
			FindRedirects: 'Cari pangaliahan',
			FRTooltip: 'Tambahkan namo lain dari pangaliahan',
			loading: 'Loading…',
			dialogtitle: 'Manambahan namo lain',
			error: 'Error: ',
			nonefound: 'Indak basobok pangaliahan.',
			dialogintro: 'Piliah pangaliahan sabagai namo lain: ',
			add: 'Tambah',
			policynote: '(Peratian: Banyak pangaliahan nan indak ditarimo sabagai namo lain. Cubo baco [[Help:Aliases/min]] untuak informasi labiah lanjuik.)'
		},
		mk: {
			FindRedirects: 'Најди пренасочувања',
			FRTooltip: 'Додај истозначници од пренасочувањата на Википедија',
			loading: 'Вчитувам…',
			dialogtitle: 'Додавање на истозначници од пренасочувања',
			error: 'Грешка: ',
			nonefound: 'Не пронајдов пренасочувања.',
			dialogintro: 'Изберете ги пренасочувањата што сакате да се додадат како истозначници: ',
			add: 'Додај',
			policynote: '(Имајте предвид дека многу пренасочувања се неприфатливи како истозначници. Повеќе информации ќе најдете на [[Help:Aliases/mk]].)'
		},
		nl: {
			FindRedirects: 'Zoek doorverwijzingen',
			FRTooltip: 'Aliassen toevoegen door middel van doorverwijzingen',
			loading: 'Laden…',
			dialogtitle: 'Adding aliases from redirects',
			error: 'Error: ',
			nonefound: 'Geen doorverwijzingen gevonden.',
			dialogintro: 'Selecteer doorverwijzingen om toe te voegen als alias: ',
			add: 'Toevoegen',
			policynote: '(Merk op dat veel doorverwijzingen niet geschikt zijn als alias. Zie [[Help:Aliases/nl]] voor meer informatie.)'
		},
		pl: {
			FindRedirects: 'Znajdź przekierowania',
			FRTooltip: 'Dodaj inne nazwy z przekierowań Wikipedii',
			loading: 'Ładowanie…',
			dialogtitle: 'Dodawanie innych nazw z przekierowań',
			error: 'Błąd: ',
			nonefound: 'Nie znaleziono przekierowań.',
			dialogintro: 'Zaznacz przekierowania do dodania innej nazwy: ',
			add: 'Dodaj',
			policynote: 'Należy pamiętać, że wiele przekierowań nie jest dopuszczalnych jako aliasy. Proszę przeczytać [[Help:Aliases/pl]] aby uzyskać więcej informacji.'
		},
		ur: {
			FindRedirects: 'رجوع مکررات تلاش کریں',
			FRTooltip: 'اضافہ القاب بلحاظ رجوع مکررات',
			loading: 'لد رہا ہے…',
			dialogtitle: 'اضافہ القاب بلحاظ رجوع مکررات',
			error: 'خطا: ',
			nonefound: 'کوئی رجوع مکرر نہیں ملا.',
			dialogintro: 'بطور لقب جس رجوع مکرر کو آپ استعمال کرنا چاہتے ہیں اسے منتخب کریں: ',
			add: 'اضافہ کریں',
			policynote: '(انتباہ : تمام رجوع مکررات کو بطور القاب استعمال نہیں کیا جاسکتا۔ براہ کرم مزید معلومات کے لیے ملاحظہ فرمائیں [[Help:Aliases/ur]]۔)'
		},
		zh: {
			FindRedirects: '查找重定向',
			FRTooltip: '根据维基百科的重定向添加别名',
			loading: '载入中…',
			dialogtitle: '根据重定向添加别名',
			error: '错误:',
			nonefound: '没有找到重定向。',
			dialogintro: '选择重定向以添加为别名:',
			add: '添加',
			policynote: 'Note: [[Help:Aliases/zh]]'
		}
	};
	var lang = mw.config.get( 'wgUserLanguage' );
	mw.messages.set( $.extend( {}, translate['en'], translate[lang] ) );
	if ( !mw.config.exists( 'wbEntityId' ) ) {
		return;
	}

	var api;

	/**
	 * Get the wikipedia site from a language code.
	 *
	 * @param {String} language code
	 * @return wikibase.Site|null
	 *
	 * required modules: wikibase
	 */
	function getSiteByLang( lang ) {
		var langs = {
			// workaround for bug 57706
			// source: https://noc.wikimedia.org/conf/InitialiseSettings.php.txt
			'crh-latn': wb.sites.getSite( 'crhwiki' ),
			'nb': wb.sites.getSite( 'nowiki' ),
			'gsw': wb.sites.getSite( 'alswiki' ),
			'sgs': wb.sites.getSite( 'bat_smgwiki' ),
			'be-tarask': wb.sites.getSite( 'be_x_oldwiki' ),
			'vro': wb.sites.getSite( 'fiu_vrowiki' ),
			'rup': wb.sites.getSite( 'roa_rupwiki' ),
			'lzh': wb.sites.getSite( 'zh_classicalwiki' ),
			'nan': wb.sites.getSite( 'zh_min_nanwiki' ),
			'yue': wb.sites.getSite( 'zh_yuewiki' )
		};
		var sites = wb.sites.getSitesOfGroup( 'wikipedia' );
		$.each( sites, function ( index, site ) {
			// ignore 'simplewiki' to get the mapping from 'en' to 'enwiki'
			if ( site.getId() === 'simplewiki' ) {
				return; // continue
			}
			langs[site.getLanguageCode()] = site;
		} );
		
		while ( lang ) {
			if ( langs.hasOwnProperty( lang ) ) {
				return langs[lang];
			}
			lang = lang.substr( 0, lang.lastIndexOf( '-' ) );
		}
		return null;
	}

	var site = getSiteByLang( mw.config.get( 'wgUserLanguage' ) );
	if ( !site ) {
		// no site found. unknown language.
		return;
	}

	var sitelinks = JSON.parse( mw.config.get( 'wbEntity' ) ).sitelinks;
	if ( !sitelinks || !sitelinks.hasOwnProperty( site.getId() ) ) {
		// no sitelink
		return;
	}

	function addAliasesFromRedirects() {
		var $dialog = $( '<div>' )
		.text( mw.msg( 'loading' ) )
		.dialog( {
			title: mw.message( 'dialogtitle' ).escaped(),
			autoOpen: true
		} );
		function error( e ) {
			$dialog
			.empty()
			.append(
				$( '<span>', {
					css: { color: '#F00' },
					text: mw.msg( 'error' ) + e
				} )
			);
		}
		$.ajax( {
			url: site.getApi(),
			dataType: 'jsonp',
			cache: true,
			data: {
				format: 'json',
				action: 'query',
				titles: sitelinks[site.getId()].title,
				prop: 'redirects',
				generator: 'redirects',
				grdlimit: 500
			}
		} )
		.done( function ( result ) {
			var pageids = [], selected = {};
			if ( !result.query || !result.query.pages ) {
				// no results found
				$dialog.text( mw.msg( 'nonefound' ) );
				return;
			}
			$.each( result.query.pages, function () {
				pageids.push( this.pageid );
				selected[ this.title ] = false;
			} );
			$.ajax( {
				url: site.getApi(),
				dataType: 'jsonp',
				cache: true,
				data: {
					format: 'json',
					action: 'query',
					pageids: pageids.join( '|' ),
					prop: 'pageprops'
				}
			} )
			.done( function ( pageprops ) {
				$.each( pageprops.query.pages, function () {
					var title, displaytitle;
					if ( this.pageprops && this.pageprops.displaytitle ) {
						displaytitle = this.pageprops.displaytitle;
						title = this.title.charAt( 0 ).toLowerCase() + this.title.substr( 1 );
						if ( displaytitle === title ) {
							delete selected[this.title];
							selected[displaytitle] = false;
						}
					}
				} );
				$dialog
				.text( mw.msg( 'dialogintro' ) )
				.append(
					$( '<br>' ),
					$( '<small>' ).msg( 'policynote' ),
					$( '<hr>' )
				)
				.dialog( { buttons: [ { text: mw.msg( 'add' ), click: function () {
					var toAdd = [];
					for ( var i in selected ) {
						if ( selected[ i ] ) {
							toAdd.push( i );
						}
					}
					if ( toAdd.length === 0 ) {
						return;
					}
					api = api || new wb.api.RepoApi();
					api.setAliases(
						mw.config.get( 'wbEntityId' ),
						0,
						toAdd,
						[],
						lang
					)
					.done( function ( result ) {
						location.href = mw.config.get( 'wgScript' ) +
						'?' + $.param( {
							title: mw.config.get( 'wgTitle' ),
							diff: result.entity.lastrevid,
							oldid: mw.config.get( 'wgRevisionId' )
						} );
					} )
					.fail( error );
					$dialog
					.dialog( { buttons: {} } )
					.text( mw.msg( 'loading' ) );
				} } ] } );
				$.each( selected, function ( r ) {
					$dialog.append(
						$( '<span>' )
						.addClass( 'YRRedirectsToAdd' )
						.text( r )
						.click( function () {
							$( this )[ ( selected[ r ] = !selected[ r ] ) ? 'addClass' : 'removeClass' ]( 'selected' );
						} )
					);
				} );
			} );
		} )
		.fail( error );
	}

	$( function () {
		$( mw.util.addPortletLink( 'p-cactions', '#', mw.msg( 'FindRedirects' ), null, mw.msg( 'FRTooltip' ) ) )
		.click( function ( event ) {
			event.preventDefault();
			mw.loader.using( ['jquery.ui', 'mediawiki.jqueryMsg', 'wikibase.RepoApi'], addAliasesFromRedirects );
		} );
	} );
}( mediaWiki, jQuery, wikibase ) );