Différences entre les pages « Module:Biblio/Commun » et « Module:Biblio/Références »

De Les Mots de l'agronomie
< Module:Biblio(Différence entre les pages)
imported>Jacques Ducloy
m (1 révision importée)
 
imported>Jacques Ducloy
m (1 révision importée)
 
Ligne 1 : Ligne 1 :
-- Les fonctions du module Biblio/Commun sont des éléments nécessaire au modules Biblio/Ouvrage, Biblio/Article, Biblio/Lien web.
+
-- 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 Commun = {}
+
local References = { }
  
  
local Date = require( 'Module:Date' )
 
 
local Outils = require( 'Module:Outils' )
 
local Outils = require( 'Module:Outils' )
 +
local validTextArg = Outils.validTextArg
 
local TableBuilder = require( 'Module:TableBuilder' )
 
local TableBuilder = require( 'Module:TableBuilder' )
local Langue -- = require( 'Module:Langue' ) ne sera chargé que si nécessaire
+
-- local Date = require( 'Module:Date' ) -- chargé uniquement si nécessaire
local Languedata -- = mw.loadData( 'Module:Langue/Data' ) ne sera chargé que si nécessaire
 
  
local abr = Outils.abr      -- fonction abréviation discréte
 
  
-- extractArgs permet de récupérer les arguement du modèle,
+
--[[
-- ou la table transmise à la fonction par une autre fonction d'un module
+
ISBN-10 and ISSN validator code calculates checksum across all isbn/issn digits including the check digit. ISBN-13 is checked in checkisbn().
local extractArgs = Outils.extractArgs
+
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 Commun.validTextArg( args, name, ... )
+
function References.isValidIsmn10( ismn )
local texte = args[name]
+
local temp = 9
if type( texte ) == 'string' and texte ~= '' and texte:match( '%S' ) then
+
if ismn:match( 'M%d%d%d%d%d%d%d%d%d' ) then
return texte
+
for i = 2, 10 do
elseif #{ ... } > 0 then
+
temp = temp + ( 1 + 2 * ( i % 2 ) ) * ismn:sub( i, i )
return Commun.validTextArg( args, ... )
+
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
 
end
 +
return false
 
end
 
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 = 0
 +
ean_str = { ean_str:byte( 1, 13 ) }
 +
for i = 1, #ean_str do
 +
temp = temp + ( 3 - 2 * ( i % 2 ) ) * tonumber( string.char( ean_str[i] ) )
 +
end
 +
return temp % 10 == 0
 +
end
 +
end
 +
return false
 +
end
  
-- Abréviation utiles
+
function References.checkissn( issn_str )
Commun.chap =  abr{ 'chap.', 'chapitre(s)', nbsp='+' }
+
if type( issn_str ) == 'string' then
Commun.coll =   abr{ 'coll.', 'collection', nbsp='+' }
+
issn_str = issn_str:gsub( '[%s]', '' )
Commun.ed =     abr{ 'éd.', 'édition', nbsp='-' }
+
if issn_str:match( '^%d%d%d%d%-%d%d%d[%dxX]$' ) then
Commun.nbp =   abr{ 'p.', 'pages', nbsp='-' }
+
issn_str = issn_str:gsub( '-', '' ) -- supprime les traits d’union et espaces
Commun.numero = abr{ 'n<sup>o</sup>', 'numéro', nbsp='+' }
+
return References.is_valid_isxn( issn_str, 8 )
Commun.page =  abr{ 'p.', 'page(s)', nbsp='+' }
+
end
Commun.plume = '<span class=nowrap title="Ouvrage utilisé pour la rédaction de l\'article">\194\160[[Image:Nuvola apps ksig horizonta.png|30px|link=|alt=]]</span>'
+
end
Commun.premiere = abr{ '1<sup>re</sup>', 'première' }
+
return false
Commun.reimpr = abr{ 'réimpr.', 'réimpression', nbsp='+' }
+
end
Commun.tome = abr{ 't.', 'tome', nbsp='+' }
 
Commun.vol = abr{ 'vol.', 'volume', nbsp='+' }
 
  
 +
-- 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
  
function Commun.detailEdition( ref )
+
local function isbn13to9( isbn_str )
return '<small>&#91;[[' .. ref .. '|détail de l’édition]]&#93;</small>'
+
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
 
end
  
function Commun.detailEditions( ref )
+
local function isbn13to10( isbn_str )
return '<small>&#91;[[' .. ref .. '|détail des éditions]]&#93;</small>'
+
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
 
end
  
 
+
function References.isbn13to10( frame )
-- affiche le texte en nombre romain majuscule.
+
local args = Outils.extractArgs( frame )
function Commun.romain( texte )
+
return isbn13to10( args[1] )
    local a = '<span class="romain" style="text-transform:uppercase">'
 
    local b = '</span>'
 
    return a, texte, b
 
 
end
 
end
  
function Commun.fusionTexteLien( texte, lien, categ )
+
function References.same_isbn( isbn1, isbn2 )
local categorisation, result
+
if type( isbn1 ) ~= 'string' or type( isbn2 ) ~= 'string' then
local message = '<sup style="color:red;">[le lien externe a été retiré]</sup>'
+
return false
if lien and lien ~= '' then
 
if texte:match( '%[%[' ) then
 
result = Commun.fusionTexteLien( texte, nil, categ )
 
elseif lien:match( '^http' ) or lien:match( '//' ) then
 
lien = false
 
categorisation = true
 
result = texte .. message
 
else
 
result = string.format( '[[%s|%s]]', lien, texte )
 
end
 
else
 
--[=[ if texte:match( '//' ) then
 
result = texte:gsub( '%[https?://[^%[%] ]* *([^%]]+)%]', '%1' )
 
:gsub( '%[//[^%[%] ]* *([^%]]+)%]', '%1' )
 
if result ~= texte then
 
result = result .. message
 
categorisation = true
 
end
 
end ]=] -- désactivé pour le moment (peut être activé si quelqu'un est prêt à corriger les erreurs)
 
 
end
 
end
if categorisation and type( categ ) == 'table' then
+
-- remove dash and spaces
categ.lienExterne = true
+
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
 
end
return result or texte
+
-- compare isbn
 +
return isbn13to9( isbn1 ) == isbn13to9( isbn2 )
 
end
 
end
  
-- voir Modèle:Module biblio/span initial
+
local function doublonIsxn( isxn, liste2, xnCode)
function Commun.spanInitial( args, validArg )
+
if type( References[ 'same_' .. xnCode ] ) == 'function' then
local validArg = function ( ... ) return Commun.validTextArg( args, ... ) or false end
+
for k, v in ipairs( liste2 ) do
local id, id2 = validArg( 'id' )
+
if References[ 'same_' .. xnCode ]( isxn, v ) then
 
+
return true
if id then
 
id = ' id="' .. id .. '"'
 
else
 
local nom = validArg( 'nom1', 'nom', 'last1', 'last', 'author' )
 
local prenom = validArg( 'prénom1', 'prénom', 'firt1', 'first' )
 
local postnom = validArg('postnom1', 'postnom' )
 
local auteur_i = validArg( 'auteur1', 'author1', 'auteur' )
 
local i = 1
 
local idTab, id2Tab = { }, { }
 
 
 
while nom or auteur_i do
 
if auteur_i and not nom then
 
-- tentative de séparation de l'auteur en prénom nom.
 
-- Enregistre le résultat dans args pour les COinS.
 
auteur_i = Outils.texteLien( auteur_i )
 
if auteur_i == '' then
 
break
 
end
 
local a1, a2, a3 = string.match( auteur_i, '^([^ ]+) ?([^ ]*) ?(.*)$' )
 
if Outils.notEmpty( a3 ) then
 
local a2len = mw.ustring.len( a2 )
 
if a2len == 1 or ( a2len == 2 and mw.ustring.sub( a2, -1 ) == "." ) then
 
-- a1 est le prénom, a2 une initiale et a3 le nom
 
nom = a3
 
if i == 1 then
 
args.nom = a3
 
args['prénom'] = a1 .. ' ' .. a2
 
end
 
else
 
-- a2 peut être le deuxième prénon ou le début du nom
 
nom = a2 .. ' ' .. a3
 
end
 
elseif Outils.notEmpty( a2 ) then
 
-- a1 prénom, a2 nom
 
nom = a2
 
if i == 1 then
 
args.nom = a2
 
args['prénom'] = a1
 
end
 
else
 
nom = a1
 
end
 
end
 
if not auteur_i then
 
if prenom and postnom then
 
auteur_i = prenom .. ' ' .. nom .. ' ' .. postnom
 
elseif prenom then
 
auteur_i = prenom .. ' ' .. nom
 
elseif postnom then
 
auteur_i = nom .. ' ' .. postnom
 
else
 
auteur_i = nom
 
end
 
 
end
 
end
table.insert( idTab, mw.uri.anchorEncode( nom ) )
 
table.insert( id2Tab, mw.uri.anchorEncode( auteur_i ) )
 
 
if i == 4 then
 
break
 
end
 
i = i + 1
 
nom = validArg( 'nom' .. i, 'last' .. i )
 
prenom = validArg( 'prénom' .. i, 'first' .. i )
 
postnom = validArg( 'postnom' .. i)
 
auteur_i = validArg( 'auteur' .. i, 'author' .. i )
 
 
end
 
end
 +
end
 +
end
  
if #idTab < 4 and validArg( 'auteur institutionnel' ) then
+
local function formatIsxn( args, validArg, xnCode, invalideCateg, checkFunction, formatLien, page )
table.insert( idTab, mw.uri.anchorEncode( validArg( 'auteur institutionnel' ) ) )
+
local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
table.insert( id2Tab, idTab[#idTab] )
+
 +
local liste = { }
 +
local liste2 = { }
 +
local i = 1
 +
local avertissementInvalid = '<sup style="color:red">[à vérifier : ' .. invalideCateg .. ']</sup>'
 +
 +
local isxnErr = validArg( xnCode .. ' erroné' )
 +
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 lien = formatLien:format( isxnErrSanitised, isxnErr ) .. ' (édité erroné)'
 +
table.insert( liste, lien )
 
end
 
end
 
+
local annee = validArg( 'année', 'year', 'date' )
+
-- boucle sur les isxn2, 3...
if annee then
+
while isxn do
local t, d = Date.separationJourMoisAnnee( annee )
+
-- vérifivation de la validité de l'ISXN
if t and annee ~= d.annee then
+
local isxnValid = checkFunction( isxn )
annee = tostring( d.annee )
+
args['année'] = annee
+
-- préparation du texte à afficher
if d.mois then
+
if isxnValid then
args.mois = args.mois or tostring( d.mois )
+
local lien = formatLien:format( isxn, isxn )
 +
table.insert( liste, lien )
 +
if type( args.categ ) == 'table' and doublonIsxn( isxn, liste2, xnCode) then
 +
args.categ[ xnCode .. 'Dupliqué' ] = isxn
 
end
 
end
if d.jour then
+
table.insert( liste2, isxn )
args.jour = args.jour or tostring( d.jour )
+
else
 +
table.insert( liste, isxn .. avertissementInvalid )
 +
if type( args.categ ) == 'table' then
 +
args.categ[ xnCode .. 'Invalid' ] = true
 
end
 
end
elseif mw.ustring.find( annee, "%a" ) and annee:find( "%f[%d]%d%d%d%d%f[%D]" ) then
 
annee = annee:match( "%f[%d]%d%d%d%d%f[%D]" )
 
 
end
 
end
annee = mw.uri.anchorEncode( tostring( annee ) )
+
table.insert( idTab, annee )
+
i = i + 1
table.insert( id2Tab, annee )
+
isxn = validArg( xnCode .. i, XN .. i )
 
end
 
end
 
+
if #idTab > 0 then
+
if args['sansLabel'] then
id = ' id="' .. table.concat( idTab ) .. '"'
+
page = ''
id2 = ' id="' .. table.concat( id2Tab ) .. '"'
 
if id2 == id then
 
id2 = false
 
end
 
 
else
 
else
id = ''
+
page = page .. '&nbsp;'
 
end
 
end
 +
return page .. mw.text.listToText( liste )
 
end
 
end
 +
end
  
local spaninitial, spanfinal
+
-- voir Modèle:ISBN
if id2 then
+
-- renvoie une liste de chaines formant le résultat du modèle une fois concaténées
spaninitial = '<span class="ouvrage"' .. id .. '><span class="ouvrage"' .. id2 .. '>'
+
function References.isbn( args, validArg )
spanfinal = '</span></span>'
+
return formatIsxn(
else
+
args,
spaninitial = '<span class="ouvrage"' .. id .. '>'
+
validArg,
spanfinal = '</span>'
+
'isbn',
end
+
'[[:Catégorie:Page avec ISBN invalide|ISBN invalide]]',
return spaninitial, spanfinal
+
References.checkisbn,
 +
'[[Spécial:Ouvrages de référence/%s|<span class="nowrap">%s</span>]]',
 +
'[[International Standard Book Number|ISBN]]'
 +
)
 
end
 
end
  
-- voir Modèle:Module biblio/libellé
+
-- voir Modèle:EAN
function Commun.libelle( args )
+
-- renvoie une liste de chaines formant le résultat du modèle une fois concaténées
local lib = args['libellé'] or ''
+
function References.ean( args, validArg )
if lib ~= '' then
+
return formatIsxn(
lib = '<small>[' .. lib .. ']</small> '
+
args,
end
+
validArg,
return lib
+
'ean',
 +
'[[:Catégorie:Page avec EAN invalide|EAN invalide]]',
 +
References.checkean13,
 +
'[[Spécial:Ouvrages de référence/%s|<span class="nowrap">%s</span>]]',
 +
'[[EAN 13|EAN]]'
 +
)
 
end
 
end
  
-- voir Modèle:Commentaire biblio
+
-- voir Modèle:ISSN
function Commun.commentaire( args )
+
-- renvoie une liste de chaines formant le résultat du modèle une fois concaténées
if Outils.trim( args.commentaire ) then
+
function References.issn( args, validArg )
local a = '<div style="Margin-top:0.1em ;margin-left:2em; line-height:1.5; margin-bottom:0.5em;">'
+
return formatIsxn(
local b = '</div>'
+
args,
return a, args.commentaire, b
+
validArg,
end
+
'issn',
return ''
+
'[[:Catégorie:Page avec ISSN invalide|ISSN invalide]]',
 +
References.checkissn,
 +
'<span class="plainlinks noarchive">[http://worldcat.org/issn/%s&lang=fr %s]</span>',
 +
'[[International Standard Serial Number|ISSN]]'
 +
)
 
end
 
end
  
-- voir Modèle:Module biblio/indication de langue
+
function References.eissn( args, validArg )
function Commun.indicationDeLangue( args, validArg )
+
return formatIsxn(
local lang = validArg( 'langue', 'lang', 'lien langue', 'language' )
+
args,
if lang then
+
validArg,
Langue = require( 'Module:Langue' )
+
'e-issn',
 +
'[[:Catégorie:Page avec ISSN invalide|ISSN invalide]]',
 +
References.checkissn,
 +
'<span class="plainlinks noarchive">[http://worldcat.org/issn/%s&lang=fr %s]</span>',
 +
'[[International Standard Serial Number#ISSN électronique|e-ISSN]]'
 +
)
 +
end
  
-- on essaie le code de langue complet (nécessaire pour les langues avec plusieurs mot comme "grec ancien")
+
-- voir Modèle:ISMN
local codeLangue = Langue.codeLangue2( lang )
+
-- 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:Page avec ISMN invalide|ISMN invalide]]',
 +
References.checkismn,
 +
'<span class="nowrap">%s</span>',
 +
'[[International Standard Music Number|ISMN]]'
 +
)
 +
end
  
if codeLangue == 'fr' or codeLangue:sub(1, 3) == 'fr-' then
+
-- fonctions liant des bases de données externes
return ''
+
local function databaseExterne( num, lienIinterne, lienExterne, complement, texteAffiche )
elseif codeLangue ~= '' then
+
if Outils.notEmpty( num ) then
return Langue.indicationMultilingue{ codeLangue }, codeLangue
+
local adresse =  
end
+
lienIinterne
 
+
.. '&nbsp;<span class="plainlinks noarchive nowrap">[http://'
-- si la langue n'a pas été trouvée on considère qu'il y a plusieurs langues
+
.. lienExterne
-- séparation des langues s'il y en a plusieurs
+
.. mw.uri.encode( num, 'PATH' )
local listeLangue = mw.text.split( lang, '[+,;:/ %.]+' )
+
.. ( complement or ' ' )  
 
+
.. mw.text.nowiki( texteAffiche or num )
-- code langue principal qui sera appliqué aux titres
+
.. ']</span>'
codeLangue = Langue.codeLangue2( listeLangue[1] )
+
 
+
return adresse
if codeLangue == '' then
+
end
if type( args.categ ) == 'table' then
+
end
args.categ.langue = true
 
end
 
return Langue.indicationMultilingue( listeLangue )
 
else
 
-- calcul code de langue et catégorie
 
local indicationLangue = Langue.indicationMultilingue( listeLangue )
 
if type( args.categ ) == 'table' then
 
args.categ.langue = indicationLangue:find( '???', 1, true )
 
end
 
  
if codeLangue ~= 'fr' and codeLangue:sub(1, 3) ~= 'fr-' then
+
function References.arkId( base )
return indicationLangue, codeLangue
+
--  Nice Opaque Identifiern utilisé par les formats Ark pour générer une clé
elseif #listeLangue > 1 then
+
base = tostring( base )
return indicationLangue, codeLangue
+
if base then
end
+
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
 
end
 +
local index = sum % 29 + 1
 +
return xdigits:sub( index, index )
 
end
 
end
return ''
 
 
end
 
end
  
 
+
function References.arxiv( arxiv )
-- voir Modèle:Module biblio/responsabilité principale
+
if Outils.trim( arxiv ) then
function Commun.responsabilitePrincipale( args, validArg )
+
return databaseExterne( arxiv, '[[arXiv]]', 'arxiv.org/abs/' ):gsub( '%%2F', '/' )
 
 
local nom = validArg( 'nom1', 'nom', 'last1', 'last' )
 
local auteur = validArg( 'auteur1', 'auteur', 'author1', 'author' )
 
local auteurInstitutionnel = validArg( 'auteur institutionnel' )
 
if not ( nom or auteur or auteurInstitutionnel ) then
 
return ''
 
 
end
 
end
 +
end
  
if nom or auteur then
+
function References.asin( asin )
-- clarification des paramètres
+
return databaseExterne( asin, '[[Amazon Standard Identification Number|ASIN]]', 'www.amazon.fr/s/?url=search-alias&lang=fr&field-keywords=' )
args['prénom1'] = validArg( 'prénom1', 'prénom', 'first1', 'first' )
+
end
args['postnom1'] = validArg( 'postnom1', 'postnom' )
 
  
args.directeur1 = validArg( 'directeur1', 'directeur' )
+
function References.bibcode( bibcode )
args['lien auteur1'] = validArg( 'lien auteur1', 'lien auteur', 'author-link' )
+
return databaseExterne( bibcode, '[[Bibcode]]', 'adsabs.harvard.edu/abs/' )
end
+
end
 
 
-- préparation des variables
 
local listeRresponsables = { }  -- contiendra un élément pour chaque nom
 
local directeur = abr { 'dir.', 'directeur de publication' }
 
local prenom, postnom, dir, responsable, lien, precision, resp
 
local i = 1
 
 
 
 
 
-- boucle sur chaque nom, assemble toutes les caractéristique et ajoute l'ensemble à la liste.
 
while nom or auteur do
 
 
 
-- nom de l'auteur
 
if not auteur then
 
prenom = validArg( 'prénom' .. i, 'first' .. i )
 
nom = '<span class="nom_auteur">' .. nom .. '</span>'
 
postnom = validArg( 'postnom' .. i)
 
if prenom and postnom then
 
auteur = prenom .. ' ' .. nom .. ' ' .. postnom
 
elseif prenom then
 
auteur = prenom .. ' ' .. nom
 
elseif postnom then
 
auteur = nom .. ' ' .. postnom
 
else
 
auteur = nom
 
end
 
end
 
  
-- lien sur l'auteur
+
function References.bnf( bnf )
auteur = Commun.fusionTexteLien( auteur, args['lien auteur' .. i], args.categ)
+
bnf = Outils.trim( bnf )
 
+
if bnf then
-- définition des responsabilités
+
local texte = bnf
dir = validArg( 'directeur' .. i )
+
local category = ''
resp = validArg( 'responsabilité' .. i )
+
local bnfId = bnf:upper():match( 'BNF(%d+%w)' ) or bnf:lower():match( 'cb(%d+%w)' ) or bnf:match( '^%d+%w' )
if dir then
+
if resp then
+
if bnfId then
precision = ' (' .. directeur .. ' et ' .. resp .. ')'
+
-- bnf contient une suite de chiffres qui peut être un ark valide
 +
local base = bnfId:sub( 1, 8 )
 +
if bnfId:len() == 8 then  
 +
-- il manque la clé, on l'ajoute
 +
bnf = base .. References.arkId( 'cb' .. base )
 +
texte = base
 +
elseif bnfId:len() > 8 and bnfId:sub( 9, 9 ) == References.arkId( 'cb' .. base ) then
 +
-- ark valide
 +
bnf = bnfId:sub( 1, 9 )
 +
texte = base
 
else
 
else
precision = ' (' .. directeur .. ')'
+
-- ark qui semble non valide
 +
bnf = bnfId
 +
texte = bnfId
 +
category = '[[Catégorie:Recension temporaire pour le modèle Ouvrage|bnf]]'
 
end
 
end
elseif resp then
 
precision = ' (' .. resp .. ')'
 
 
else
 
else
precision = ''
+
-- le paramètre ne semble pas un ark valide
 +
category = '[[Catégorie:Recension temporaire pour le modèle Ouvrage|bnf]]'
 
end
 
end
 +
 +
-- dans tous les cas on renvoie l'adresse, on catégorise juste pour vérifier ce qui ne va pas
 +
local lien = databaseExterne( bnf,
 +
'notice [[Bibliothèque nationale de France|BnF]] n<sup>o</sup>',
 +
'catalogue.bnf.fr/ark:/12148/cb',
 +
'/PUBLIC FRBNF',
 +
texte
 +
)
 +
 +
return lien .. category
 +
end
 +
end
  
table.insert( listeRresponsables, auteur .. precision )
+
function References.dnb( dnb )
 +
return databaseExterne( dnb, '[[Bibliothèque nationale allemande|DNB]]', 'd-nb.info/' )
 +
end
  
i = i + 1
+
function References.doi( doi )
nom = validArg( 'nom' .. i, 'last' .. i )
+
return databaseExterne( doi, '[[Digital Object Identifier|DOI]]', 'dx.doi.org/' )
auteur = validArg( 'auteur' .. i, 'author' .. i )
+
end
end
 
  
local listeAuteurs
+
function References.jstor( jstor )
local et_al = ''
+
return databaseExterne( jstor, '[[JSTOR]]', 'jstor.org/stable/' )
if validArg( 'et al.', 'et alii' ) then
+
end
et_al = " ''" .. abr { "et al.", "et alii (et d’autres)" } .. "''"
 
listeAuteurs = table.concat( listeRresponsables, ', ' ) .. et_al
 
else
 
listeAuteurs = mw.text.listToText( listeRresponsables )
 
end
 
  
if auteurInstitutionnel then
+
function References.lccn( lccn )
if #listeRresponsables > 0 then
+
return databaseExterne( lccn, '[[Numéro de contrôle de la Bibliothèque du Congrès|LCCN]]', 'lccn.loc.gov/' )
return listeAuteurs .. ', ' .. auteurInstitutionnel
+
end
else
 
return auteurInstitutionnel .. et_al
 
end
 
else
 
return listeAuteurs
 
end
 
  
 +
function References.mathreviews( mathreviews )
 +
return databaseExterne( mathreviews, '[[Mathematical Reviews|Math Reviews]]', 'www.ams.org/mathscinet-getitem?mr=' )
 
end
 
end
  
 +
function References.oclc( oclc )
 +
return databaseExterne( oclc, '[[Online Computer Library Center|OCLC]]', 'worldcat.org/oclc/', '&lang=fr ' )
 +
end
  
-- voir Module biblio/responsabilité secondaire
+
function References.pmcid( pmcid )
function Commun.responsabiliteSecondaire( args, validArg )
+
return databaseExterne( pmcid, '[[PubMed Central|PMCID]]', 'www.ncbi.nlm.nih.gov/pmc/articles/' )
local liste = { }
+
end
  
-- fonction qui teste l'existence d'un paramètre et insérere  dans liste une abréviation discrète suivi de ce paramètre
+
function References.pmid( pmid )
local function insertAbr( arg, abrev, texte )
+
return databaseExterne( pmid, '[[PubMed|PMID]]', 'www.ncbi.nlm.nih.gov/pubmed/' )
if arg then
+
end
table.insert( liste, abr{ abrev, texte, nbsp='+' } .. arg )
 
end
 
end
 
  
-- langue originale et traducteur
+
function References.sbn( sbn )
local trad = validArg( 'traducteur', 'trad', 'traduction' )
+
local id = ( sbn or '' ):upper():gsub( '\\', '' ):gsub( '^ITICCU', '' )
local langueOriginale = validArg( 'langue originale' )
+
return databaseExterne( id, '[[Service bibliothécaire national]]', 'opac.sbn.it/bid/' )
if langueOriginale then
+
end
local Languedata = mw.loadData( 'Module:Langue/Data' )
 
langueOriginale = Languedata[langueOriginale] and Languedata[langueOriginale].nom
 
end
 
if langueOriginale then
 
if trad then
 
trad = ' par ' .. trad
 
else
 
trad = ''
 
end
 
if mw.ustring.sub( langueOriginale, 1, 1 ):match( '[a, e, é, è, i, o, u, y]' ) or
 
langueOriginale == 'hébreu' then
 
trad = "de l'" .. langueOriginale .. trad
 
else
 
trad = 'du ' .. langueOriginale .. trad
 
end
 
end
 
insertAbr( trad, 'trad.', 'traduction' )
 
  
-- ajout des différents responsables
+
function References.sudoc( sudoc )
insertAbr( validArg( 'préface' ), 'préf.', 'préface' )
+
return databaseExterne( sudoc, '[[Système universitaire de documentation|SUDOC]]', 'www.sudoc.fr/' )
if validArg( 'postface' ) then
 
table.insert( liste, 'postface ' .. args.postface )
 
end
 
insertAbr( validArg( 'illustrateur' ), 'ill.', 'illustrations' )
 
insertAbr( validArg( 'photographe' ), 'photogr.', 'photographies' )
 
if validArg( 'champ libre' ) then
 
table.insert( liste, args['champ libre'] )
 
end
 
 
 
-- concaténation de l'ensemble
 
local texte = table.concat( liste, ', ')
 
if texte ~= '' then
 
return ' (' .. texte .. ')'
 
end
 
 
end
 
end
  
---
+
function References.wikisource( wikisource )
-- voir émule le modèle:Inscription date
+
if Outils.notEmpty( wikisource ) then
-- la détection des arguments permet d'utilisé la fonction depuis un modèle, depuis invoke, ou depuis une autre fonction.
+
return '[[s:' .. wikisource .. '|lire sur Wikisource]]'
-- pour facilité l'écriture de lua, annee (sans accent) est accepté lors de l'appel depuis lua.
 
function Commun.inscriptionDate( frame )
 
local args = Outils.extractArgs( frame )
 
local annee = Outils.notEmpty( args['année'], args.annee, args.year )
 
if annee then
 
if annee:match( '^%-?%d+$' ) then
 
-- si l'année est correctement renseigné, on essaye de trouver le mois
 
local mois = Outils.notEmpty( args.mois, args.month, args.saison )
 
mois = string.lower(Date.determinationMois( mois ) or Date.valideSaison( mois ) or mois or '')
 
local jour = Outils.notEmpty( args.jour, args.day, args['quantième'] )
 
local t, jma = Date.validationJourMoisAnnee( jour, mois, annee )
 
if t then
 
return Date.modeleDate{ jour, mois, annee, nolinks=true }
 
else
 
local date = { jour }
 
table.insert( date, mois )
 
table.insert( date, annee )
 
return '<time class="nowrap" datevalue="' .. annee .. '">' .. table.concat( date, ' ' ) .. '</time>'
 
end
 
else
 
return Commun.inscriptionDate{ date = annee }
 
end
 
else
 
-- si annee n'est pas précisé, on utilise la paramètre date
 
local date = Outils.validTextArg( args, 'date' )
 
if date then
 
date = date:lower()
 
date = date:gsub( '^(%d%d%d%d%-%d%d%-%d%d)t[%d:+-]+$', '%1') -- Date iso avec l'heure : suppression de l'heure
 
local t, jma = Date.separationJourMoisAnnee( date )
 
if t and ( Date.determinationMois( jma.mois ) or Date.valideSaison( jma.mois ) ) then
 
args['année'] = jma.annee
 
jma.nolinks = true
 
jma.nocat = true
 
return Date.modeleDate( jma )
 
else
 
-- date non reconnue, on essaye Month day, year
 
local mois, jour, annee = mw.ustring.match( date, '^([%a]+)%s*(%d%d?)[,%s]+(%d+)$' )
 
if Date.determinationMois( mois ) or Date.valideSaison( mois ) then
 
return Date.modeleDate{ jour, mois, annee, nolinks=true }
 
end
 
end
 
return date
 
end
 
 
end
 
end
return ''
 
 
end
 
end
  
-- retire toutes le lien interne, externe et balise html pour ne garder que le texte brut.
+
function References.zbl( zbl )
local function nettoyageTexte( texte )
+
return databaseExterne( zbl, '[[Zentralblatt MATH|zbMATH]]', 'zbmath.org/?q=an:' )
if type( texte ) == 'string'  then
 
if texte:match( '[%[<]' ) then
 
local function texteDuLien( l, t )
 
return ( t ~= '' and t ) or l
 
end
 
-- nettoyage des liens interne
 
texte = texte:gsub( '%[%[([^%[%]|]*)|?([^%[%]]*)%]%]', texteDuLien )
 
-- nettoyage des liens externes
 
:gsub( '%[https?://[^%[%] ]* *([^%]]+)%]', '%1' )
 
:gsub( '%[//[^%[%] ]* *([^%]]+)%]', '%1' )
 
-- nettoyage des balise html
 
:gsub( '%b<>', '' )
 
end
 
return texte
 
end
 
 
end
 
end
  
-- voir Modèle:COinS bibliographique
 
-- NISO Z39.88
 
-- http://www.openurl.info/registry
 
function Commun.COinS( args, validArg, genre )
 
local liste = { }
 
  
-- insertlist ajoute à la table 'liste' un couple 'nom Coins normalisé' - 'donnée'
+
-- enLigne est destiné à remplacer "lire en ligne", "écouter en ligne", "présentation en ligne"
-- Si istexte = true, le deuxième élément de tab est considéré comme du texte,
+
function References.enLigne( args, validArg )
-- sinon comme le nom d'un paramètre.
+
local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
local function insertList( key, value, prefix )
+
local lang, esp = '', ''
prefix = prefix or ''
+
if args.langue then
if type( value ) == 'string' and value ~= '' then
+
local Langue = require( 'Module:Langue' )
table.insert( liste, key .. '=' .. mw.uri.encode( prefix .. value ) )
+
lang = Langue.indicationMultilingue{ args.langue, args.langue2, args.langue3 }
end
+
esp = '&nbsp'
 
end
 
end
 
+
-- norme du COinS
+
local url = validArg( 'lien', 'url' )
insertList( 'ctx_ver', 'Z39.88-2004' )
+
if url == nil then  
 
+
if validArg( 'doi' ) then
-- genre, titre et sous-titre
+
url = 'http://dx.doi.org/' .. mw.uri.encode( args.doi )  
if genre == 'article' then
 
insertList( 'rft_val_fmt', 'info:ofi/fmt:kev:mtx:journal' )
 
insertList( 'rft.genre', 'article' )
 
insertList( 'rft.atitle', nettoyageTexte( args.titre ) )
 
insertList( 'rft.jtitle', nettoyageTexte( validArg( 'périodique', 'revue', 'journal' ) ) )
 
insertList( 'rft.issue', validArg( 'numéro', 'no', 'issue' ) )
 
else
 
-- genre = ouvrage ou chaitre
 
insertList( 'rft_val_fmt','info:ofi/fmt:kev:mtx:book' )
 
if genre == 'chapitre' then
 
insertList( 'rft.genre', 'bookitem' )
 
 
else
 
else
insertList( 'rft.genre', 'book' )
+
return
 
end
 
end
insertList( 'rft.btitle', nettoyageTexte( args.titre ) )
 
insertList( 'rft.atitle', nettoyageTexte( validArg( 'titre chapitre', 'titreChap' ) ) )
 
 
-- donnée sur l'éditeur
 
insertList( 'rft.place', Outils.texteLien( validArg( 'lieu', 'location' ) ), nil )
 
insertList( 'rft.pub', Outils.texteLien( validArg( 'éditeur', 'édition' ) ), nil )
 
insertList( 'rft.edition', args["numéro d'édition"] )
 
 
end
 
end
insertList( 'rft.stitle', args['sous-titre'] )
+
url = url:gsub( '%[', '%%5B' ):gsub( '%]', '%%5D' ):gsub( ' ', '%%20' )
 
+
-- Premier auteur, séparé en noms et prénoms
+
local texte = validArg( 'texte' ) or 'en ligne'
local nom = Outils.texteLien( validArg( 'nom1', 'nom', 'last1', 'last' ) )
+
local date = validArg( 'date', 'consulté le' )
if nom then
+
insertList( 'rft.aulast', nom )
+
if date then
insertList( 'rft.aufirst', validArg( 'prénom1', 'prénom', 'first1', 'first' ) )
+
return lang .. esp .. '[' .. url .. ' ' .. texte .. ']&nbsp;(consultée le' .. date .. ')'
insertList( 'rtf.ausuffix ', validArg( 'postnom1', 'postnom' ) )
 
 
else
 
else
local auteur = Outils.texteLien( validArg( 'auteur', 'auteur1' ) )
+
return lang .. esp .. '[' .. url .. ' ' .. texte .. ']'
if auteur then
 
insertList( 'rft.au', auteur )
 
end
 
 
end
 
end
 +
end
  
-- les autres auteurs, la norme ne prévoit pas de séparation
+
function References.affichageLiensExternes( args, validArg, lireEnLigne, consulteLe )
for i = 2, 20 do
+
local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
local nom_i = Outils.texteLien( validArg( 'nom' .. i ) )
+
if nom_i then
+
local liensExternes = TableBuilder.new(  )
local prenom_i = validArg( 'prénom' .. i )
+
local postnom_i = validArg( 'postnom' .. i)
+
-- isbn et issn
if prenom_i and postnom_i then
+
liensExternes.minsert(
insertList( 'rft.au', nom_i .. ' ' .. postnom_i .. ', ' .. prenom_i )
+
References.isbn( args, validArg ),
elseif prenom_i then
+
References.ean( args, validArg ),
insertList( 'rft.au', nom_i .. ', ' .. prenom_i )
+
References.issn( args, validArg ),
elseif postnom_i then
+
References.eissn( args, validArg ),
insertList( 'rft.au', nom_i .. ' ' .. postnom_i )
+
References.ismn( args, validArg )
else
+
)
insertList( 'rft.au', nom_i )
+
end
+
liensExternes.minsert(
else
+
References.oclc( args.oclc ),
local auteur_i = Outils.texteLien( validArg( 'auteur' .. i ) )
+
References.bnf ( args.bnf ),
if auteur_i then
+
References.sbn ( args.sbn ),
insertList( 'rft.au', auteur_i )
+
References.lccn( args.lccn ),
else
+
References.dnb ( args.dnb ),
break
+
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( args['math reviews'] ),
 +
References.zbl( validArg( 'zbl', 'zbmath' ) ),
 +
References.arxiv( args.arxiv ),
 +
References.asin( args.asin ),
 +
References.sudoc( args.sudoc ),
 +
References.wikisource( args.wikisource )
 +
)
 +
 +
liensExternes.minsert(
 +
References.enLigne{ url = args['résumé'], texte = 'résumé' },
 +
References.enLigne{ url = args['présentation en ligne'], texte = 'présentation en ligne' },
 +
References.enLigne{ url = args['écouter en ligne'], texte = 'écouter en ligne' }
 +
)
 +
 +
local url = validArg( 'lire en ligne', 'url texte', 'url', 'texte' )
 +
if url and lireEnLigne then
 +
liensExternes.minsert(
 +
References.enLigne{
 +
lien = url,
 +
texte = 'lire en ligne',
 +
} .. ( References.indicationDeFormat( args['format électronique'] ) or '' )
 +
)
 +
end
 +
 +
-- consulté le
 +
if consulteLe then
 +
local consult = validArg( 'consulté le', 'accessdate', 'Consulté le', 'consulté', 'consultée le' )
 +
if consult then
 +
if string.sub( consult, -1,-1) == '.' then
 +
consult = string.sub( consult, 1, -2)
 +
end
 +
local consulteLe = 'consulté en '
 +
local Date = require( 'Module:Date' )
 +
local test, tdate = Date.separationJourMoisAnnee( consult )
 +
if test then
 +
if tdate.jour then
 +
consulteLe = 'consulté le '
 +
                        if tdate.jour == 1 then
 +
                        tdate.jour = Outils.abr( '1<sup>er</sup>', 'premier' )
 +
                        end
 +
end
 +
consult = TableBuilder.new()
 +
.minsert( tdate.jour, tdate.mois, tdate.annee )
 +
.concat( ' ' )
 +
end
 +
liensExternes.minsert( consulteLe .. Outils.nobr( consult:lower() ) )
 
end
 
end
 
end
 
end
end
+
 +
if #liensExternes > 0 then
 +
return ' <small style="line-height:1em;">(' .. liensExternes.concat( ', ' ) ..  ')</small>'
 +
end
 +
end
  
if validArg( 'auteur institutionnel' ) then
+
function References.indicationDeFormat( format )
insertList( 'rft.aucorp', args['auteur institutionnel'] )
+
if not Outils.trim( format ) then  
 +
return
 
end
 
end
 
+
local listeFormat = {
-- date
+
audio = { "audio", "Fichiers audio au format MP3, Ogg..." },
local datePub = Date.dateISO( args )
+
bat  = { "bat",  "Script de traitement par lot (batch)" },
if datePub then
+
djvu  = { "DjVu",  "Document au format DjVu" },
insertList( 'rft.date', datePub )
+
doc  = { "doc",  "Document Microsoft Word" },
 +
epub  = { "EPUB",  "Document au format Epub" },
 +
flash = { "flash", "Animation vectorielle au format Macromedia Flash" },
 +
hlp  = { "hlp",  "Fichier HeLP (aide) datant de Microsoft Windows 3.1" },
 +
html  = { "html",  "Fichier au format Hypertext Markup Language (HTML)" },
 +
image = { "image", "Image au format JPEG, PNG, GIF..." },
 +
java  = { "java",  "Applet Java" },
 +
mov  = { "mov",  "Vidéo au format Apple QuickTime" },
 +
mp3  = { "MP3",  "Fichier audio au format MP3" },
 +
odt  = { "odt",  "Document au format OpenDocument" },
 +
ogg  = { "ogg",  "Fichier au format conteneur Ogg" },
 +
pdf  = { "PDF",  "Document au format Portable Document Format (PDF) d'Adobe" },
 +
php  = { "php",  "Script PHP" },
 +
pl    = { "pl",    "Script Practical Extraction and Report Language (Perl)" },
 +
ppt  = { "ppt",  "Présentation Microsoft PowerPoint" },
 +
ps    = { "ps",    "Fichier de description vectorielle au format PostScript" },
 +
radio = { "radio", "Radio au format MPEG, AVI..." },
 +
rar  = { "rar",  "Document compressé au format RAR" },
 +
rm    = { "rm",    "Vidéo au format RealMedia, RealAudio..." },
 +
rtf  = { "RTF",  "Document texte en Rich Text Format (RTF)" },
 +
svg  = { "SVG",  "Image vectorielle au format Scalable Vector Graphics (SVG)" },
 +
sxi  = { "sxi",  "Présentation OpenOffice.org Impress" },
 +
sxw  = { "sxw",  "Document OpenOffice.org Writer" },
 +
tex  = { "TeX",  "Document TeX" },
 +
txt  = { "txt",  "Fichier au format texte brut" },
 +
video = { "vidéo", "Vidéo au format MPEG, AVI..." },
 +
xls  = { "xls",  "Classeur Microsoft Excel" },
 +
xml  = { "XML",  "Document au format Extensible Markup Language (XML)" },
 +
zip  = { "zip",  "Archive au format Zip" },
 +
}
 +
listeFormat['vidéo'] = listeFormat.video
 +
listeFormat.vid = listeFormat.video
 +
listeFormat.htm = listeFormat.html
 +
listeFormat.excel = listeFormat.xls
 +
listeFormat.powerpoint = listeFormat.ppt
 +
listeFormat.word = listeFormat.doc
 +
listeFormat.aud = listeFormat.audio
 +
 +
local tabFormat = listeFormat[ string.lower( format ) ]
 +
if tabFormat then
 +
return ( ' <abbr class="abbr indicateur-format format-' .. string.lower(tabFormat[1]) .. '" title="' .. tabFormat[2]
 +
.. '">' .. mw.text.nowiki( '[' .. tabFormat[1] .. ']' ) .. '</abbr>' )
 
else
 
else
insertList( 'rft.date', args.date )
+
-- teste si le suffixe est suivi d'une précision (ex : pdf 6 Mo)
 +
local ext, texte = string.match( format, "^(...) (.*)$")
 +
if ext and listeFormat[ string.lower( ext ) ] then
 +
return References.indicationDeFormat( ext ) .. ' ' .. texte
 +
else
 +
return ' ' .. '&#91;' .. format .. '&#93;'  -- '&#91;' = '<nowiki>[</nowiki>', '&#93;' = '<nowiki>]</nowiki>',
 +
end
 
end
 
end
 
+
-- doonées physique de la publication
 
insertList( 'rft.volume', validArg( 'volume', 'vol' ) )
 
insertList( 'rft.pages', validArg( 'passage', 'page' ) )
 
insertList( 'rft.spage', args['page début chapitre'] )
 
insertList( 'rft.tpages', args['pages totales'] )
 
 
 
 
 
-- références internationales
 
insertList( 'rft.isbn', args.isbn )
 
insertList( 'rft.issn', args.issn )
 
insertList( 'rft_id', args.doi, 'info:doi/' )
 
insertList( 'rft_id', args.pmid, 'info:pmid/' )
 
insertList( 'rft_id', args.oclc, 'info:oclcnum/' )
 
insertList( 'rft_id', args.url )
 
 
 
-- referer : page Wikipedia ou se trouve cette référence
 
insertList( 'rfr_id', 'fr.wikipedia.org:' .. mw.title.getCurrentTitle().fullText, 'info:sid/' )
 
 
 
local contextObject = table.concat( liste, '&' )
 
 
 
-- calcul d'un id pour que le span vide ne soit pas supprimé par tydy ( cf. https://bugzilla.wikimedia.org/show_bug.cgi?id=27786 )
 
local id=0
 
for i = 1, #contextObject do
 
id = id + string.byte( contextObject, i )
 
end
 
 
 
return '<span class="Z3988" title="' .. contextObject .. '" id="COinS_' .. id ..'"></span>'
 
 
end
 
end
  
  
return Commun
+
return References

Version actuelle datée du 28 décembre 2020 à 10:53

La documentation pour ce module peut être créée à Module:Biblio/Références/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 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 = 0
			ean_str = { ean_str:byte( 1, 13 ) }
			for i = 1, #ean_str do
				temp = temp + ( 3 - 2 * ( i % 2 ) ) * tonumber( string.char( ean_str[i] ) )
			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 doublonIsxn( isxn, liste2, xnCode)
	if type( References[ 'same_' .. xnCode ] ) == 'function' then
		for k, v in ipairs( liste2 ) do
			if References[ 'same_' .. xnCode ]( isxn, v ) then
				return true
			end
		end
	end
end

local function formatIsxn( args, validArg, xnCode, invalideCateg, checkFunction, formatLien, page )
	local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
	
	local liste = { }
	local liste2 = { }
	local i = 1
	local avertissementInvalid = '<sup style="color:red">[à vérifier : ' .. invalideCateg .. ']</sup>'
	
	local isxnErr = validArg( xnCode .. ' erroné' )
	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 lien = formatLien:format( isxnErrSanitised, isxnErr ) .. ' (édité erroné)'
			table.insert( liste, lien )
		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 lien = formatLien:format( isxn, isxn )
				table.insert( liste, lien )
				if type( args.categ ) == 'table' and doublonIsxn( isxn, liste2, xnCode) then
					args.categ[ xnCode .. 'Dupliqué' ] = isxn
				end
				table.insert( liste2, isxn )
			else
				table.insert( liste, isxn .. avertissementInvalid )
				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['sansLabel'] then 
			page = ''
		else
			page = page .. '&nbsp;'
		end
		return page .. mw.text.listToText( liste )
	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:Page avec ISBN invalide|ISBN invalide]]',
		References.checkisbn,
		'[[Spécial:Ouvrages de référence/%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:Page avec EAN invalide|EAN invalide]]',
		References.checkean13,
		'[[Spécial:Ouvrages de référence/%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:Page avec ISSN invalide|ISSN invalide]]',
		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:Page avec ISSN invalide|ISSN invalide]]',
		References.checkissn,
		'<span class="plainlinks noarchive">[http://worldcat.org/issn/%s&lang=fr %s]</span>',
		'[[International Standard Serial Number#ISSN électronique|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:Page avec ISMN invalide|ISMN invalide]]',
		References.checkismn,
		'<span class="nowrap">%s</span>',
		'[[International Standard Music Number|ISMN]]'
	)
end

-- fonctions liant des bases de données externes
local function databaseExterne( num, lienIinterne, lienExterne, complement, texteAffiche )
	if Outils.notEmpty( num ) then
		local adresse = 
				lienIinterne	
				.. '&nbsp;<span class="plainlinks noarchive nowrap">[http://'
				.. lienExterne 
				.. mw.uri.encode( num, 'PATH' )
				.. ( complement or ' ' ) 
				.. mw.text.nowiki( texteAffiche or num )
				.. ']</span>'
		
		return adresse
	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 databaseExterne( arxiv, '[[arXiv]]', 'arxiv.org/abs/' ):gsub( '%%2F', '/' )
	end
end

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

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

function References.bnf( bnf )
	bnf = Outils.trim( bnf )
	if bnf then
		local texte = bnf
		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 )
			if bnfId:len() == 8 then 
				-- il manque la clé, on l'ajoute
				bnf = base .. References.arkId( 'cb' .. base )
				texte = base
			elseif bnfId:len() > 8 and bnfId:sub( 9, 9 ) == References.arkId( 'cb' .. base ) then
				-- ark valide
				bnf = bnfId:sub( 1, 9 )
				texte = base
			else
				-- ark qui semble non valide
				bnf = bnfId
				texte = bnfId
				category = '[[Catégorie:Recension temporaire pour le modèle Ouvrage|bnf]]'
			end
		else
			-- le paramètre ne semble pas un ark valide
			category = '[[Catégorie:Recension temporaire pour le modèle Ouvrage|bnf]]'
		end
		
		-- dans tous les cas on renvoie l'adresse, on catégorise juste pour vérifier ce qui ne va pas
		local lien = databaseExterne( bnf, 
			'notice [[Bibliothèque nationale de France|BnF]] n<sup>o</sup>', 
			'catalogue.bnf.fr/ark:/12148/cb', 
			'/PUBLIC FRBNF', 
			texte 
		)
		
		return lien .. category
	end
end

function References.dnb( dnb )
	return databaseExterne( dnb, '[[Bibliothèque nationale allemande|DNB]]', 'd-nb.info/' )
end

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

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

function References.lccn( lccn )
	return databaseExterne( lccn, '[[Numéro de contrôle de la Bibliothèque du Congrès|LCCN]]', 'lccn.loc.gov/' )
end

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

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

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

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

function References.sbn( sbn )
	local id = ( sbn or '' ):upper():gsub( '\\', '' ):gsub( '^ITICCU', '' )
	return databaseExterne( id, '[[Service bibliothécaire national]]', 'opac.sbn.it/bid/' )
end

function References.sudoc( sudoc )
	return databaseExterne( sudoc, '[[Système universitaire de documentation|SUDOC]]', 'www.sudoc.fr/' )
end

function References.wikisource( wikisource )
	if Outils.notEmpty( wikisource ) then
		return '[[s:' .. wikisource .. '|lire sur Wikisource]]'
	end
end

function References.zbl( zbl )
	return databaseExterne( 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.enLigne( args, validArg )
	local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
	local lang, esp = '', ''
	if args.langue then
		local Langue = require( 'Module:Langue' )
		lang = Langue.indicationMultilingue{ args.langue, args.langue2, args.langue3 }
		esp = '&nbsp'
	end
	
	local url = validArg( 'lien', 'url' )
	if url == nil then 
		if validArg( 'doi' ) then 
			url = 'http://dx.doi.org/' .. mw.uri.encode( args.doi ) 
		else
			return
		end
	end
	url = url:gsub( '%[', '%%5B' ):gsub( '%]', '%%5D' ):gsub( ' ', '%%20' )
	
	local texte = validArg( 'texte' ) or 'en ligne'
	local date = validArg( 'date', 'consulté le' )
	
	if date then 
		return lang .. esp .. '[' .. url .. ' ' .. texte .. ']&nbsp;(consultée le' .. date .. ')'
	else
		return lang .. esp .. '[' .. url .. ' ' .. texte .. ']'
	end
end

function References.affichageLiensExternes( args, validArg, lireEnLigne, consulteLe )
	local validArg = validArg or function ( ... ) return validTextArg( args, ... ) end
		
		local liensExternes = TableBuilder.new(  )
		
		-- isbn et issn
		liensExternes.minsert(
			References.isbn( args, validArg ),
			References.ean( args, validArg ),
			References.issn( args, validArg ),
			References.eissn( args, validArg ),
			References.ismn( args, validArg )
		)
		
		liensExternes.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( args['math reviews'] ),
			References.zbl( validArg( 'zbl', 'zbmath' ) ),
			References.arxiv( args.arxiv ),
			References.asin( args.asin ),
			References.sudoc( args.sudoc ),
			References.wikisource( args.wikisource )
		)
		
		liensExternes.minsert( 
				References.enLigne{ url = args['résumé'], texte = 'résumé' },
				References.enLigne{ url = args['présentation en ligne'], texte = 'présentation en ligne' },
				References.enLigne{ url = args['écouter en ligne'], texte = 'écouter en ligne' }
			)
		
		local url = validArg( 'lire en ligne', 'url texte', 'url', 'texte' )
		if url and lireEnLigne then
			liensExternes.minsert( 
				References.enLigne{
					lien = url,
					texte = 'lire en ligne',
				} .. ( References.indicationDeFormat( args['format électronique'] ) or '' )
			)
		end
		
		-- consulté le
		if consulteLe then
			local consult = validArg( 'consulté le', 'accessdate', 'Consulté le', 'consulté', 'consultée le' )
			if consult then
				if string.sub( consult, -1,-1) == '.' then
					consult = string.sub( consult, 1, -2)
				end
				local consulteLe = 'consulté en '
				local Date = require( 'Module:Date' )
				local test, tdate = Date.separationJourMoisAnnee( consult )
				if test then
					if tdate.jour then
						consulteLe = 'consulté le '
                        if tdate.jour == 1 then
                        	tdate.jour = Outils.abr( '1<sup>er</sup>', 'premier' )
                        end
					end
					consult = TableBuilder.new()
						.minsert( tdate.jour, tdate.mois, tdate.annee )
						.concat( ' ' )
				end					
				liensExternes.minsert( consulteLe .. Outils.nobr( consult:lower() ) )
			end
		end
		
		if #liensExternes > 0 then
			return ' <small style="line-height:1em;">(' .. liensExternes.concat( ', ' ) ..  ')</small>'
		end
end

function References.indicationDeFormat( format )
	if not Outils.trim( format ) then 
		return
	end
	local listeFormat = {
		audio = { "audio", "Fichiers audio au format MP3, Ogg..." },
		bat   = { "bat",   "Script de traitement par lot (batch)" },
		djvu  = { "DjVu",  "Document au format DjVu" },
		doc   = { "doc",   "Document Microsoft Word" },
		epub  = { "EPUB",  "Document au format Epub" },
		flash = { "flash", "Animation vectorielle au format Macromedia Flash" },
		hlp   = { "hlp",   "Fichier HeLP (aide) datant de Microsoft Windows 3.1" },
		html  = { "html",  "Fichier au format Hypertext Markup Language (HTML)" },
		image = { "image", "Image au format JPEG, PNG, GIF..." },
		java  = { "java",  "Applet Java" },
		mov   = { "mov",   "Vidéo au format Apple QuickTime" },
		mp3   = { "MP3",   "Fichier audio au format MP3" },
		odt   = { "odt",   "Document au format OpenDocument" },
		ogg   = { "ogg",   "Fichier au format conteneur Ogg" },
		pdf   = { "PDF",   "Document au format Portable Document Format (PDF) d'Adobe" },
		php   = { "php",   "Script PHP" },
		pl    = { "pl",    "Script Practical Extraction and Report Language (Perl)" },
		ppt   = { "ppt",   "Présentation Microsoft PowerPoint" },
		ps    = { "ps",    "Fichier de description vectorielle au format PostScript" },
		radio = { "radio", "Radio au format MPEG, AVI..." },
		rar   = { "rar",   "Document compressé au format RAR" },
		rm    = { "rm",    "Vidéo au format RealMedia, RealAudio..." },
		rtf   = { "RTF",   "Document texte en Rich Text Format (RTF)" },
		svg   = { "SVG",   "Image vectorielle au format Scalable Vector Graphics (SVG)" },
		sxi   = { "sxi",   "Présentation OpenOffice.org Impress" },
		sxw   = { "sxw",   "Document OpenOffice.org Writer" },
		tex   = { "TeX",   "Document TeX" },
		txt   = { "txt",   "Fichier au format texte brut" },
		video = { "vidéo", "Vidéo au format MPEG, AVI..." },
		xls   = { "xls",   "Classeur Microsoft Excel" },
		xml   = { "XML",   "Document au format Extensible Markup Language (XML)" },
		zip   = { "zip",   "Archive au format Zip" },
	}
	listeFormat['vidéo'] = listeFormat.video
	listeFormat.vid = listeFormat.video
	listeFormat.htm = listeFormat.html
	listeFormat.excel = listeFormat.xls
	listeFormat.powerpoint = listeFormat.ppt
	listeFormat.word = listeFormat.doc
	listeFormat.aud = listeFormat.audio
	
	local tabFormat = listeFormat[ string.lower( format ) ]
	if tabFormat then
		return ( ' <abbr class="abbr indicateur-format format-' .. string.lower(tabFormat[1]) .. '" 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, texte = string.match( format, "^(...) (.*)$")
		if ext and listeFormat[ string.lower( ext ) ] then
			return References.indicationDeFormat( ext ) .. ' ' .. texte
		else
			return ' ' .. '&#91;' .. format .. '&#93;'  -- '&#91;' = '<nowiki>[</nowiki>',  '&#93;' = '<nowiki>]</nowiki>',
		end
	end
	
end


return References