MediaWiki:Gadget-disFixer.js: Różnice pomiędzy wersjami

Z Wikipedii, wolnej encyklopedii
Usunięta treść Dodana treść
nie odpalaj na specjalnych
v. 1.1 - poprawne redirecty małą literą i do sekcji, możliwość przywrócenia starego zachowania przez "useOldRedirFixing=true"
Linia 1: Linia 1:
/*
/*


disFixer v. 1.0 by Matma Rex
disFixer v. 1.1 by Matma Rex


Użycie: dodaj do swojego monobook.js linię
Użycie: dodaj do swojego monobook.js linię
Linia 44: Linia 44:
if(typeof disMarkAsMinor=='undefined') disMarkAsMinor=false
if(typeof disMarkAsMinor=='undefined') disMarkAsMinor=false
if(typeof disCodeCleanup=='undefined') disCodeCleanup=true
if(typeof disCodeCleanup=='undefined') disCodeCleanup=true
if(typeof useOldRedirFixing=='undefined') useOldRedirFixing=false



if(disCodeCleanup && typeof wp_sk=='undefined')
if(disCodeCleanup && typeof wp_sk=='undefined')
Linia 149: Linia 151:
}
}
disCallApi({
if(useOldRedirFixing)
action:'query',
{
redirects:'',
disCallApi({
titles:titles2.join('|'),
action:'query',
callback:'disRedirCallback'
redirects:'',
})
titles:titles2.join('|'),
callback:'disRedirCallback'
})
}
else
{
disCallApi({
action:'query',
prop:'revisions',
rvprop:'content',
titles:titles2.join('|'),
callback:'disRedirCallback2'
})
}
}
}
}
}
Linia 223: Linia 239:
{
{
window.disResolvedRedirs=res.query.redirects
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(/^#\w+\[\[([^\]]+)\]\][\s\S]+$/,'$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=document.getElementById('disRedirsStatus')

Wersja z 17:22, 25 maj 2009

/*

disFixer v. 1.1 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(disCodeCleanup && typeof wp_sk=='undefined')
{
	importScript('Wikipedysta:Nux/wp sk.js')
}

function disCallApi(query) // z [[MediaWiki:Gadget-lib-beau.js]]
{
	var url = wgServer + wgScriptPath + '/api.php?';
 
	for (var field in query)
	{
		
		var value = query[field];
		url += '&' + field + '=' + encodeURIComponent(value);
	}
	url += '&format=json';
	importScriptURI(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="/w/index.php?title='+encodeURIComponent(page.title)+'" title="'+disStr.viewDabPage+'">&#8663;</a>'+
			(addScrollToLink
				?'<a href="javascript:disScrollToLink('+'\''+page.title+'\''+')" title="'+disStr.scrollToLink+'">&#8659;</a>'
				:''
			)+
			': <select id="input-dislink'+page.title+'">'
			str+='<option>'+page.title+'</option>'
			
			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(/^#\w+\[\[([^\]]+)\]\][\s\S]+$/,'$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!='')
	{
		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
			}
			
			str=str.replace(new RegExp('\\[\\[('+from+')\\]\\]','gi'), '[['+to+'|$1]]')
			str=str.replace(new RegExp('\\[\\['+from+'\\|([^\\]]+)\\]\\]','gi'), '[['+to+'|$1]]')
		}
	}
	
	
	links=readCookie('disFixRedirs'+wgPageName)
	if(links!=null && 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]
			
			str=str.replace(new RegExp('\\[\\[('+from+')\\]\\]','gi'), '[['+to+'|$1]]')
			str=str.replace(new RegExp('\\[\\['+from+'\\|([^\\]]+)\\]\\]','gi'), '[['+to+'|$1]]')
		}
	}

	
	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)
	{
		name=decodeURIComponent(name)
		anchor=decodeURIComponent(anchor.replace(/\.([0-9A-F]{2})\.([0-9A-F]{2})/g,'%$1%$2'))
		a='[['+name+anchor+end
	
		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(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 = name+"="+value+expires+"; path=/";
	}
}

function readCookie(name)
{
	try
	{
		return (globalStorage['pl.wikipedia.org'][name])+'' //weird Firefox fix
	}
	catch(er)
	{
		var nameEQ = 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 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.parentNode.className.indexOf('disambig')!=-1)
				continue;
 
			if (link.parentNode && link.parentNode.parentNode)
				if (link.parentNode.parentNode.className.match(/\bdisambig\b/))
					continue;
 
			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)