Wikipedysta:Lampak/disFixer.js

/*

disFixer v. 1.2 by Matma Rex

Użycie: dodaj do swojego monobook.js linię
importScript('Wikipedysta:Matma Rex/disFixer.js')

Szerszy opis: [[Wikipedysta:Matma Rex/disFixer]].

*/

disStr= //strings - translate this!
{
	and:' i ', //used in summary
	autosummaryBegin:'poprawa linków do',
	dabsShort:'ujedn.',
	redirsShort:'przek.',
	
	categoryDabPages:'Kategoria:Strony ujednoznaczniające',
	wikipediaDabPage:'Wikipedia:Strona ujednoznaczniająca',
	
	fixLinks:'Popraw linki do ujednoznacznień i przekierowań', //main button
	wait:'Czekaj...', //main button after click
	
	noRedirLinks:'Brak linków do przekierowań.',
	fixingInProgress:'Rozwiązywanie przekierowań: trwa...',
	
	fixRedirsOnly:'Popraw redirecty (Wykonaj także inne zmiany! Poprawa redirectów dla samej ich poprawy nie ma sensu!)', //fix button if no dabs
	fixButton:'Popraw', //fix button
	
	fixDabs:'Popraw ujednoznacznienia:', //before list of dabs
	viewDabPage:'Zobacz stronę ujedn.', //title
	scrollToLink:'Przewiń do pozycji linku w tekście', //title
	delink:'odlinkuj', //last element in every list
	
	fixRedirsCheckbox:'popraw przekierowania',
	
	otherTarget:'inny cel...',
	setNewLinkTarget:'Dokąd ma prowadzić link?'
}

//domyślne ustawienia
if(typeof disFixIfRedirsOnly=='undefined') disFixIfRedirsOnly=false
if(typeof disMarkAsMinor=='undefined') disMarkAsMinor=false
if(typeof disCodeCleanup=='undefined') disCodeCleanup=true
if(typeof useOldRedirFixing=='undefined') useOldRedirFixing=false
if(typeof disEnforceCookies=='undefined') disEnforceCookies=false


if(disCodeCleanup && typeof wp_sk=='undefined')
{
	importScript('Wikipedysta:Nux/wp sk.js')
}

function disCallApi(query) // z [[MediaWiki:Gadget-lib-beau.js]]
{
	var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php?';
 
	for (var field in query)
	{
		
		var value = query[field];
		url += '&' + field + '=' + encodeURIComponent(value);
	}
	url += '&format=json';
	mw.loader.load(url);
}

function disScrollToLink(target)
{
	if(typeof disHighlightedLinkTimeout!='undefined' && typeof disHighlightedLink!='undefined')
	{
		clearTimeout(disHighlightedLinkTimeout)
		disHighlightedLink.style.background=''
	}
	
	for(i=0;i<dis.length;i++)
	{
		if(dis[i].title==target)
		{
			dis[i].style.background='red'
			window.disHighlightedLink=dis[i]
			window.disHighlightedLinkTimeout=setTimeout(function()
			{
				disHighlightedLink.style.background=''
			},3000)
			dis[i].scrollIntoView()
			break
		}
	}
}

function disOnload()
{
	window.dis=getElementsByClassName(document,'a','mw-disambig')
	window.disRedirs=getElementsByClassName(document,'a','mw-redirect')
	
	//nie ma disambigów, na pewno - nic do roboty
	if(dis.length==0)
	{
		if(!disFixIfRedirsOnly || disRedirs.length==0) return //możliwość wymuszenia sprawdzania mimo braku disambigów, ale tylko, gdy są rediry
	}
	
	el=document.createElement('input')
	el.id='disBeginButton'
	el.type='submit'
	el.value=disStr.fixLinks
	
	addHandler(el,'click',function()
	{
		try
		{
			document.getElementById('disBeginButton').value=disStr.wait
		}
		catch(er){}
	})
	
	addHandler(el,'click',disBegin)
	
	document.getElementById('content').insertBefore(el,document.getElementsByTagName('h1')[0])
}

function disBegin()
{
	el=document.createElement('div')
	el.id='disRedirsStatus'
	if(window.disRedirs.length==0) el.innerHTML='<input type="checkbox" id="disFixRedirsCheckbox" style="display:none" />'+disStr.noRedirLinks
	else el.innerHTML='<input type="checkbox" id="disFixRedirsCheckbox" style="display:none" />'+disStr.fixingInProgress
	document.getElementById('content').insertBefore(el,document.getElementsByTagName('h1')[0])
	
	titles=[]
	for(i=0;i<dis.length;i++)
	{
		titles.push(dis[i].title)
	}
	
	disCallApi({
		action:'query',
		prop:'links',
		titles:titles.join('|'),
		plnamespace:0,
		pllimit:500,
		callback:'disCallback'
	})
	
	if(window.disRedirs.length>0)
	{
		titles2=[]
		for(i=0;i<disRedirs.length;i++)
		{
			titles2.push(disRedirs[i].title)
		}
		
		
		if(useOldRedirFixing)
		{
			disCallApi({
				action:'query',
				redirects:'',
				titles:titles2.join('|'),
				callback:'disRedirCallback'
			})
		}
		else
		{
			disCallApi({
				action:'query',
				prop:'revisions',
				rvprop:'content',
				titles:titles2.join('|'),
				callback:'disRedirCallback2'
			})
		}
	}
}

function disCallback(res)
{
	if(typeof res.query=='undefined' && disFixIfRedirsOnly)
	{
		el=document.createElement('div')
		el.id="disContainer"
	
		input=document.createElement('input')
		input.type='submit'
		input.value=disStr.fixRedirsOnly
		input.style.cssText='font-weight:bold;color:red'
		
		addHandler(input,'click',disSend)
		
		el.appendChild(input)
	}
	else
	{
		addScrollToLink=(document.getElementById('content').scrollIntoView?true:false)
		
		pages=res.query.pages
		
		str=disStr.fixDabs+'<br />'
		for(i in pages)
		{
			if(isNaN(+i)) continue //prototypes, damn
			page=pages[i]
			
			str+=
			'<label>'+page.title+' '+
			'<a href="https://profillengkap.com/pl/'+encodeURIComponent(page.title)+'" title="'+disStr.viewDabPage+'">&#8663;</a>'+
			(addScrollToLink
				?'<a href="https://profillengkap.com/pl/javascript:disScrollToLink('+'\''+page.title+'\''+')" title="'+disStr.scrollToLink+'">&#8659;</a>'
				:''
			)+
			': <select id="input-dislink'+page.title+'">'
			str+='<option>'+page.title+'</option>'
			
			if(typeof page.links=='undefined') page.links=[]
			for(i=0;i<page.links.length;i++)
			{
				str+='<option>'+page.links[i].title+'</option>'
			}
			
			str+='<option style="color:grey">['+disStr.delink+']</option>'
			str+='</select> <input type="submit" onclick="disSetLinkTarget(this)" value="'+disStr.otherTarget+'" /></label><br />'
		}
		
		el=document.createElement('div')
		el.id="disContainer"
		
		input=document.createElement('input')
		input.type='submit'
		input.value=disStr.fixButton
		addHandler(input,'click',disSend)
		
		el.innerHTML=str
		el.appendChild(input)
	}
	
	document.getElementById('content').replaceChild(el,document.getElementById('disBeginButton'))
}

function disRedirCallback(res)
{
	window.disResolvedRedirs=res.query.redirects
	
	el=document.getElementById('disRedirsStatus')
	el.innerHTML=
		'<input type="checkbox" id="disFixRedirsCheckbox" checked="checked" /> '+
		'<label for="disFixRedirsCheckbox">'+disStr.fixRedirsCheckbox+
		' ('+disResolvedRedirs.length+')</label>'
	
	el.style.color='green'
}

function disRedirCallback2(res)
{
	p=res.query.pages
	window.disResolvedRedirs=[]
	
	for(i in p)
	{
		if(isNaN(i)) continue
		
		f=p[i].title
		t=p[i].revisions[0]['*'].replace(/^#(?:REDIRECT|TAM|PATRZ|PRZEKIERUJ)\s*\[\[([^\]]+)\]\][\s\S]*$/i,'$1')
		
		if(t.match(/[<>\[\]|{}\r\n]/))
		{
			//coś się pomieszało - tych znaków nie powinno być w tytule strony
			continue
		}
		
		window.disResolvedRedirs.push({
			from:f,
			to:t
		})
	}
	
	el=document.getElementById('disRedirsStatus')
	el.innerHTML=
		'<input type="checkbox" id="disFixRedirsCheckbox" checked="checked" /> '+
		'<label for="disFixRedirsCheckbox">'+disStr.fixRedirsCheckbox+
		' ('+disResolvedRedirs.length+')</label>'
	
	el.style.color='green'
}

function disSend()
{
	cn=document.getElementById('disContainer')
	inputs=cn.getElementsByTagName('select')
	
	toFix=[]
	for(i=0;i<inputs.length;i++)
	{
		from=inputs[i].options[0].value
		to=inputs[i].value
		
		if(from==to) continue
		
		toFix.push(from+'~'+to)
	}
	
	createCookie('disFixDis'+wgPageName, toFix.join('|'), 0)	
	
	redirCheckbox=document.getElementById('disFixRedirsCheckbox')
	if(typeof disResolvedRedirs!='undefined' && redirCheckbox.checked)
	{
		toFix=[]
		for(i=0;i<disResolvedRedirs.length;i++)
		{
			from=disResolvedRedirs[i].from
			to=disResolvedRedirs[i].to
		
			toFix.push(from+'~'+to)
		}
		
		createCookie('disFixRedirs'+wgPageName, toFix.join('|'), 0)
	}
	
	
	url=document.getElementById('ca-edit').getElementsByTagName('a')[0].href
	window.location=url
}

function disOnloadEdit()
{
	whatIsFixed=[]
	str=document.getElementById('wpTextbox1').value
	
	str=str.replace(/\r\n/g,'\n').replace(/\s*$/,'')
	
	if(disCodeCleanup && typeof wp_sk!='undefined')
	{
		str=wp_sk.cleaner(str)
	}
	else
	{
		str=disCleanLinks(str)
	}
	
	
	links=readCookie('disFixDis'+wgPageName)
	
	if(links!=null && links!='undefined' && links!='')
	{
		links=links.split('|')
		whatIsFixed.push(disStr.dabsShort)
		
		for(i=0;i<links.length;i++)
		{
			l=links[i].split('~')
			from=l[0].replace(/([\/\.\*\+\?\|\(\)\[\]\{\}\\])/g,'\\$1') //regex escape
			to=l[1]
			
			if(to=='['+disStr.delink+']')
			{
				str=str.replace(new RegExp('\\[\\[('+from+')(?:#[^\\]\\|]+|)\\]\\]','gi'), '$1')
				str=str.replace(new RegExp('\\[\\['+from+'(?:#[^\\]\\|]+|)\\|([^\\]]+)\\]\\]','gi'), '$1')
				continue
			}
			
			sh=(to.indexOf('#')!=-1)
			str=str.replace(new RegExp('\\[\\[('+from+')(#[^\\]\\|]+|)\\]\\]','gi'), '[['+(sh?to:to+'$2')+'|$1]]')
			str=str.replace(new RegExp('\\[\\['+from+'(#[^\\]\\|]+|)\\|([^\\]]+)\\]\\]','gi'), '[['+(sh?to:to+'$1')+'|$2]]')
		}
	}
	
	
	links=readCookie('disFixRedirs'+wgPageName)
	if(links!=null && links!='undefined' && links!='')
	{
		links=links.split('|')
		whatIsFixed.push(disStr.redirsShort)
		
		for(i=0;i<links.length;i++)
		{
			l=links[i].split('~')
			from=l[0].replace(/([\/\.\*\+\?\|\(\)\[\]\{\}\\])/g,'\\$1') //regex escape
			to=l[1]
			
			sh=(to.indexOf('#')!=-1)
			str=str.replace(new RegExp('\\[\\[('+from+')(#[^\\]\\|]+|)\\]\\]','gi'), '[['+(sh?to:to+'$2')+'|$1]]')
			str=str.replace(new RegExp('\\[\\['+from+'(#[^\\]\\|]+|)\\|([^\\]]+)\\]\\]','gi'), '[['+(sh?to:to+'$1')+'|$2]]')
		}
	}

	
	str=disCleanLinks(str)
	
	eraseCookie('disFixDis'+wgPageName)
	eraseCookie('disFixRedirs'+wgPageName)
	
	if(whatIsFixed.length==0) return
	
	document.getElementById('wpTextbox1').value=str
	document.getElementById('wpSummary').value+='[[User:Matma Rex/disFixer|'+disStr.autosummaryBegin+' '+whatIsFixed.join(disStr.and)+']]'+(disCodeCleanup?', [[WP:SK]]':'')
	if(disMarkAsMinor) document.getElementById('wpMinoredit').checked=true
	document.getElementById('wpDiff').click()
}

function disSetLinkTarget(el) //helper - for buttons
{
	target=prompt(disStr.setNewLinkTarget)
	if(typeof target=='undefined' || target=='') return
	
	o=document.createElement('option')
	o.value=o.innerHTML=target
	sel=el.parentNode.getElementsByTagName('select')[0]
	
	sel.appendChild(o)
	sel.selectedIndex=sel.options.length-1
}

// based on Nux's code cleanup
// http://pl.wikipedia.org/wiki/Wikipedysta:Nux/wp_sk.js
function disCleanLinks(str)
{
	//najprostszy cleanup, głównie po to, żeby regeksy do poprawy linków mogły być prostsze
	
	// [[Kto%C5%9B_jaki%C5%9B#co.C5.9B|...]]›[[Ktoś jakiś#coś|...]]
	str = str.replace(/\[\[([^|#\]]*)([^|\]]*)(\||\]\])/g, function(a,name,anchor,end)
	{
		try
		{
			name=decodeURIComponent(name)
			anchor=decodeURIComponent(anchor.replace(/\.([0-9A-F]{2})\.([0-9A-F]{2})/g,'%$1%$2'))
			a='[['+name+anchor+end;
		}
		catch(err){} // błąd na linkach typu [[%]]
	 
		return a.replace(/_/g,' ');
	})

	// [[Link|link]] > [[link]]
	str = str.replace(/\[\[([^|\]])([^|\]]*)\|([^\]])\2\]\]/g, function (a, w1_1, w_rest, w2_1)
	{
		return (w1_1.toUpperCase()==w2_1.toUpperCase()) ? '[['+w2_1+w_rest+']]' : a;
	})
 
	// (ro)zwijanie wikilinków
	str = str.replace(/\[\[([^|\]]*)\|\1([a-zA-ZżółćęśąźńŻÓŁĆĘŚĄŹŃ]*)\]\]/g, '[[$1]]$2');
	str = str.replace(/\[\[([^|\]]+)\|([^|\]]+)\]\]([a-zA-ZżółćęśąźńŻÓŁĆĘŚĄŹŃ]+)/g, '[[$1|$2$3]]');
 
	// usuwanie spacji w wikilinkach
	str = str.replace(/\[\[ *([^\]\|:]*[^\]\| ]) *\|/g, '[[$1|');
	str = str.replace(/([^ \t\n])\[\[ +/g, '$1 [[');
	str = str.replace(/\[\[ +/g, '[[');
	str = str.replace(/([^ \t\n])\[\[([^\]\|:]+)\| +/g, '$1 [[$2|');
	str = str.replace(/\[\[([^\]\|:]+)\| +/g, '[[$1|');
	str = str.replace(/([^ \|]) +\]\]([^ \t\na-zA-ZżółćęśąźńŻÓŁĆĘŚĄŹŃ])/g, '$1]] $2');
	str = str.replace(/([^ \|]) +\]\]([^a-zA-ZżółćęśąźńŻÓŁĆĘŚĄŹŃ])/g, '$1]]$2');
 
	return str
}


// http://www.quirksmode.org/js/cookies.html
// modified to use globalStorage in Firefox
function createCookie(name,value,days)
{
	try
	{
		if(disEnforceCookies) throw('cookies enforced')

		if(days<0) globalStorage['pl.wikipedia.org'].removeItem(name)
		else globalStorage['pl.wikipedia.org'][name]=value
	}
	catch(er)
	{ //regular cookies
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = escape(name)+"="+escape(value)+expires+"; path=/";
	}
}

function readCookie(name)
{
	try
	{
		if(disEnforceCookies) throw('cookies enforced')

		return (globalStorage['pl.wikipedia.org'][name])+'' //weird Firefox fix
	}
	catch(er)
	{
		var nameEQ = escape(name) + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++)
		{
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	}
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}



// borrowed from Beau's disambig marking tool
// http://pl.wikipedia.org/wiki/MediaWiki:Gadget-mark-disambigs.js
var dg$pageLoaded = false;
var dg$dataLoaded = false;
var dg$disambig = {};
var dg$uniqueLinks = 0;
var dg$links = 0;

if (wgNamespaceNumber >= 0 && wgAction == 'view') {
	dg$request();
	addOnloadHook(dg$init);
}
 
function dg$request(clcontinue)
{
	var query = {
		action:	'query',
		titles:	wgPageName,
		prop:	'categories',
		cllimit:	500,
		gpllimit:	500,
		generator:	'links',
		callback:	'dg_callback',
	};
	if (clcontinue) {
		query['clcontinue'] = clcontinue;
	}
	disCallApi(query);
}
 
function dg$isDisambig(categories)
{
	for (var key in categories) {
		if (categories[key].title == disStr.categoryDabPages)
			return true;
	}
	return false;
}
 
function dg_callback(data)
{
	if (! data.query)
		return;
 
	document.data = data;
	for (var pageid in data.query.pages) {
		var page = data.query.pages[pageid];
		if (page.categories && dg$isDisambig(page.categories))
		{
			if (dg$disambig[page.title])
				continue;
 
			dg$disambig[page.title] = true;
			dg$uniqueLinks++;
		}
	}
 
	if (data['query-continue'] && data['query-continue']['categories']) {
		dg$request(data['query-continue']['categories']['clcontinue'])
	}
	else if (dg$pageLoaded)
		dg$doColor();
	else
		dg$dataLoaded = true;
}
 
function dg$doColor() {
	if (! dg$uniqueLinks)
		return;
 
	var links = document.getElementsByTagName('a');
	dg$disambig['Wikipedia:Strona ujednoznaczniająca'] = false;
	for (var i = 0; i < links.length; i++)
	{
		var link = links[i];
 
		if (dg$disambig[link.title]) {
			dg$links++;
			if (link.parentNode.className.indexOf('disambig')==-1)
				link.className = 'mw-disambig';
		}
	}
}
 
 
function dg$init() {
	dg$pageLoaded = true;
	if (dg$dataLoaded)
		dg$doColor();
}


/*
AND FINALLY MAIN ONLOAD
*/

if((wgAction=='view'||wgAction=='purge')&&wgCanonicalNamespace!="Special") addOnloadHook(disOnload)
if(wgAction=='edit') addOnloadHook(disOnloadEdit)

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.
Kembali kehalaman sebelumnya