Utilisateur:Dhenry/wmlinksubber.py

Une page de Wikipédia, l'encyclopédie libre.

copié de Utilisateur:FoeNyx/wmlinksubber.py.


Copy the source between the <source> and the </source> tags.

# filename: wmlinksubber.py

__module_name__ = "wmlinksubber" 
__module_version__ = "0.0.8b" 
__module_description__ = "Replaces [[links like this]] with the appropriate URL"
__module_author__ = "[[de:Benutzer:Andre Riemann]], [[en:User:Jeronim]], [[fr:Utilisateur:FoeNyx]]"

debug = False

import re
import urllib
import os.path
import xchat

directory = xchat.get_info("xchatdir") + "/"
if directory == "/":
	directory = "./"
mappingfilename = directory + ".ircwikimapping.txt"

print "Loading plugin " + __module_name__ + " ..."

def loadChanToNSMappingFromFile(mappingfilename):
	
	if os.path.exists(mappingfilename) :
		print "Loading channels mapping from file :\n * [%s]" % mappingfilename
		try :
			freenodeChannelsToWikipediaNamespaces = {}
			f = open(mappingfilename)
			for line in f:
				line = line.strip()
				if not line.startswith("//") :
					line = line.replace("'","").replace('"',"")
					chan,namespace,encoding = line.split(";")
					
					freenodeChannelsToWikipediaNamespaces[chan.strip()] = {
						"namespace":namespace.strip(),
						"chan-encoding":encoding.strip()
					}
			f.close()
			return freenodeChannelsToWikipediaNamespaces
		except:
			print "Impossible to load file [%s], probably misformated" % mappingfilename
			return None
	else:
		print "No customized channels to namespace mapping file found." 
		return None

def saveChanToNSMappingIntoFile(mappingfilename, mapChanToNS):
	try:
		print "Saving custom channel mapping into [%s]" % mappingfilename
		lines = "// This file is used by wmsublinker xchat python plugin to map irc channels to wikimedia namespaces.\n"
		for chan, value in mapChanToNS.items():
			namespace = value["namespace"]
			encoding = value["chan-encoding"]
			lines += "'%s';'%s';'%s'\n" % (chan,namespace,encoding)

		f = open(mappingfilename, "w")
		f.write(lines)
		f.close()
	except:
		print "Impossible to save into file [%s]" % mappingfilename
		return False


def subwmlinks(word, word_eol, userdata):
	channel = xchat.get_info("channel")
	defaultURL = None
	isUTF8 = False
	try:
		defaultURL = freenodeChannelsToWikipediaURL[channel]
		if debug: print defaultURL
		if not defaultURL :
			return xchat.EAT_NONE
	except:
		if debug: print "not a registered channel"
		return xchat.EAT_NONE

        event, pos = userdata
        nick=word[0]
        subbedchunks = []
        changed = False

        try:
                chunks = re_link.split(word[pos])
        except IndexError:
                return xchat.EAT_NONE
        for chunk in chunks:
		# if chunk is a [[something]]
                if re_link.match(chunk):			
                        linktext = chunk[2:-2]
			caption = ""
			try:
				for x in range(len(linktext)) :
					if linktext[x] == "|":
						caption = " " + linktext[x+1:]
						linktext = linktext[:x]						
						break
			except:
				pass
			
			linktext = linktext.replace(" ","_")
			linktext = urllib.quote(linktext,":/#@")

			# lets test if it's an external wiki
			matchobj = re_interOtherWikis.match(linktext,0)
			if matchobj:
				linktext = linktext.replace("_","%20") 
				nameSpace = matchobj.group("namespace")
				urlWiki = otherWikiNamespaces[nameSpace]
				
				subbedchunks.append('(' +
						    color + "8"
						    + re_interOtherWikis.sub(urlWiki, linktext)
						    + caption 
						    + reset_color + ')')
				
			else: 
				# now lets test if it's an wikimedia projects interwiki
				for reNS in wikimediaNamespaceMapOrder:
					if reNS.match(linktext):
						subbedchunks.append('(' +
								    color + "7"
								    + reNS.sub(wikimediaNamespaceMap[reNS],linktext)
								    + caption
								    + reset_color + ')')
						break
						
				# else we use the default channel mapping
				else:
					subbedchunks.append('(' +
							    color + "9" + defaultURL +
							    linktext +
							    caption + 
							    reset_color + ')')
                        changed = True
                else:
                        subbedchunks.append(chunk)
			
        if changed:
                xchat.emit_print(event, nick, "".join(subbedchunks))
                return xchat.EAT_XCHAT
        else:
                return xchat.EAT_NONE

re_link = re.compile(r'(\[\[[^\[\]]+\]\])')

freenodeChannelsToWikipediaNamespaces = {
		# http://meta.wikimedia.org/wiki/IRC_channels
		#chan encoding is not used yet by this script
		"#wikimedia"            : {"namespace": "m:"      ,     "chan-encoding": "UTF-8"         },
                "#wikimania"            : {"namespace": "wikimania:",   "chan-encoding": "UTF-8"         },
                "#quarto"               : {"namespace": "quarto:" ,     "chan-encoding": "UTF-8"         },
                "#wikipedia"            : {"namespace": "w:en:"   ,     "chan-encoding": "UTF-8"         },
                "#mediawiki"            : {"namespace": "m:"      ,     "chan-encoding": ""              },
                "#mediawiki-dev"        : {"namespace": "m:"      ,     "chan-encoding": ""              },
                "#wikimedia-tech"       : {"namespace": "m:"      ,     "chan-encoding": ""              },
                "#wikinews"             : {"namespace": "n:en:"   ,     "chan-encoding": ""              },
                "#wikiquote"            : {"namespace": "q:en:"   ,     "chan-encoding": "UTF-8"         },
                "#wikimedia-commons"    : {"namespace": "commons:",     "chan-encoding": "UTF-8"         },
                "#wiktionary"           : {"namespace": "wikt:en:",     "chan-encoding": "UTF-8"         },
                "#wikibooks"            : {"namespace": "b:en:"   ,     "chan-encoding": "UTF-8"         },
                "#als.wikipedia"        : {"namespace": "w:als:"  ,     "chan-encoding": "UTF-8"         },
                "#ar.wikipedia"         : {"namespace": "w:ar:"   ,     "chan-encoding": ""              },
                "#bg.wikipedia"         : {"namespace": "w:bg:"   ,     "chan-encoding": ""              },
                "#wikipedia-cs"         : {"namespace": "w:cs:"   ,     "chan-encoding": "UTF-8"         },
                "#wikipedia-da"         : {"namespace": "w:da:"   ,     "chan-encoding": ""              },
                "#wikipedia-de"         : {"namespace": "w:de:"   ,     "chan-encoding": "UTF-8"         },
                "#de.wikinews"          : {"namespace": "n:de:"   ,     "chan-encoding": ""              },
                "#wikipedia-en"         : {"namespace": "w:en:"   ,     "chan-encoding": "UTF-8"         },
                "#wikipedia-en-vandalism" : {"namespace": "w:en:" ,     "chan-encoding": "UTF-8"         },
                "#wikipedia-es"         : {"namespace": "w:es:"   ,     "chan-encoding": "UTF-8"         },
                "#wikipedia-fi"         : {"namespace": "w:fi:"   ,     "chan-encoding": "ISO-8859-1"    },
                "#wikipedia-fr"         : {"namespace": "w:fr:"   ,     "chan-encoding": "UTF-8"         },
                "#hi.wikipedia"         : {"namespace": "w:hi:"   ,     "chan-encoding": ""              },
                "#is.wikipedia"         : {"namespace": "w:is:"   ,     "chan-encoding": "UTF-8"         },
                "#it.wikipedia"         : {"namespace": "w:it:"   ,     "chan-encoding": "UTF-8"         },
                "#wikinews-it"          : {"namespace": "n:it:"   ,     "chan-encoding": ""              },
                "#ja.wikipedia"         : {"namespace": "w:ja:"   ,     "chan-encoding": "ISO-2022-JP"   },
                "#ja.wikiquote"         : {"namespace": "q:ja:"   ,     "chan-encoding": "ISO-2022-JP"   },
                "#ja.wikinews"          : {"namespace": "n:ja:"   ,     "chan-encoding": "ISO-2022-JP"   },
                "#wikipedia-ko"         : {"namespace": "w:ko:"   ,     "chan-encoding": "UTF-8"         },
                "#wikipedia-nl"         : {"namespace": "w:nl:"   ,     "chan-encoding": ""              },
                "#wikipedia-no"         : {"namespace": "w:no:"   ,     "chan-encoding": ""              },
                "#wikipedia-pl"         : {"namespace": "w:pl:"   ,     "chan-encoding": "UTF-8"         },
                "#pt.wikipedia"         : {"namespace": "w:pt:"   ,     "chan-encoding": "UTF-8"         },
                "#ro.wikipedia"         : {"namespace": "w:ro:"   ,     "chan-encoding": ""              },
                "#ru.wikipedia"         : {"namespace": "w:ru:"   ,     "chan-encoding": "UTF-8"         },
                "#simple.wikipedia"     : {"namespace": "w:simple:",    "chan-encoding": ""              },
                "#sk.wikipedia"         : {"namespace": "w:sk:"   ,     "chan-encoding": "UTF-8"         },
                "#sq.wikipedia"         : {"namespace": "w:sq:"   ,     "chan-encoding": "UTF-8"         },
                "#wikipedia-sr"         : {"namespace": "w:sr:"   ,     "chan-encoding": ""              },
                "#wikipedia-sv"         : {"namespace": "w:sv:"   ,     "chan-encoding": "UTF-8"         },
                "#wikipedia-tr"         : {"namespace": "w:tr:"   ,     "chan-encoding": ""              },
                "#vi.wikipedia"         : {"namespace": "w:vi:"   ,     "chan-encoding": ""              },
                "#wikinews-en"          : {"namespace": "n:en:"   ,     "chan-encoding": ""              },
                "#wikinews-pl"          : {"namespace": "n:pl:"   ,     "chan-encoding": ""              },
                "#wikislownik"          : {"namespace": "wikt:pl:",     "chan-encoding": "UTF-8"         },
                "#wiktionary-fr"        : {"namespace": "wikt:fr:",     "chan-encoding": "UTF-8"         },
		}

# Check for an existing customized mapping Channel To Wiki namespace and load it
personalconfig = loadChanToNSMappingFromFile(mappingfilename)
if personalconfig :
	freenodeChannelsToWikipediaNamespaces.update(personalconfig)

languagesList = [ "aa", "ab", "af", "ak", "als", "am", "an", "ang", "ar", "arc", "as", "ast", "av", "ay", "az", "ba", "be", "bg", "bh", "bi", "bm", "bn", "bo", "br", "bs", "ca", "ce", "ceb", "ch", "cho", "chr", "chy", "closed-zh-tw", "co", "cr", "cs", "csb", "cv", "cy", "da", "de", "dv", "dz", "ee", "el", "en", "eo", "es", "et", "eu", "fa", "ff", "fi", "fiu-vro", "fj", "fo", "fr", "fur", "fy", "ga", "gd", "gl", "gn", "got", "gu", "gv", "ha", "haw", "he", "hi", "ho", "hr", "ht", "hu", "hy", "hz", "ia", "id", "ie", "ig", "ii", "ik", "ilo", "io", "is", "it", "iu", "ja", "jbo", "jv", "ka", "kg", "ki", "kj", "kk", "kl", "km", "kn", "ko", "kr", "ks", "ku", "kv", "kw", "ky", "la", "lad", "lb", "lg", "li", "ln", "lo", "lt", "lv", "mg", "mh", "mi", "mk", "ml", "mn", "mo", "mr", "ms", "mt", "mus", "my", "na", "nah", "nap", "nds", "ne", "ng", "nl", "nn", "no", "nv", "ny", "oc", "om", "or", "os", "pa", "pam", "pi", "pl", "ps", "pt", "qu", "rm", "rn", "ro", "roa-rup", "ru", "rw", "sa", "sc", "scn", "sco", "sd", "se", "sg", "sh", "si", "simple", "sk", "sl", "sm", "sn", "so", "sq", "sr", "ss", "st", "su", "sv", "sw", "ta", "te", "tg", "th", "ti", "tk", "tl", "tlh", "tn", "to", "tokipona", "tpi", "tr", "ts", "tt", "tum", "tw", "ty", "ug", "uk", "ur", "uz", "ve", "vi", "vo", "wa", "war", "wo", "xh", "yi", "yo", "za", "zh", "zh-min-nan", "zu" ]

# projects where there is a sub-project per language 
# → [[project:lang:article]], [[project:article]], [[project-shorcut:lang:article]], [[project-shorcut:article]]
wikimediaMainProjects = {
	"wikipedia" 	: "w",
	"wiktionary" 	: "wikt",
	"wikibooks" 	: "b",
	"wikinews" 	: "n",
	"wikiquote"	: "q",
	"wikisource" 	: "s"
}

#namespace pattern to url pattern
# (%s) is for lang list
# Try to substitute the longer pattern before the shorter or it will match the shorter first
wikimediaProjectsMapOrder = []

for name, shortcut in wikimediaMainProjects.items() :
	wikimediaProjectsMapOrder += [
		'(%s:(%%s)):(.*)' % name, '(%s):(.*)' % name,	'(%s:(%%s)):(.*)' % shortcut, '(%s):(.*)' % shortcut
	]

wikimediaProjectsMapOrder += [
	'(meta):(.*)', 		'(m):(.*)',
	# misc
	'(commons):(.*)',	'(foundation):(.*)', 	'(grants):(.*)', 
	'(species):(.*)',	'(internal):(.*)',	'(nostalgia):(.*)',
	'(sep11):(.*)',		'(wikimania):(.*)',
	# the last one is a tricky one for ppl who forget the w: before language (as in interwiki)
	'(%s):(.*)' 
	]

wikimediaProjectsMap = {
	'(meta):(.*)'		: 'http://meta.wikimedia.org/wiki/\\2',
	'(m):(.*)'		: 'http://meta.wikimedia.org/wiki/\\2',
	# project without shorcut
	'(commons):(.*)'	: 'http://commons.wikimedia.org/wiki/\\2',	
	'(species):(.*)'	: 'http://species.wikipedia.org/\\2',
	'(foundation):(.*)'	: 'http://wikimediafoundation.org/wiki/\\2', 	
	'(grants):(.*)'		: 'http://grants.wikimedia.org/wiki/\\2', 
	'(internal):(.*)'	: 'http://internal.wikimedia.org/wiki/\\2',
	'(nostalgia):(.*)'	: 'http://nostalgia.wikipedia.org/wiki/\\2',
	'(sep11):(.*)'		: 'http://sep11.wikipedia.org/wiki/\\2',
	'(wikimania):(.*)'	: 'http://wikimania.wikimedia.org/wiki/\\2',
	# lang is given but no project shorcut, default → wikipedia
	'(%s):(.*)'		: 'http://\\1.wikipedia.org/wiki/\\2'
	}

for name, shortcut in wikimediaMainProjects.items() :
	wikimediaProjectsMap['(%s:(%%s)):(.*)' % name ]     = 'http://\\2.%s.org/wiki/\\3' % name # project:lang:article
	wikimediaProjectsMap['(%s):(.*)'       % name ]     = 'http://www.%s.org/wiki/\\2' % name # project:article
	wikimediaProjectsMap['(%s:(%%s)):(.*)' % shortcut ] = 'http://\\2.%s.org/wiki/\\3' % name # shortcut:lang:article
	wikimediaProjectsMap['(%s):(.*)'       % shortcut ] = 'http://www.%s.org/wiki/\\2' % name # shortcut:article


#the list of language pipe separated
patternLang = "|".join(languageList)

# The non mediawiki Wikies
otherWikiNamespaces = {
	# As of 10 October 2005 : http://meta.wikimedia.org/wiki/Interwiki_map
	'AbbeNormal' :		'http://ourpla.net/cgi/pikie?\\2',
	'AcadWiki' :		'http://xarch.tu-graz.ac.at/autocad/wiki/\\2',
	'Acronym' :		'http://www.acronymfinder.com/af-query.asp?String=exact&Acronym=\\2',
	'Advogato' :		'http://www.advogato.org/\\2',
	'Airwarfare' :		'http://airwarfare.com/mediawiki-1.4.5/index.php?\\2',
	'AIWiki' :		'http://www.ifi.unizh.ch/ailab/aiwiki/aiw.cgi?\\2',
	'AjaxXAB' :		'http://www.kessin.com/XAB/\\2',
	'ALife' :		'http://news.alife.org/wiki/index.php?\\2',
	'AllWiki' :		'http://allwiki.com/index.php/\\2',
	'Annotation' :		'http://bayle.stanford.edu/crit/nph-med.cgi/\\2',
	'AnnotationWiki' :	'http://www.seedwiki.com/page.cfm?wikiid=368&doc=\\2',
	'ArchiveCompress' :	'http://www.archive.org/compress/\\2',
	'ArchiveStream' :	'http://www.archive.org/stream/\\2',
	'arXiv' :		'http://www.arxiv.org/abs/\\2',
	'AspieNetWiki' :	'http://aspie.mela.de/Wiki/index.php?title=\\2 ',
	'BattlestarWiki' :	'http://www.battlestarwiki.org/index.php?title=\\2',
	'BEMI' :		'http://bemi.free.fr/vikio/index.php?\\2',
	'BenefitsWiki' :	'http://www.benefitslink.com/cgi-bin/wiki.cgi?\\2',
	'BluWiki' :		'http://www.bluwiki.org/go/\\2',
	'BmpCN' :		'http://wqy.sitaphi.com/index.cgi?\\2 ',
	'Boxrec' :		'http://www.boxrec.com/media/index.php?\\2 ',
	'BrasilWiki' :		'http://rio.ifi.unizh.ch/brasilienwiki/index.php/\\2',
	'BrazilWiki' :		'http://rio.ifi.unizh.ch/brazilwiki/index.php/\\2',
	'BrickWiki' :		'http://brickwiki.zapto.org/index.php/\\2',
	'BridgesWiki' :		'http://c2.com:8000/\\2',
	'BSWiki' :		'http://www.bswiki.com/index.php/\\2',
	'bugzilla' :		'http://bugzilla.wikimedia.org/show_bug.cgi?id=\\2',
	'Bytesmiths' :		'http://www.Bytesmiths.com/wiki/\\2',
	'C2' :			'http://c2.com/\\2',
	'C2find' :		'http://c2.com/cgi/wiki?FindPage&value=\\2',
	'Cache' :		'http://www.google.com/search?q=cache:\\2',
	'CanyonWiki' :		'http://www.canyonwiki.com/wiki/index.php/\\2',
	'ĈEJ' :			'http://esperanto.blahus.cz/cxej/vikio/index.php/\\2',
	'Changemakers' :	'http://www.changemakers.net/cmwiki/index.php?title=\\2',
	'CheatsWiki' :		'http://www.cheatswiki.com/index.php/\\2',
	'ChEJ' :		'http://esperanto.blahus.cz/cxej/vikio/index.php/\\2',
	'Ciscavate' :		'http://ciscavate.org/index.php/\\2',
	'CityHall' :		'http://cityhall.underverse.org.au/index.php?title=\\2',
	'CLiki' :		'http://ww.telent.net/cliki/\\2',
	'CmWiki' :		'http://www.ourpla.net/cgi-bin/wiki.pl?\\2',
	'CodersBase' :		'http://www.codersbase.com/\\2',
	'CoLab' :		'http://colab.info',
	'Comixpedia' :		'http://www.comixpedia.org/index.php/\\2',
	'CommunityScheme' :	'http://community.schemewiki.org/?c=s&key=\\2',
	'Consciousness' :	'http://teadvus.inspiral.org/',
	'CorpKnowPedia' :	'http://corpknowpedia.org/wiki/index.php/\\2',
	'cPanelWiki' :		'http://cpanelwiki.org/index.php/\\2',
	'CraftedByCarol' :	'http://www.CraftedByCarol.com/wiki/\\2',
	'CrazyHacks' :		'http://www.crazy-hacks.org/wiki/index.php?title=\\2',
	'CreationMatters' :	'http://www.ourpla.net/cgi-bin/wiki.pl?\\2',
	'CreaturesWiki' :	'http://creatures.wikicities.com/wiki/\\2',
	'CxEJ' :		'http://esperanto.blahus.cz/cxej/vikio/index.php/\\2',
	'DAwiki' :		'http://www.dienstag-abend.de/wiki/index.php/\\2',
	'DCDatabase' :		'http://www.dcdatabaseproject.com/wiki/\\2',
	'DejaNews' :		'http://www.deja.com/=dnc/getdoc.xp?AN=\\2',
	'Delicious' :		'http://del.icio.us/tag/\\2',
	'Demokraatia' :		'http://wiki.demokraatia.ee/',
	'Devmo' :		'http://developer.mozilla.org/',
	'Dictionary' :		'http://www.dict.org/bin/Dict?Database=*&Form=Dict1&Strategy=*&Query=\\2',
	'Disinfopedia' :	'http://www.sourcewatch.org/wiki.phtml?title=\\2',
	'DiveIntoOsx' :		'http://diveintoosx.org/\\2',
	'DocBook' :		'http://docbook.org/wiki/moin.cgi/\\2',
	'DolphinWiki' :		'http://www.object-arts.com/wiki/html/Dolphin/\\2',
	'DRAE' :		'http://buscon.rae.es/draeI/SrvltGUIBusUsual?LEMA=\\2',
	'DrumCorpsWiki' :	'http://www.drumcorpswiki.com/index.php/\\2',
	'DwellersWiki' :	'http://x.crevicedwellers.com/index.php/\\2',
	'DWJWiki' :		'http://www.suberic.net/cgi-bin/dwj/wiki.cgi?\\2',
	'EB' :			'http://www.eskimobob.com/\\2',
	'EBWiki' :		'http://ebwiki.zeeblo.com/index.php/\\2',
	'EĉeI' :		'http://www.ikso.net/cgi-bin/wiki.pl?\\2',
	'EcheI' :		'http://www.ikso.net/cgi-bin/wiki.pl?\\2',
	'Echolink' :		'http://www.aroip.com/el/index.php/\\2',
	'EcxeI' :		'http://www.ikso.net/cgi-bin/wiki.pl?\\2',
	'ED' :			'http://www.encyclopediadramatica.com/index.php/\\2',
	'EditCount' :		'http://kohl.wikimedia.org/~kate/cgi-bin/count_edits?dbname=enwiki&user=\\2',
	'EfnetCeeWiki' :	'http://purl.net/wiki/c/\\2',
	'EfnetCppWiki' :	'http://purl.net/wiki/cpp/\\2',
	'EfnetPythonWiki' :	'http://purl.net/wiki/python/\\2',
	'EfnetXmlWiki' :	'http://purl.net/wiki/xml/\\2',
	'ELibre' :		'http://enciclopedia.us.es/index.php/\\2',
	'EljWiki' :		'http://elj.sourceforge.net/phpwiki/index.php/\\2',
	'EmacsWiki' :		'http://www.emacswiki.org/cgi-bin/wiki.pl?\\2',
	'EnergieWiki' :		'http://www.netzwerk-energieberater.de/wiki/index.php/\\2',
	'EoKulturCentro' :	'http://esperanto.toulouse.free.fr/wakka.php?wiki=\\2',
	'EvoWiki' :		'http://www.evowiki.org/index.php/\\2',
	'FanimutationWiki' :	'http://wiki.animutationportal.com/index.php/\\2',
	'FET' :			'http://www.egnu.org/thelema/index.php/\\2',
	'FinalEmpire' :		'http://final-empire.sourceforge.net/cgi-bin/wiki.pl?\\2',
	'FIRSTwiki' :		'http://firstwiki.org/index.php/\\2',
	'Foldoc' :		'http://www.foldoc.org/foldoc/foldoc.cgi?\\2',
	'ForthFreak' :		'http://wiki.forthfreak.net/index.cgi?\\2 ',
	'FoxWiki' :		'http://fox.wikis.com/wc.dll?Wiki~\\2',
	'fr.be' :		'http://fr.wikinations.be/\\2',
	'fr.ca' :		'http://fr.ca.wikinations.org/\\2',
	'fr.fr' :		'http://fr.fr.wikinations.org/\\2',
	'fr.org' :		'http://fr.wikinations.be/\\2',
	'FreeBio' :		'http://freebiology.org/wiki/\\2',
	'FreeBSDman' :		'http://www.FreeBSD.org/cgi/man.cgi?apropos=1&query=\\2',
	'FreekiWiki' :		'http://wiki.freegeek.org/index.php/\\2',
	'front' :		'http://front.math.ucdavis.edu/\\2',
	'GameWiki' :		'http://gamewiki.org/wiki/index.php/\\2',
	'GaussWiki' :		'http://gauss.ffii.org/\\2',
	'GEJ' :			'http://www.esperanto.de/cgi-bin/aktivikio/wiki.pl?\\2',
	'Gentoo-Wiki' :		'http://gentoo-wiki.com/\\2',
	'GlenCookWiki' :	'http://wiki.bitparts.org/index.php/\\2',
	'GlobalVoices' :	'http://cyber.law.harvard.edu/dyn/globalvoices/wiki/\\2',
	'GlossarWiki' :		'http://glossar.fh-augsburg.de/\\2',
	'GlossaryWiki' :	'http://glossary.fh-augsburg.de/\\2',
	'GmailWiki' :		'http://www.gmailwiki.com/index.php/\\2',
	'Google' :		'http://www.google.com/search?q=\\2',
	'GoogleGroups' :	'http://groups.google.com/groups?q=\\2',
	'GotAMac' :		'http://www.got-a-mac.org/\\2',
	'GreenCheese' :		'http://www.greencheese.org/\\2',
	'Guildwiki' :		'http://www.guildwiki.org/guildwars/index.php/\\2',
	'H2Wiki' :		'http://halowiki.net/h2wiki?\\2',
	'HammondWiki' :		'http://www.dairiki.org/HammondWiki/index.php3?\\2',
	'Haribeau' :		'http://wiki.haribeau.de/cgi-bin/wiki.pl?\\2',
	'HerzKinderWiki' :	'http://www.herzkinderinfo.de/Mediawiki/index.php/\\2',
	'HeWikisource' :	'http://he.wikisource.org/wiki/\\2',
	'HolshamTraders' :	'http://www.holsham-traders.de/wiki/index.php/\\2',
	'HRWiki' :		'http://www.hrwiki.org/index.php/\\2',
	'IAWiki' :		'http://www.IAwiki.net/\\2',
	'IMDbName' :		'http://www.imdb.com/name/nm\\2',
	'IMDbTitle' :		'http://www.imdb.com/title/tt\\2',
	'Infosecpedia' :	'http://www.infosecpedia.org/pedia/index.php/\\2',
	'Iuridictum' :		'http://iuridictum.pecina.cz/iuridictum/index.php/\\2',
	'JamesHoward' :		'http://jameshoward.us/\\2',
	'JargonFile' :		'http://sunir.org/apps/meta.pl?wiki=JargonFile&redirect=\\2',
	'JavaNet' :		'http://wiki.java.net/bin/view/Main/\\2',
	'Javapedia' :		'http://wiki.java.net/bin/view/Javapedia/\\2',
	'JEFO' :		'http://www.esperanto-jeunes.org/vikio/index.php?\\2',
	'JiniWiki' :		'http://www.cdegroot.com/cgi-bin/jini?\\2',
	'JspWiki' :		'http://www.ecyrd.com/JSPWiki/Wiki.jsp?page=\\2',
	'JSTOR' :		'http://www.jstor.org/journals/\\2',
	'Karlsruhe' :		'http://ka.stadtwiki.net/\\2',
	'KDE' :			'http://wiki.kde.org/tiki-index.php?page=\\2',
	'KerimWiki' :		'http://wiki.oxus.net/\\2',
	'KinoWiki' :		'http://kino.skripov.com/index.php/\\2',
	'KmWiki' :		'http://www.voght.com/cgi-bin/pywiki?\\2',
	'KnowHow' :		'http://www2.iro.umontreal.ca/~paquetse/cgi-bin/wiki.cgi?\\2',
	'KontuWiki' :		'http://www.vihrealohikaarme.com/kontuwiki/\\2',
	'LanifexWiki' :		'http://opt.lanifex.com/cgi-bin/wiki.pl?\\2',
	'LinuxWiki' :		'http://www.linuxwiki.de/\\2',
	'LinuxWikiDe' :		'http://www.linuxwiki.de/\\2',
	'LISWiki' :		'http://www.liswiki.com/wiki/\\2',
	'Lojban' :		'http://www.lojban.org/tiki/tiki-index.php?page=\\2',
	'LQWiki' :		'http://wiki.linuxquestions.org/wiki/\\2',
	'LugKR' :		'http://lug-kr.sourceforge.net/cgi-bin/lugwiki.pl?\\2',
	'LutherWiki' :		'http://www.lutheranarchives.com/mw/index.php/\\2',
	'LVwiki' :		'http://wiki.gmnow.com/index.php/\\2',
	'M-W' :			'http://www.merriam-webster.com/cgi-bin/\\2',
	'Mail' :		'http://mail.wikipedia.org/mailman/listinfo/\\2',
	'MarvelDatabase' :	'http://www.marveldatabase.com/wiki/\\2',
	'MathSongsWiki' :	'http://SeedWiki.com/page.cfm?wikiid=237&doc=\\2',
	'MbTest' :		'http://www.usemod.com/cgi-bin/mbtest.pl?\\2',
	'MeatBall' :		'http://www.usemod.com/cgi-bin/mb.pl?\\2',
	'MediaWiki' :		'http://www.mediawiki.org/wiki/\\2',
	'MediaZilla' :		'http://bugzilla.wikimedia.org/\\2',
	'MemoryAlpha' :		'http://www.memory-alpha.org/en/index.php/\\2',
	'MetaReciclagem' :	'http://www.metareciclagem.com.br/wiki/index.php/\\2',
	'Metaweb' :		'http://www.metaweb.com/wiki/wiki.phtml?title=\\2',
	'MetaWiki' :		'http://sunir.org/apps/meta.pl?\\2',
	'Mineralienatlas' :	'http://www.mineralienatlas.de/lexikon/index.php/\\2',
	'MoinMoin' :		'http://moinmoin.wikiwikiweb.de/\\2',
	'MozCom' :		'http://mozilla.wikicities.com/wiki/\\2',
	'MozillaWiki' :		'http://wiki.mozilla.org/\\2',
	'MozillaZineKB' :	'http://kb.mozillazine.org/\\2',
	'MozWiki' :		'http://mozwiki.moznetwork.org/index.php/\\2',
	'MusicBrainz' :		'http://wiki.musicbrainz.org/\\2',
	'MuWeb' :		'http://www.dunstable.com/scripts/MuWebWeb?\\2',
	'MW' :			'http://www.mediawiki.org/wiki/\\2',
	'MWOD' :		'http://www.merriam-webster.com/cgi-bin/dictionary?book=Dictionary&va=\\2',
	'MWOT' :		'http://www.merriam-webster.com/cgi-bin/thesaurus?book=Thesaurus&va=\\2',
	'MyTips' :		'http://www.mytips.info/html/\\2',
	'NetVillage' :		'http://www.netbros.com/?\\2',
	'Nomad' :		'http://nomad.underverse.org.au/index.php?title=\\2',
	'NSwiki' :		'http://ns.goobergunch.net/wiki/index.php/\\2',
	'OEIS' :		'http://www.research.att.com/projects/OEIS?Anum=\\2',
	'OldWikisource' :	'http://wikisource.org/wiki/\\2',
	'OneLook' :		'http://www.onelook.com/?ls=b&w=\\2',
	'OpenFacts' :		'http://openfacts.berlios.de/index.phtml?title=\\2',
	'OpenSourceSportsDirectory' :	'http://sun10259.dn.net/wiki/index.php/\\2',
	'OpenWetWare' :		'http://www.openwetware.org/index.php?title=\\2',
	'OpenWiki' :		'http://openwiki.com/?\\2',
	'Opera7Wiki' :		'http://nontroppo.org/wiki/\\2',
	'OrganicDesign' :	'http://www.organicdesign.co.nz/wiki/index.php/\\2',
	'OrgPatterns' :		'http://www.bell-labs.com/cgi-user/OrgPatterns/OrgPatterns?\\2',
	#'OSI reference model' :	'http://wiki.tigma.ee/index.php/\\2', # Space in name space odd behaviour
	'OurMedia' :		'http://www.socialtext.net/ourmedia/index.cgi?\\2',
	'PangalacticOrg' :	'http://www.pangalactic.org/Wiki/\\2',
	'PatWIKI' :		'http://gauss.ffii.org/\\2',
	'PersonalTelco' :	'http://www.personaltelco.net/index.cgi/\\2',
	'PhpWiki' :		'http://phpwiki.sourceforge.net/phpwiki/index.php?\\2',
	'Pikie' :		'http://pikie.darktech.org/cgi/pikie?\\2',
	'PMEG' :		'http://www.bertilow.com/pmeg/\\2.php',
	'PMWiki' :		'http://www.porplemontage.net/index.php/\\2',
	'PPR' :			'http://c2.com/cgi/wiki?\\2',
	'PPRCGI' :		'http://c2.com/cgi/\\2',
	'PurlNet' :		'http://purl.oclc.org/NET/\\2',
	'PythonInfo' :		'http://www.python.org/cgi-bin/moinmoin/\\2',
	'PythonWiki' :		'http://www.pythonwiki.de/\\2',
	'PyWiki' :		'http://www.voght.com/cgi-bin/pywiki?\\2',
	'QuakeWiki' :		'http://wiki.quakesrc.org/index.php/\\2',
	'Qwiki' :		'http://qwiki.caltech.edu/wiki/\\2',
	'r3000' :		'http://prinsig.se/weekee/\\2',
	'Raec' :		'http://www.raec.clacso.edu.ar:8080/raec/Members/raecpedia/\\2',
	'RedWiki' :		'http://www.redapollo.org/wiki/index.php/\\2',
	'ReVo' :		'http://purl.org/NET/voko/revo/art/\\2.html',
	'RFC' :			'http://www.rfc-editor.org/rfc/rfc\\2.txt',
	'RoboWiki' :		'http://robowiki.net/?\\2',
	'RoWiki' :		'http://wiki.rennkuckuck.de/index.php/\\2',
	'rtfm' :		'ftp://rtfm.mit.edu/pub/faqs/\\2',
	'S23Wiki' :		'http://is-root.de/wiki/index.php/\\2',
	'Scoutpedia' :		'http://www.scoutpedia.info/index.php/\\2',
	'SeaPig' :		'http://www.seapig.org/\\2',
	'SeattleWiki' :		'http://seattlewiki.org/wiki/\\2',
	'SeattleWireless' :	'http://seattlewireless.net/?\\2',
	'SEEDS' :		'http://www.IslandSeeds.org/wiki/\\2',
	'SenseisLibrary' :	'http://senseis.xmp.net/?\\2',
	'Shakti' :		'http://cgi.algonet.se/htbin/cgiwrap/pgd/ShaktiWiki/\\2',
	'SiliconValley' :	'http://www.siliconvalleyinfozone.com/companies/\\2',
	'Slashdot' :		'http://slashdot.org/article.pl?sid=\\2',
	'Slashdot:User' :	'http://slashdot.org/~\\2',
	'slskrex' :		'http://www.soulseekrecords.com/projects/index.php/\\2',
	'SMikipedia' :		'http://www.smikipedia.org/\\2',
	'SockWiki' :		'http://wiki.socklabs.com/\\2',
	'SourceForge' :		'http://sourceforge.net/\\2',
	'SourceXtreme' :	'http://wiki.sourcextreme.org/index.php/\\2',
	'Squeak' :		'http://minnow.cc.gatech.edu/squeak/\\2',
	'Stockphotoss' :	'http://stockphotoss.com/index.php/\\2',
	'StrikiWiki' :		'http://ch.twi.tudelft.nl/~mostert/striki/teststriki.pl?\\2',
	'Susning' :		'http://www.susning.nu/\\2',
	'SVGWiki' :		'http://www.protocol7.com/svg-wiki/default.asp?\\2',
	'SwinBrain' :		'http://mercury.it.swin.edu.au/acain/mediawiki/index.php/\\2',
	'TabWiki' :		'http://www.tabwiki.com/index.php/\\2',
	'taki' :		'http://www.takipedia.org/wiki/\\2',
	'Takipedia' :		'http://www.takipedia.org/wiki/\\2',
	'tamriel' :		'http://www.tamriel.info/\\2',
	'Tavi' :		'http://tavi.sourceforge.net/\\2',
	'TclersWiki' :		'http://wiki.tcl.tk/\\2',
	'Technorati' :		'http://www.technorati.com/search/\\2',
	'TEJO' :		'http://www.tejo.org/vikio/\\2',
	'TerrorWiki' :		'http://www.liberalsagainstterrorism.com/wiki/index.php/\\2',
	'TESOLTaiwan' :		'http://www.tesol-taiwan.org/wiki/index.php/\\2',
	#'The Windows Documentation Project' :		'http://twdp.havenite.net.com/?title=\\2', # Space in name space odd behaviour
	'Thelemapedia' :	'http://www.thelemapedia.org/index.php/\\2',
	'Theo' :		'http://www.forumhost.us/theo/index.php?title=\\2',
	'Theopedia' :		'http://www.theopedia.com/\\2',
	'TheoWiki' :		'http://www.theowiki.com/index.php/\\2',
	'ThinkWiki' :		'http://www.thinkwiki.org/wiki/\\2',
	'TibiaWiki' :		'http://tibia.erig.net/\\2',
	'TMBW' :		'http://www.tmbw.net/wiki/index.php/\\2',
	'TmNet' :		'http://www.technomanifestos.net/?\\2',
	'TMwiki' :		'http://www.EasyTopicMaps.com/?page=\\2',
	'Toyah' :		'http://toyah.org/\\2',
	'Turismo' :		'http://www.tejo.org/turismo/\\2',
	'TWiki' :		'http://twiki.org/cgi-bin/view/\\2',
	'TwistedWiki' :		'http://purl.net/wiki/twisted/\\2',
	'UD' :			'http://www.urbandictionary.com/\\2',
	'UEA' :			'http://www.tejo.org/uea/\\2',
	'UFS' :			'http://www.unmaintained-free-software.org/wiki/index.php/\\2',
	'Uncyclopedia' :	'http://uncyclopedia.org/wiki/\\2',
	'Underverse' :		'http://www.phoenix.underverse.org.au/index.php?title=\\2',
	'Unreal' :		'http://wiki.beyondunreal.com/wiki/\\2',
	'Ursine' :		'http://ursine.ca/\\2',
	'USEJ' :		'http://www.tejo.org/usej/\\2',
	'UseMod' :		'http://www.usemod.com/cgi-bin/wiki.pl?\\2',
	'VillageArts' :		'http://www.Village-Arts.org/wiki/index.php/\\2',
	'VisualWorks' :		'http://wiki.cs.uiuc.edu/VisualWorks/\\2',
	'VKoL' :		'http://thekolwiki.net/wiki/\\2',
	'WarpedView' :		'http://www.warpedview.com/mediawiki/index.php/\\2',
	'WebDevWikiNL' :	'http://www.promo-it.nl/WebDevWiki/index.php?page=\\2',
	'Webisodes' :		'http://www.webisodes.org/\\2',
	'WebSeitzWiki' :	'http://webseitz.fluxent.com/wiki/\\2',
	'Why' :			'http://clublet.com/c/c/why?\\2',
	'Wiki' :		'http://c2.com/cgi/wiki?\\2',
	'Wikia' :		'http://www.wikia.com/wiki/index.php/\\2',
	'Wikicities' :		'http://www.wikicities.com/wiki/\\2',
	'WikiF1' :		'http://www.wikif1.org/\\2',
	'WikiFur' :		'http://furry.wikicities.com/wiki/\\2',
	'WikiKto' :		'http://fr.wikikto.org/index.php?title=\\2',
	'Wikinfo' :		'http://www.wikinfo.org/wiki.php?title=\\2',
	'Wikinurse' :		'http://wikinurse.org/media/index.php?title=\\2',
	'Wikipaltz' :		'http://www.wikipaltz.com/wiki/\\2',
#	'Wikipedia' :		'http://en.wikipedia.org/wiki/\\2',
	'WikipediaWikipedia' :	'http://en.wikipedia.org/wiki/Wikipedia:\\2',
	'Wikireason' :		'http://wikireason.net/wiki/\\2',
	'wikisophia' :		'http://wikisophia.org/index.php?title=\\2',
	'WikiTI' :		'http://wikiti.denglend.net/index.php?title=\\2',
	'WikiTravel' :		'http://wikitravel.org/en/\\2',
	'WikiTree' :		'http://wikitree.org/index.php?title=\\2',
	'wikiveg' :		'http://www.wikiveg.org/\\2',
	'WikiWikiWeb' :		'http://c2.com/cgi/wiki?\\2',
	'WikiWorld' :		'http://WikiWorld.com/wiki/index.php/\\2',
	'Wipipedia' :		'http://www.lfshosting.co.uk/wipi/index.php/\\2',
	'WLUG' :		'http://www.wlug.org.nz/\\2',
	'WLWiki' :		'http://winslowslair.supremepixels.net/wiki/index.php/\\2',
	'Wmania' :		'http://wikimania.wikimedia.org/wiki/\\2',
	'World66' :		'http://www.world66.com/\\2',
	'WoWWiki' :		'http://www.wowwiki.com/\\2',
	'Wqy' :			'http://wqy.sourceforge.net/cgi-bin/index.cgi?\\2',
	'WurmPedia' :		'http://www.wurmonline.com/wiki/index.php/\\2',
	'WZNAN' :		'http://www.wikiznanie.ru/wiki/article/\\2',
	'YpsiEyeball' :		'http://sknkwrks.dyndns.org:1957/writewiki/wiki.pl?\\2',
	'ZRHwiki' :		'http://www.zrhwiki.ch/wiki/\\2',
	'ZUM' :			'http://www.zum.de/wiki/index.php/\\2',
	'ZWiki' :		'http://www.zwiki.org/\\2',
	##'ZZZ Wiki' :		'http://wiki.zzz.ee/index.php/\\2' # Space in name space odd behaviour
}

# build otherWiki regexp pattern
re_interOtherWikis = "|".join(otherWikiNamespaces)
pattern = "(?P<namespace>%s):(?P<text>.*)" % re_interOtherWikis
if debug : print "re_interOtherWikis :", pattern
re_interOtherWikis = re.compile(pattern)

#then build regexp obj to url pattern
wikimediaNamespaceMapOrder = []
wikimediaNamespaceMap = {}	
for pattern in wikimediaProjectsMapOrder:
	url = wikimediaProjectsMap[pattern]
	try:
		pattern = pattern % patternLang
	except:
		pass
	if debug : print pattern
	re_interWikis = re.compile(pattern)
	wikimediaNamespaceMapOrder.append(re_interWikis)
	wikimediaNamespaceMap[re_interWikis] = url

# build channel to url map according to wikimediaProjectsMap and otherWikiNamespaces
freenodeChannelsToWikipediaURL = {}

def buildChannelToURL(chan="",chanNS=""):
	# check in mediawiki namespaces
	for reNS in wikimediaNamespaceMapOrder:
		if reNS.match(chanNS):
			freenodeChannelsToWikipediaURL[chan] = reNS.sub(wikimediaNamespaceMap[reNS],chanNS)
			if debug : print chan, freenodeChannelsToWikipediaURL[chan]
			return True

	# check in other wiki namespace
	matchobj = re_interOtherWikis.match(chanNS)
	if matchobj:
		nameSpace = matchobj.group("namespace")
		urlWiki = otherWikiNamespaces[nameSpace]				
		freenodeChannelsToWikipediaURL[chan] = re_interOtherWikis.sub(urlWiki, chanNS)
	else:
		return False
	return True

for chan, val in freenodeChannelsToWikipediaNamespaces.items():
	chanNS = val["namespace"]
	buildChannelToURL(chan, chanNS)
	
if debug : print freenodeChannelsToWikipediaURL

def changeNamespace(word, word_eol, userdata): 
	channel = xchat.get_info("channel")
	#print channel
	if len(word) < 2:		
		if channel in freenodeChannelsToWikipediaNamespaces.items():
			print "Current default namespace for %s channel is %s" % \
			       (channel, val["namespace"] )
		else: 
			print "No current wiki namespace enabled for this channel"
	else:
		namespace = word_eol[1]
		#print namespace
		if namespace == "None":
			del freenodeChannelsToWikipediaNamespaces[channel]
			del freenodeChannelsToWikipediaURL[channel]
			print "Default wiki namespace for %s channel have been removed" % channel
			saveChanToNSMappingIntoFile(mappingfilename, freenodeChannelsToWikipediaNamespaces)
		else:
			freenodeChannelsToWikipediaNamespaces[channel] = {"namespace":namespace, "chan-encoding":"UTF-8"}
			if buildChannelToURL(channel,namespace) :
				print "Default wiki namespace for %s channel have been set to %s" % (channel, namespace)
				saveChanToNSMappingIntoFile(mappingfilename, freenodeChannelsToWikipediaNamespaces)
			else:
				print "No wiki namespaces matching (see /LISTWNS, it's case sensitive and do not forget the trailing ':')"
				
	return xchat.EAT_ALL

def listAvailableNameSpace(word, word_eol, userdata):
	print "*** Available wiki namespaces ***",
	print "\n**** External wikis namespaces ****"
	for namespace in otherWikiNamespaces:
		print namespace,
	print "\n**** Mediawiki namespaces ****"
	for namespace in wikimediaProjectsMap:
		print namespace.replace("):(.*)","").replace('(','').replace(")","") + ":",
	print "\nwhere %s can be one of the language among :"
	for language in languagesList:
		print language,
	print #flush the buffer
	return xchat.EAT_ALL

def listEnabledNameSpaces(word, word_eol, userdata):
	print "*** Enabled wiki namespaces ***"
	print "channel".ljust(30), "namespace".ljust(30)
	for channel, val in freenodeChannelsToWikipediaNamespaces.items():
		namespace = val["namespace"]
		print channel.ljust(30), namespace.ljust(30)
	return xchat.EAT_ALL
		
xchat.hook_command("DEFAULTWNS", changeNamespace,
		   help="/DEFAULTWNS [<namespace>] Print or Change the default wiki namespace for this channel. If <namespace> value is 'None' then the current mapping will be removed.") 
xchat.hook_command("LISTWNS", listAvailableNameSpace,
		   help="/LISTWNS List the available wiki namespaces") 
xchat.hook_command("MAPWNS", listEnabledNameSpaces,
		   help="/MAPWNS Show the current mapping of channels and wiki namespaces")

print "Script %s Commands : %s" %( __module_name__, "DEFAULTWNS LISTWNS MAPWNS" )

EVENTS = []
EVENTS.append(("Channel Message", 1))
EVENTS.append(("Channel Msg Hilight", 1))
# if you don't want it to replace text which ''you'' type, comment the following out ( with"#" like this line)
EVENTS.append(("Your Message", 1))
EVENTS.append(("Private Message", 1))
EVENTS.append(("Private Message to Dialog", 1))

for event in EVENTS:
        xchat.hook_print(event[0], subwmlinks, event)

reset_color ='\017'
color = '\003'
#'\0037' would be orange -> color + '7' for mediawiki
#'\0038' would be yellow -> color + '8' for otherwiki
#'\0038' would be green  -> color + '9' for localwiki

def unload(userdata):
	print "Plugin " + __module_name__ + " " + __module_version__ + " unloaded."
xchat.hook_unload(unload)

print "Plugin " + __module_name__ + " " + __module_version__ + " loaded."
print "This plugin script convert a [[wikilink]] to an url according to channel preferences"

#ChangeLog:
# 2005-12-18, v0.0.8b (Foenyx)
# minor tweaks :
#        + #wikipedia-en-vandalism ( as asked by [[w:en:User:Mozzerati]] )
#        - Wikipedia: namespace in external wiki link

# 2005-11-21, v0.0.8a (Foenyx)
# save the user channel mapping to a file in xchatdir rather than dcc_dir 
# do not forget to move the file if needed

# 2005-10-13, v0.0.8 (Foenyx)
# save the user channel mapping to a file
# update of : 
#	channels moved to suit with freenode naming policy (to be continued)

# 2005-10-10, v0.0.7c (Foenyx)
# update of : 
#	project namespaces (commons + wikinews were never added), 
# 	global interwikis and 
#	channels moved to suit with freenode naming policy (to be continued)

# 2004-08-01, v0.0.7 (Foenyx)
# Show the piped label in [[reference|label]]

# 2004-07-30, v0.0.6 (Foenyx)
# added per channel default wiki namespace selection,
# other wiki (non mediawiki) intermap
# and an url encode for the non ascii text
# some commands to manage mapping of current channel with namespace
# a channel need to have a default namespace to urlize the [[expr]]
# and a lot of obfuscated code :( sorry 

# 2004-06-09, v0.0.5
# added color support to point out which link was substituted
# regexp upgraded to prevent links with [ or ] inside, e.g. [[[Test]]
# brackets around the link because a link with leading [ don't acts as link

# 2003-03-29, v0.0.4
# bugfix for when pasting text with consecutive line-breaks
# the [[quick]] [[brown]] [[w:fox]] jumps
# over the [[lazy]] [[wiktionary:dog]]