User:So9q/CreateTranslation.js

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

//==========================================================================================
// Creating a translation page from a red link in a translation section
// Extended to send the user to a prefilled newentrywis.js
// -----------------------------------------------------------------------------------------
// Ported to en:WT by So9q 24/10-2019 from https://fr.wiktionary.org/w/index.php?title=MediaWiki:Gadget-CreerTrad.js&oldid=25391535
// Original author: Pamputt 2013-06-13
// Inspiré de https://fr.wiktionary.org/wiki/MediaWiki:Gadget-CreerFlexionFr.js développé par ArséniureDeGallium
// -----------------------------------------------------------------------------------------
// [[Catégorie:JavaScript du Witkionnaire|CreerTrad]]
//==========================================================================================
//<nowiki>

if (// Run only in mainspace
	mw.config.get('wgNamespaceNumber') === 0 && 
	// if view
	mw.config.get('wgAction') === 'view' &&
	// and if a translation section exist
	$('.translations').length !== 0) { CrTr_ChangerLiensRouges(); }

//--------------------------------------------------------------------------------------
// Créer les liens vers le gadget
// pour tous les liens rouges dans les infobox de classe "translations"
//--------------------------------------------------------------------------------------
function CrTr_ChangerLiensRouges() {
	console.info('CrTr_ChangerLiensRouges start');
	$('.translations').find('.new')
	.each(function() {
		var link = $(this);
		var title = link.attr('title');
		//console.info(title);
		var trad = /^(.*?) \(page does not exist\)$/.exec(title);
		if (trad !== null) {
			trad = trad[1];
		} else {
			// l'attribut title n'est pas sous la forme "<titre> (page inexistante)"
			// le lien ne sera pas colorisé
			return;
		}
		var code_langue = link.parents().first().attr('lang');
		var name_lang = link.parents().parents().first().text();
		var test = /^(.*?):.*/.exec(name_lang);
		if (test !== null)
			name_lang = test[1];
		else {
			//mw.notify('CreateTranslation: Error: Language name could not be extracted.');
			return; // abort coloring the link
		}
		//debug
		//console.info(code_langue + ' ' + name_lang);
		
		link.css('background-color', '#fac563');
		link.attr('title', 'click to create « ' + trad + ' » with the gadget');
		link.click(function(event) {
			event.preventDefault();
			CrTr_CreerTrad1(trad, code_langue, name_lang);
		});
	});
}
window.CrTr_ChangerLiensRouges = CrTr_ChangerLiensRouges;

// The following object is from https://fr.wiktionary.org/w/index.php?title=MediaWiki:Gadget-CommonWikt.js&oldid=25178800
/******************* REQUÊTES AUX SERVEURS ************************/ 
//----------------------------------------------------------------------------------
// Fonction de requête ajax, utilisée pour faire une requête aux serveurs WikiMedia
// - soit via l'interface standard (index.php)
// - soit via l'API (api.php)
// - soit via les requêtes POST et GET
//----------------------------------------------------------------------------------
var CommonWikt_ajax = {
	http: function(bundle) {
		var xmlhttp;
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					xmlhttp = false;
				}
			}
		}
		if (xmlhttp) {
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4) {
					CommonWikt_ajax.httpComplete(xmlhttp, bundle);
				}
			};
			xmlhttp.open(bundle.method ? bundle.method : "GET", bundle.url, bundle.async === false ? false : true);
			if (bundle.headers) {
				for (var field in bundle.headers) {
					try {
						xmlhttp.setRequestHeader(field, bundle.headers[field]);
					} catch (err) {}
				}
			}
			xmlhttp.send(bundle.data ? bundle.data : null);
		}
		return xmlhttp;
	},
	httpComplete: function(xmlhttp, bundle) {
		if (xmlhttp.status == 200 || xmlhttp.status == 302) {
			if (bundle.onSuccess) bundle.onSuccess(xmlhttp, bundle);
		} else if (bundle.onFailure) {
			bundle.onFailure(xmlhttp, bundle);
		} else {}
	}
};

//==========================================================================================
var CrTr_Mot = "";
var CrTr_Trad = "";
var CrTr_codelangue = "";
var CrTr_name = "";

//--------------------------------------------------------------------------------------
// Première étape suite à clic :
// * mémoriser les graphies des mots dans les variables globales
// * requête pour obtenir le wikicode de l'article
//--------------------------------------------------------------------------------------
function CrTr_CreerTrad1( trad, lang, name ) {
	CrTr_Mot  = mw.config.get( 'wgPageName' ).replace(/_/g," ");
	CrTr_Trad = trad;
	CrTr_codelangue = lang;
	CrTr_name = name;

	// requête pour obtenir le contenu de l'article
	var urlMot = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?title=' + encodeURIComponent(CrTr_Mot);
	CommonWikt_ajax.http({
		url: urlMot + '&action=raw',
		onSuccess: CrTr_CreerTrad2
	});
}

//--------------------------------------------------------------------------------------
// Deuxième étape suite à clic :
// * récupération du wikicode de l'article et extraction des informations pertinentes
//--------------------------------------------------------------------------------------
function CrTr_CreerTrad2( Req, data ) {

	// récupérer le wikicode
	var codewiki = Req.responseText;
	var codesplit = codewiki.split("\n"); // séparation en lignes individuelles

	var status = "pret";
	var new_codewiki = "";

	var ligne_trad = 0;
	var lig_trad_trouve = false;
	var a_rechercher = CrTr_codelangue + "|" + CrTr_Trad;
	var cmptDef = 0;
	var ligne_def = "";

	for (var k = 0; k < codesplit.length; k++) {
		// on recherche la ligne où se trouve la traduction
		if ( codesplit[k].indexOf( a_rechercher ) > 0 ) {
			if ( lig_trad_trouve ) {
				alert( "Le gadget ne prend pas en charge le fait \n qu'une traduction apparaisse deux fois dans la même page." );
				status = "fini";
				break;
			}
			ligne_trad = k;
			lig_trad_trouve = true;
		}
	}

	// si une transcription est indiquée, on la récupère
	var transcription = "";
	var regex_transcription = new RegExp("\\{\\{t[+-]{0,2}\\|" + CrTr_codelangue +
	                          "\\|" + CrTr_Trad + "\\|(?:[^}]*?\\|)?(?:R|tr)=([^=|}]*?)[|}]");
	var array_transcription = regex_transcription.exec(codesplit[ligne_trad]);
	if (array_transcription !== null) {
		transcription = array_transcription[1];
	}

	// si le paramètre dif est utilisé, on récupère sa valeur
	// exemple : * {{T|he}} : {{trad+|he|מכלב|R=makhlev|dif=מַכְלֵב}} {{m}}
	var dif = "";
	a_rechercher = CrTr_codelangue + "\\|" + CrTr_Trad + "[^}]*?dif=([^|}]*?)[|}]";
	var dif_regex = new RegExp( a_rechercher, "" );
	if ( dif_regex.exec( codesplit[ligne_trad] ) !== null ) {
		dif = dif_regex.exec( codesplit[ligne_trad] )[1];
	}

	// si un genre est indiqué, on le récupère
	var genre = "";
	var regex_genre = new RegExp("\\{\\{t[+-]{0,2}\\|" + CrTr_codelangue +
	                  "\\|" + CrTr_Trad + "\\|(?:[^}]*?\\|)?([^=|}]*?)[|}]");
	var array_genre = regex_genre.exec(codesplit[ligne_trad]);
	if (array_genre !== null) {
		genre = array_genre[1];
	}
	
	//debug
	//console.info(codesplit[kk]);
	
	if ( status != "fini" ) {
		// on parcourt le code wiki de la ligne 0
		// à la ligne où on a trouvé la traduction
		// la dernière section que l'on rencontre
		// correspond à la nature grammaticale du mot traduit

		var nature = "";
		for (var kk = 0; kk < ligne_trad; kk++){
			//debug
			console.info(codesplit[kk]);
			if (/Adjective=/.test(codesplit[kk]) || /S\|adjectif\|/.test(codesplit[kk])) { nature = "Adjective"; }
			if (/Adverb=/.test(codesplit[kk]) || /S\|adverbe\|/.test(codesplit[kk])) { nature = "Adverb"; }
			if (/Noun=/.test(codesplit[kk]) || /S\|nom\|/.test(codesplit[kk])) { nature = "Noun"; }
			if (/Verb=/.test(codesplit[kk]) || /-verb-pr-\|/.test(codesplit[kk]) || /S\|verbe\|/.test(codesplit[kk])) { nature = "Verb"; }
			// TODO fix the rest of these
			if (/-conj-\|/.test(codesplit[kk]) || /S\|conjonction\|/.test(codesplit[kk])) { nature = "conjonction"; }
			if (/-nom-pr-\|/.test(codesplit[kk]) || /S\|nom propre\|/.test(codesplit[kk])) { nature = "nom propre"; }
			if (/-prép-\|/.test(codesplit[kk]) || /S\|préposition\|/.test(codesplit[kk])) { nature = "préposition"; }
			if (/-phr-\|/.test(codesplit[kk])) { nature = "locution-phrase"; }
			if (/-onom-\|/.test(codesplit[kk]) || /S\|onomatopée\|/.test(codesplit[kk])) { nature = "onomatopée"; }
			if (/S\|interj(?:ection)?\|/.test(codesplit[kk])) { nature = "interjection"; }

			var diese = '#';
			var etoile = '*';
			if ( codesplit[kk].charAt(0) == diese && codesplit[kk].charAt(1) != etoile) {
				cmptDef++;
				ligne_def = codesplit[kk];
			}
		}

		//s'il n'y a qu'une seule définition, on récupère un éventuel modèle de spécificité (biologie, astronomie, ...)
		var domaine = "";

		if (cmptDef == 1) {
			var regex_domaine = /\{\{([^|}]+?)\|[^|}]+?\}\}/;
			var array_domaine = regex_domaine.exec(ligne_def);
			if (array_domaine !== null) {
				domaine = array_domaine[1];
			}
		}
	} // fini

	// redirect when we got what we need
	//ouvrir la nouvelle page en édition
	var urlTrad = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + "?title=" + encodeURIComponent(CrTr_Trad);
	window.location.href =urlTrad + "&action=edit&editintro=User:So9q/usenec&ct=true&pos=" + nature +'&def=' + CrTr_Mot +'&lang=' + CrTr_codelangue;
}
//</nowiki>