Module:Biblio/Rèferences

De Vouiquipèdia, l’enciclopèdia abada.

La documentation pour ce module peut être créée à Module:Biblio/Rèferences/doc

-- Les fonctions de ce module sont destinées à être utilisées par un autre module.
-- Leur paramètre d'entrée est une table simple (args), voire une chaine (oclc, bnf...)

local References = { }


local Outils = require( 'Module:Outils' )
local validTextArg = Outils.validTextArg
local TableBuilder = require( 'Module:TableBuilder' )
local Comon = require 'Module:Biblio/Comon'
-- local Date = require( 'Module:Date' ) -- chargé uniquement si nécessaire


--[[
ISBN-10 and ISSN validator code calculates checksum across all isbn/issn digits including the check digit. ISBN-13 is checked in checkisbn().
If the number is valid the result will be 0. Before calling this function, issbn/issn must be checked for length and stripped of dashes,
spaces and other non-isxn characters.
]]
function References.is_valid_isxn( isxn_str, len )
	local temp = 0
	isxn_str = isxn_str:gsub( 'x', 'X' )
	isxn_str = { isxn_str:byte(1, len) }	-- make a table of bytes
	len = len+1								-- adjust to be a loop counter
	for i, v in ipairs( isxn_str ) do		-- loop through all of the bytes and calculate the checksum
		if v == string.byte( 'X' ) then		-- if checkdigit is X
			temp = temp + 10 * ( len - i )	-- it represents 10 decimal
		else
			temp = temp + tonumber( string.char( v ) ) * ( len - i )
		end
	end
	return temp % 11 == 0					-- returns true if calculation result is zero
end

function References.isValidIsmn10( ismn )
	local temp = 9
	if ismn:match( 'M%d%d%d%d%d%d%d%d%d' ) then
		for i = 2, 10 do
			temp = temp + ( 1 + 2 * ( i % 2 ) ) * ismn:sub( i, i )
		end	
	end
	return temp % 10 == 0
end
	
-- Teste si une chaine ISBN est valide
function References.checkisbn( isbn_str )
	if type( isbn_str ) == 'string' then
		isbn_str = isbn_str:gsub( '[-%s]', '' )	-- supprime les traits d’union et espaces
		
		if isbn_str:len() == 10 then
			if isbn_str:match( '^%d+[xX]?$' ) then
				return  References.is_valid_isxn( isbn_str, 10 )
			end
		elseif isbn_str:match( '^97[89]' ) then
			return References.checkean13( isbn_str )
		end
	end
	return false
end

-- Teste si une chaine EAN 13 est valide
function References.checkean13( ean_str )
	if type( ean_str ) == 'string' then
		ean_str = ean_str:gsub( '[-%s]', '' )	-- supprime les traits d’union et espaces
		if ean_str:len() == 13 and ean_str:match( '^%d+$' ) then
			local temp, strVal = 0
			ean_str = { ean_str:byte( 1, 13 ) }
			for i = 1, #ean_str do
				strVal = tonumber( string.char( ean_str[i] ) )
				temp = temp + ( 3 - 2 * ( i % 2 ) ) * strVal
			end
			return temp % 10 == 0
		end
	end
	return false
end

function References.checkissn( issn_str )
	if type( issn_str ) == 'string' then
		issn_str = issn_str:gsub( '[%s]', '' )
		if issn_str:match( '^%d%d%d%d%-%d%d%d[%dxX]$' ) then
			issn_str = issn_str:gsub( '-', '' )		-- supprime les traits d’union et espaces
			return References.is_valid_isxn( issn_str, 8 )
		end
	end
	return false
end

-- Teste si une chaine ISMN est valide
function References.checkismn( ismn_str )
	if type( ismn_str ) == 'string' then
		ismn_str = ismn_str:gsub( '[-%s]', '' )	-- supprime les traits d’union et espaces
		
		if ismn_str:len() == 10 then
			return  References.isValidIsmn10( ismn_str, 10 )
		elseif ismn_str:match( '^9790' ) then
			return References.checkean13( ismn_str )
		end
	end
	return false
end

local function isbn13to9( isbn_str )
	if type( isbn_str ) == 'string' then
		local isbn = isbn_str:gsub( '[-%s]', '' )
		if isbn:len() == 13 and isbn:sub( 1, 3 ) == '978' then
			isbn = isbn:sub( 4, 12 )
			return isbn
		elseif isbn:len() == 10 then
			return isbn:sub( 1, -2 )
		end
	end
	return isbn_str
end

local function isbn13to10( isbn_str )
	local isbn = isbn13to9( isbn_str )
	if isbn ~= isbn_str and isbn_str:len() ~= 10 then
		for i = 0, 9 do
			if References.checkisbn( isbn .. i ) then
				return isbn .. i
			end
		end
		return isbn .. 'X'
	end
	return isbn_str
end

function References.isbn13to10( frame )
	local args = Outils.extractArgs( frame )
	return isbn13to10( args[1] )
end

function References.same_isbn( isbn1, isbn2 )
	if type( isbn1 ) ~= 'string' or type( isbn2 ) ~= 'string' then
		return false
	end
	-- remove dash and spaces
	isbn1 = isbn1:gsub( '[-%s]', '' )
	isbn2 = isbn2:gsub( '[-%s]', '' )
    -- check if both isbn are valid
	if not ( References.checkisbn(isbn1) and References.checkisbn(isbn2) ) then
		return false
	end
	-- compare isbn
	return isbn13to9( isbn1 ) == isbn13to9( isbn2 )
end

local function doblonIsxn( isxn, lista2, xnCode)
	if type( References[ 'same_' .. xnCode ] ) == 'function' then
		for k, v in ipairs( lista2 ) do
			if References[ 'same_' .. xnCode ]( isxn, v ) then
				return true
			end
		end
	end
end

local function formatIsxn( args, validArg, xnCode, envalidaCateg, checkFunction, formatLim, page )
	local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
	
	local lista = { }
	local lista2 = { }
	local i = 1
	local envalida = '<sup style="color:red">[a controlar : ' .. envalidaCateg .. ']</sup>'
	
	local isxnErr = validArg( xnCode .. ' fôx' )
	local XN = xnCode:upper()
	local isxn = validArg( xnCode, XN, xnCode .. '1', XN .. '1' )
	if isxnErr or isxn then
		local isxnErrSanitised = isxnErr and isxnErr:match( '%d[%d -]+[%dXx]' )
		if isxnErrSanitised then
			local lim = formatLim:format( isxnErrSanitised, isxnErr )
			table.insert( lista, lim .. ' (èditâ fôx)' )
		end
		
		-- boucle sur les isxn2, 3...		
		while isxn do
			-- vérifivation de la validité de l'ISXN
			local isxnValid = checkFunction( isxn )
			
			-- préparation du texte à afficher
			if isxnValid then
				local lim = formatLim:format( isxn, isxn )
				table.insert( lista, lim )
				if type( args.categ ) == 'table' and doblonIsxn( isxn, lista2, xnCode) then
					args.categ[ xnCode .. 'Duplicâ' ] = isxn
				end
				table.insert( lista2, isxn )
			else
				table.insert( lista, isxn .. envalida )
				if type( args.categ ) == 'table' then
					args.categ[ xnCode .. 'Invalid' ] = true
				end
			end
			
			i = i + 1
			isxn = validArg( xnCode .. i, XN .. i )
		end
		
		if args['senLambél'] then 
			page = ''
		else
			page = page .. '&nbsp;'
		end
		return page .. mw.text.listToText( lista )
	end
end	

-- voir Modèle:ISBN
-- renvoie une liste de chaines formant le résultat du modèle une fois concaténées
function References.isbn( args, validArg )
	return formatIsxn(
		args,
		validArg,
		'isbn',
		'[[:Catègorie:Pâge avouéc ISBN envalido|ISBN envalido]]',
		References.checkisbn,
		'[[Spèciâl:Ôvra de rèference/%s|<span class="nowrap">%s</span>]]',
		'[[International Standard Book Number|ISBN]]'
	)
end

-- voir Modèle:EAN
-- renvoie une liste de chaines formant le résultat du modèle une fois concaténées
function References.ean( args, validArg )
	return formatIsxn(
		args,
		validArg,
		'ean',
		'[[:Catègorie:Pâge avouéc EAN envalido|EAN envalido]]',
		References.checkean13,
		'[[Spèciâl:Ôvra de rèference/%s|<span class="nowrap">%s</span>]]',
		'[[EAN 13|EAN]]'
	)
end

-- voir Modèle:ISSN
-- renvoie une liste de chaines formant le résultat du modèle une fois concaténées
function References.issn( args, validArg )
	return formatIsxn(
		args,
		validArg,
		'issn',
		'[[:Catègorie:Pâge avouéc ISSN envalido|ISSN envalido]]',
		References.checkissn,
		'<span class="plainlinks noarchive">[http://worldcat.org/issn/%s&lang=fr %s]</span>',
		'[[International Standard Serial Number|ISSN]]'
	)
end

function References.eissn( args, validArg )
	return formatIsxn(
		args,
		validArg,
		'e-issn',
		'[[:Catègorie:Pâge avouéc ISSN envalido|ISSN envalido]]',
		References.checkissn,
		'<span class="plainlinks noarchive">[http://worldcat.org/issn/%s&lang=fr %s]</span>',
		'[[International Standard Serial Number#ISSN èlèctronico|e-ISSN]]'
	)
end

-- voir Modèle:ISMN
-- renvoie une liste de chaines formant le résultat du modèle une fois concaténées
function References.ismn( args, validArg )
	return formatIsxn(
		args,
		validArg,
		'ismn',
		'[[:Catègorie:Pâge avouéc ISMN envalido|ISMN envalido]]',
		References.checkismn,
		'<span class="nowrap">%s</span>',
		'[[International Standard Music Number|ISMN]]'
	)
end

-- fonctions liant des bases de données externes
local function databaseDeDefor( num, limDeDedens, limDeDefor, complement, textoAfiche )
	if Outils.notEmpty( num ) then
		local adrece = 
				limDeDedens
				.. '&nbsp;<span class="plainlinks noarchive nowrap">['
				.. 'https://' .. limDeDefor .. mw.uri.encode( num, 'PATH' ) .. ( complement or '' )
				.. ' '
				.. mw.text.nowiki( textoAfiche or num )
				.. ']</span>'
		
		return adrece
	end
end

function References.arkId( base )
	--  Nice Opaque Identifiern utilisé par les formats Ark pour générer une clé
	base = tostring( base )
	if base then
		local xdigits = '0123456789bcdfghjkmnpqrstvwxz'
		local sum = 0 
		local position
		for i = 1, base:len() do
			position = xdigits:find( base:sub( i, i ), 1, true ) or 1
			sum = sum + i * ( position - 1 )
		end
		local index = sum % 29 + 1
		return xdigits:sub( index, index )
	end
end

function References.arxiv( arxiv )
	if Outils.trim( arxiv ) then
		return databaseDeDefor(
			arxiv,
			'[[arXiv]]',
			'arxiv.org/abs/' ):gsub( '%%2F', '/'
		)
	end
end

function References.asin( asin )
	return databaseDeDefor(
		asin,
		'[[Amazon Standard Identification Number|ASIN]]',
		'www.amazon.fr/s/?url=search-alias&lang=fr&field-keywords='
	)
end

function References.bibcode( bibcode )
	return databaseDeDefor( bibcode, '[[Bibcode]]', 'ui.adsabs.harvard.edu/abs/' )
end

function References.bnf( bnf )
	bnf = Outils.trim( bnf )
	if bnf then
		local texto = ''
		local category = ''
		local bnfId = bnf:upper():match( 'BNF(%d+%w)' ) or
			bnf:lower():match( 'cb(%d+%w)' ) or
			bnf:match( '^%d+%w' )
		
		if bnfId then
			-- bnf contient une suite de chiffres qui peut être un ark valide
			local base = bnfId:sub( 1, 8 )
			local arkId = References.arkId( 'cb' .. base )
			if bnfId:len() == 8 then 
				-- il manque la clé, on l'ajoute
				bnf = base .. arkId
				texto = 'FRBNF' .. base
			elseif bnfId:len() > 8 and bnfId:sub( 9, 9 ) == arkId then
				-- ark valide
				bnf = bnfId:sub( 1, 9 )
				texto = 'FRBNF' .. base
			else
				-- ark qui semble non valide
				bnf = bnfId
				texto = 'FRBNF' .. bnfId
				category = '[[Catègorie:Recension temporèra por lo modèlo Ôvra|bnf]]'
			end
		else
			-- le paramètre ne semble pas un ark valide
			texto = bnf
			category = '[[Catègorie:Recension temporèra por lo modèlo Ôvra|bnf]]'
		end
		
		-- dans tous les cas on renvoie l'adresse, on catégorise juste pour vérifier ce qui ne va pas
		local lim = databaseDeDefor(
			bnf, 
			'notiça [[Bibliotèca nacionâla de France|BnF]] <abbr class="abbr" title="numerô">n<sup>o</sup></abbr>', 
			'catalogue.bnf.fr/ark:/12148/cb', 
			'.public', 
			texto 
		)
		
		return lim .. category
	end
end

function References.dnb( dnb )
	return databaseDeDefor(
		dnb,
		'[[Bibliotèca nacionâla alemanda|DNB]]',
		'd-nb.info/'
	)
end

function References.doi( doi )
	return databaseDeDefor(
		doi,
		'[[Digital Object Identifier|DOI]]',
		'dx.doi.org/'
	)
end

function References.jstor( jstor )
	return databaseDeDefor( jstor, '[[JSTOR]]', 'jstor.org/stable/' )
end

function References.hal( hal )
	if Outils.trim( hal ) then
		if not hal:match( '^%w+%-%d' ) then
			hal = 'hal-' .. hal
		end
		return databaseDeDefor(
			hal,
			'[[Hipèr articllos en legne|HAL]]',
			'hal.archives-ouvertes.fr/' ):gsub( '%%2F', '/'
		)
	end
end

function References.lccn( lccn )
	return databaseDeDefor(
		lccn,
		'[[Numerô de contrôlo de la Bibliotèca du Congrès|LCCN]]',
		'lccn.loc.gov/'
	)
end

function References.mathreviews( mathreviews )
	return databaseDeDefor(
		mathreviews,
		'[[Mathematical Reviews|Math Reviews]]',
		'www.ams.org/mathscinet-getitem?mr='
	)
end

function References.oclc( oclc )
	return databaseDeDefor(
		oclc,
		'[[Online Computer Library Center|OCLC]]',
		'worldcat.org/oclc/', '&lang=fr'
	)
end

function References.pmcid( pmcid )
	return databaseDeDefor(
		pmcid,
		'[[PubMed Central|PMCID]]',
		'www.ncbi.nlm.nih.gov/pmc/articles/'
	)
end

function References.pmid( pmid )
	return databaseDeDefor(
		pmid,
		'[[PubMed|PMID]]',
		'www.ncbi.nlm.nih.gov/pubmed/'
	)
end

function References.sbn( sbn )
	local id = ( sbn or '' ):upper():gsub( '\\', '' ):gsub( '^ITICCU', '' )
	return databaseDeDefor(
		id,
		'[[Sèrviço bibliotèquèro nacionâl]]',
		'opac.sbn.it/bid/'
	)
end

function References.sudoc( sudoc )
	return databaseDeDefor(
		sudoc,
		'[[Sistèmo univèrsitèro de documentacion|SUDOC]]',
		'www.sudoc.fr/'
	)
end

function References.wikisource( wikisource )
	if Outils.notEmpty( wikisource ) then
		return '[[s:' .. wikisource .. '|liére dessus Vouiquisôrsa]]'
	end
end

function References.zbl( zbl )
	return databaseDeDefor( zbl, '[[Zentralblatt MATH|zbMATH]]', 'zbmath.org/?q=an:' )
end


-- enLigne est destiné à remplacer "lire en ligne", "écouter en ligne", "présentation en ligne"
function References.enLegne( args, validArg )
	local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
	local lang, esp = '', ''
	if args.lengoua then
		local Lengoua = require( 'Module:Lengoua' )
		lang = Lengoua.endicacionMultilengoua{ args.lengoua, args.lengoua2, args.lengoua3 }
		esp = '&nbsp;'
	end
	
	local url = validArg( 'lim', 'url' )
	local urlSimplo = true
	
	if url then
		if url:match( '^https?://' ) or url:match( '^ftp://' ) or url:match( '^//' ) then
			url = url:gsub( '%[', '%%5B' ):gsub( '%]', '%%5D' ):gsub( ' ', '%%20' )
		else
			urlSimplo = false
		end
	elseif validArg( 'doi' ) then
		url = 'http://dx.doi.org/' .. mw.uri.encode( args.doi ) 
	else
		return
	end
	
	local lim
	if urlSimplo then
		local texto = validArg( 'tèxto' ) or 'en legne'
		lim = '[' .. url .. ' ' .. texto .. ']'
	else
		lim = url
	end
	
	local date = validArg( 'dâta', 'viu lo' )
	
	if date then 
		return lang .. esp .. lim .. '&nbsp;(viu lo' .. date .. ')'
	else
		return lang .. esp .. lim
	end
end

function References.afichajoLimsDeDefor( args, validArg, liereEnLegne, viuLo )
	local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
		
		local limsDeDefor = TableBuilder.new(  )
		
		-- isbn et issn
		limsDeDefor.minsert(
			References.isbn( args, validArg ),
			References.ean( args, validArg ),
			References.issn( args, validArg ),
			References.eissn( args, validArg ),
			References.ismn( args, validArg )
		)
		
		limsDeDefor.minsert( 
			References.oclc( args.oclc ),
			References.bnf ( args.bnf ),
			References.sbn ( args.sbn ),
			References.lccn( args.lccn ),
			References.dnb ( args.dnb ),
			References.pmid( validArg( 'pmid', 'PMID' ) ),
			References.pmcid ( validArg( 'pmcid', 'pmc'  ) ),
			References.doi( validArg( 'doi', 'DOI' ) ),
			References.jstor( args.jstor ),
			References.bibcode( args.bibcode ),
			References.mathreviews( validArg( 'math reviews', 'mr' ) ),
			References.zbl( validArg( 'zbl', 'zbmath' ) ),
			References.arxiv( args.arxiv ),
			References.hal( args.hal ),
			References.asin( args.asin ),
			References.sudoc( args.sudoc ),
			References.wikisource( args.wikisource )
		)
		
		limsDeDefor.minsert( 
			References.enLegne{ url = args['rèsumâ'], texto = 'rèsumâ' },
			References.enLegne{ url = args['presentacion en legne'], texto = 'presentacion en legne' },
			References.enLegne{ url = args['acutar en legne'], texto = 'acutar en legne' }
		)
		
		local url = validArg( 'liére en legne', 'url tèxto', 'url', 'tèxto' )
		if url and liereEnLegne then
			local archiveUrl = validArg( 'arch·ives-url', 'archiveurl' )
			if archiveUrl then
				if not ( string.match( archiveUrl, '^http' ) or string.match( archiveUrl, '^//' ) ) then
					archiveUrl = 'http://' .. archiveUrl
				end
				local textArchive = ' arch·ives'
				local dateArchive = validArg( 'arch·ives-dâta', 'archivedate' )
				if dateArchive then
					textArchive = ' arch·ives du ' .. Comon.enscripcionData{ date = dateArchive }
				end
				limsDeDefor.minsert( 
					'<span class="noarchive">'
					.. References.enLegne{	url = url,	texto = 'liére en legne' }
					..  '<small class="plainlinks cachelinks">[['
					.. archiveUrl .. textArchive
					.. ']]</small>'
					.. '</span>'
					.. ( References.endicacionDeFormat( args['format èlèctronico'] ) or '' )
				)
			else
				limsDeDefor.minsert( 
					References.enLegne{	url = url,	texto = 'liére en legne' }
					.. ( References.endicacionDeFormat( args['format èlèctronico'] ) or '' )
				)
			end
		end
		
		-- consulté le
		if viuLo then
			local consult = validArg( 'viu lo', 'accessdate', 'access-date', 'Viu lo', 'viu' )
			if consult then
				if string.sub( consult, -1,-1) == '.' then
					consult = string.sub( consult, 1, -2)
				end
				local viuLo = 'viu en '
				local Data = require( 'Module:Dâta' )
				local test, tdata = Data.separacionJornMesAn( consult )
				if test then
					if tdata.jorn then
						viuLo = 'viu lo '
                        if tdata.jorn == 1 then
                        	tdata.jorn = '<abbr class="abbr" title="premiér">1<sup>ér</sup></abbr>'
                        end
					end
					consult = TableBuilder.new()
						.minsert( tdata.jorn, tdata.mes, tdata.an )
						.concat( ' ' )
				end					
				limsDeDefor.minsert( viuLo .. '<span class="nowrap">' .. consult:lower() .. '</span>' )
			end
		end
		
		if #limsDeDefor > 0 then
			return ' <small style="line-height:1em;">(' .. limsDeDefor.concat( ', ' ) ..  ')</small>'
		end
end

function References.endicacionDeFormat( format )
	if not Outils.trim( format ) then 
		return
	end
	local listaFormat = {
		audio = { "ôdiô", "Fichiérs ôdiô u format MP3, Ogg..." },
		bat   = { "bat",   "Scripte de trètament per lot (batch)" },
		djvu  = { "DjVu",  "Document u format DjVu" },
		doc   = { "doc",   "Document Microsoft Word" },
		epub  = { "EPUB",  "Document u format Epub" },
		flash = { "flash", "Animacion vèctoriâla u format Macromedia Flash" },
		hlp   = { "hlp",   "Fichiér HeLP (éde) que dâte de Microsoft Windows 3.1" },
		html  = { "html",  "Fichiér u format Hypertext Markup Language (HTML)" },
		image = { "émâge", "Émâge u format JPEG, PNG, GIF..." },
		java  = { "java",  "Aplèt Java" },
		mov   = { "mov",   "Vidèô u format Apple QuickTime" },
		mp3   = { "MP3",   "Fichiér ôdiô u format MP3" },
		odt   = { "odt",   "Document u format OpenDocument" },
		ogg   = { "ogg",   "Fichiér u format contenior Ogg" },
		pdf   = { "PDF",   "Document u format Portable Document Format (PDF) d’Adobe" },
		php   = { "php",   "Scripte PHP" },
		pl    = { "pl",    "Scripte Practical Extraction and Report Language (Perl)" },
		ppt   = { "ppt",   "Presentacion Microsoft PowerPoint" },
		ps    = { "ps",    "Fichiér de dèscripcion vèctoriâla u format PostScript" },
		radio = { "radiô", "Radiô u format MPEG, AVI..." },
		rar   = { "rar",   "Document comprèssâ u format RAR" },
		rm    = { "rm",    "Vidèô u format RealMedia, RealAudio..." },
		rtf   = { "RTF",   "Document tèxto en Rich Text Format (RTF)" },
		svg   = { "SVG",   "Émâge vèctoriâla u format Scalable Vector Graphics (SVG)" },
		sxi   = { "sxi",   "Presentacion OpenOffice.org Impress" },
		sxw   = { "sxw",   "Document OpenOffice.org Writer" },
		tex   = { "TeX",   "Document TeX" },
		txt   = { "txt",   "Fichiér u format tèxto bruto" },
		video = { "vidèô", "Vidèô u format MPEG, AVI..." },
		xls   = { "xls",   "Cllassor Microsoft Excel" },
		xml   = { "XML",   "Document u format Extensible Markup Language (XML)" },
		zip   = { "zip",   "Arch·ives u format Zip" },
	}
	listaFormat['vidèô'] = listaFormat.video
	listaFormat.vid = listaFormat.video
	listaFormat.htm = listaFormat.html
	listaFormat.excel = listaFormat.xls
	listaFormat.powerpoint = listaFormat.ppt
	listaFormat.word = listaFormat.doc
	listaFormat.aud = listaFormat.audio
	
	local tabFormat = listaFormat[ string.lower( format ) ]
	if tabFormat then
		return (
			' <abbr class="abbr endiquior-format format-' .. tabFormat[1]:lower() .. '" '
			.. 'title="' .. tabFormat[2] .. '">'
			.. mw.text.nowiki( '[' .. tabFormat[1] .. ']' ) .. '</abbr>'
		)
	else
		-- teste si le suffixe est suivi d'une précision (ex : pdf 6 Mo)
		local ext, texto = string.match( format, "^(...) (.*)$")
		if ext and listaFormat[ string.lower( ext ) ] then
			return References.endicacionDeFormat( ext ) .. ' ' .. texto
		else
			return ' &#91;' .. format .. '&#93;'  -- '&#91;' = '<nowiki>[</nowiki>',  '&#93;' = '<nowiki>]</nowiki>',
		end
	end
	
end


return References