« Module:Auteur2 » : différence entre les versions

La bibliothèque libre.
Contenu supprimé Contenu ajouté
usage des dates plus restrictif en cas de précision inférieure à l'année
n'affiche pas d'erreur si Wikidata contiens plusieurs dates avec la même année
Ligne 114 : Ligne 114 :


function getDateFromTimeStatements(statements, field)
function getDateFromTimeStatements(statements, field)
if #statements == 0 then
return {
precision = 0
}
end

local time = nil
for _, statement in pairs(statements) do
local newTime = getDateFromTimeStatement(statement, field)
if time == nil then
time = newTime
elseif time.year ~= newTime.year then --années contradictoires
return {
text = errorMessage('Plusieurs années de ' .. field .. ' possibles sur Wikidata. Une manière simple de résoudre se problème est de mettre la date à afficher au rang "préféré".'),
precision = 0
}
end
end

if time == nil then
return {
precision = 0
}
end

return time
end

function getDateFromTimeStatement(statement, field)
local struct = {
local struct = {
year = nil,
year = nil,
Ligne 120 : Ligne 149 :
precision = 0
precision = 0
}
}
local snak = statement.mainsnak

if #statements == 0 then
return struct
end
if #statements > 1 then
struct.text = errorMessage('Plusieurs dates de ' .. field .. ' possibles sur Wikidata')
return struct
end

local snak = statements[1].mainsnak
if snak.snaktype ~= 'value' then
if snak.snaktype ~= 'value' then
struct.text = errorMessage('La date de ' .. field .. ' n’est pas une valeur sur Wikidata')
struct.text = errorMessage('La date de ' .. field .. ' n’est pas une valeur sur Wikidata')

Version du 1 décembre 2015 à 21:01

Documentation du module [voir] [modifier] [purger]
La documentation de ce module Scribunto écrit en Lua est incluse depuis sa sous-page de documentation.

Ce module contient le code de Modèle:Auteur. Il se charge notamment des tâches d’extraction/transformation des données depuis les paramètres passés au modèle et des informations relatives sur les autres projets Wikimédia, notamment Wikidata.

Pages de données pour la catégorisation automatique :

function errorMessage(text)
	-- Return a html formated version of text stylized as an error.
	local html = mw.html.create('div')
	html:addClass('error')
		:wikitext(text)
		:wikitext('[[Catégorie:Pages faisant un appel erroné au modèle Auteur]]')
	return tostring(html)
end

function createLinkRow(link)
	-- Return some html stylised formated text of link
	local html = mw.html.create('div')
	html:tag('span')
		:css({['color'] = '#232388', ['font-size'] = '140%', ['line-height'] = '150%'})
		:wikitext('•  ')
	html:wikitext(link)
	return html
end

function categorization(baseName, parameter)
	-- Return the categorisation wikitext for each element of parameter prefixed with baseName
	if parameter == nil then
		return ''
	end

	local wikitext = ''
	for _,param in pairs(mw.text.split(parameter, '/', true)) do
		wikitext = wikitext .. '[[Catégorie:' .. baseName .. ' ' .. param .. ']]'
	end
	return wikitext
end

function computeCenturyFromYear(year)
	-- Return the correpsonding century for the given year
	if year >= 0 then
		return math.ceil(year / 100)
	else
		return -math.ceil(-year / 100)
	end
end

function getTextForCentury(century, withHtml)
	-- Return a roman ordinal of century appended with a trailing text precising
	-- if the date is before of after the calendar reference point.
	local romanNumbers1 = {'', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'}
	local romanNumbers2 = {'', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'}

	local text = romanNumbers2[math.floor(math.abs(century) / 10) + 1] .. romanNumbers1[math.floor(math.abs(century) % 10) + 1]
	if withHtml then
		text = text .. '<sup>e</sup>'
	else
		text = text .. 'e'
	end
	if century > 0 then
		return text .. ' siècle'
	else
		return text .. ' siècle av. J.-C.'
	end
end

function getTextForYear(year)
	local text = math.abs(year)
	if year < 0 then
		text = text .. ' av. J.-C.'
	end
	return text
end

function getDateFromArgs(args, field, fieldUpper)
	local struct = {
		year = nil,
		century = nil,
		text = nil,
		precision = 0
	}

	--extract year or century
	local date = args['annee' .. fieldUpper]
	if date == nil then
		date = args[field]
	end
	if tonumber(date) ~= nil then
		struct.year = tonumber(date)
		if struct.year == 0 then
			struct.text = errorMessage("Le calendrier grégorien ne possède pas d’année 0 !")
			return struct
		end
		struct.century = computeCenturyFromYear(struct.year)
		struct.precision = 9
	elseif args['siecle' .. fieldUpper] ~= nil then
		struct.century = tonumber(args['siecle' .. fieldUpper])
		struct.precision = 7
	end

	--build text
	if struct.year ~= nil then
		struct.text = getTextForYear(struct.year)
	elseif struct.century ~= nil then
		struct.text = getTextForCentury(struct.century, true)
	else
		struct.text = date
	end
	if args['text' .. fieldUpper] ~= nil then
		struct.precision = 0 --we don't know anything
		struct.text = args['text' .. fieldUpper] .. ' ' .. struct.text
	end
	if args['incertitude' .. fieldUpper] ~= nil then
		struct.precision = 0 --we don't know anything
		struct.text = args['incertitude' .. fieldUpper] .. ' ' .. struct.text
	end

	return struct
end

function getDateFromTimeStatements(statements, field)
	if #statements == 0 then
		return {
			precision = 0
		}
	end

	local time = nil
	for _, statement in pairs(statements) do
		local newTime = getDateFromTimeStatement(statement, field)
		if time == nil then
			time = newTime
		elseif time.year ~= newTime.year then --années contradictoires
			return {
				text = errorMessage('Plusieurs années de ' .. field .. ' possibles sur Wikidata. Une manière simple de résoudre se problème est de mettre la date à afficher au rang "préféré".'),
				precision = 0
			}
		end
	end

	if time == nil then
		return {
			precision = 0
		}
	end

	return time
end

function getDateFromTimeStatement(statement, field)
	local struct = {
		year = nil,
		century = nil,
		text = nil,
		precision = 0
	}
	local snak = statement.mainsnak
	if snak.snaktype ~= 'value' then
		struct.text = errorMessage('La date de ' .. field .. ' n’est pas une valeur sur Wikidata')
		return struct
	end
	local value = snak.datavalue.value

	local _,_, year = string.find(value.time, '([%+%-]%d%d%d+)%-')
	year = tonumber(year)
	struct.year = year
	struct.century = computeCenturyFromYear(year)
	struct.precision = value.precision
	
	--Create text
	if value.precision >= 9 then
		struct.text = getTextForYear(struct.year)
	elseif value.precision == 8 then
		struct.text = 'vers ' .. getTextForYear(struct.year)
	elseif value.precision == 7 then
		struct.text = getTextForCentury(struct.century, true)
	else
		struct.text = errorMessage('La date de ' .. field .. ' a une précision trop faible sur Wikidata')
	end
	
	return struct
end

function formatDates(naissance, deces)
	if naissance.text == nil and deces.text == nil then
		return ''
	end

	local text = '('
	if naissance.precision >= 9 then
		text = text .. '<time datetime=' .. naissance.year .. ' class="bday">' .. naissance.text .. '</time> '
	elseif naissance.text ~= nil then
		text = text .. naissance.text .. ' '
	end
	text = text .. '–'
	if deces.precision >= 9 then
		text = text .. ' <time datetime=' .. deces.year .. '  class="dday">' .. deces.text .. '</time>'
	elseif deces.text ~= nil then
		text = text .. ' ' .. deces.text
	end
	return text .. ')'
end

function qidForProperty(item, property)
	local statements = item:getBestStatements(property)
	if statements[1] ~= nil and statements[1].mainsnak.datavalue ~= nil then
		return 'Q' .. statements[1].mainsnak.datavalue.value['numeric-id']
	end
	return nil
end

function main(frame)
	--create a clean table of parameters with blank parameters removed
	local args = {}
	for k,v in pairs(frame:getParent().args) do
		if v ~= '' then
			args[k] = v
		end
	end

	local naissance = getDateFromArgs(args, 'naissance', 'Naissance')
	local deces = getDateFromArgs(args, 'deces', 'Deces')
	local sexe = nil

	--Utilise Wikidata si paramètres non renseignés
	local item = mw.wikibase.getEntityObject()
	if item ~= nil then
		if args.nom == nil then
			args.nom = item:getLabel()
		end
		if args.description == nil and item.descriptions ~= nil and item.descriptions.fr ~= nil then
			args.description = item.descriptions.fr.value
		end
		if args.image == nil then
			local statements = item:getBestStatements('P18')
			if statements[1] ~= nil and statements[1].mainsnak.datavalue ~= nil then
				args.image = statements[1].mainsnak.datavalue.value
			end
		end
		if naissance.year == nil and naissance.century == nil then
			naissance = getDateFromTimeStatements(item:getBestStatements('P569'), 'naissance')
		end
		if deces.year == nil and deces.century == nil then
			deces = getDateFromTimeStatements(item:getBestStatements('P570'), 'deces')
		end
		--sexe
		sexe = qidForProperty(item, 'P21')
	end

	if args.nom == nil then
		return errorMessage('Le paramètre « nom » est obligatoire et doit contenir le nom de l’auteur')
	end

	--sort key and initiale
	local firstName = ''
	local familyName = ''
	if item ~= nil then
		local firstNameId = qidForProperty(item, 'P735')
		if firstNameId ~= nil then
			firstName = mw.wikibase.label(firstNameId)
		end
		local familyNameId = qidForProperty(item, 'P734')
		if familyNameId ~= nil then
			familyName = mw.wikibase.label(familyNameId)
		end
	end
	if familyName == '' then
		--We are in a simple case with first name and last name. TODO: bad hack, should be improved
		local nameParts = mw.text.split(args.nom, ' ', true)
		if #nameParts == 2 then
			firstName = nameParts[1]
			familyName = nameParts[2]
		end
	end
	if args.cle == nil then
		if familyName ~= '' then
			local moduleClassement = require 'Module:Classement'
			args.cle = moduleClassement.getSortKeyForName({args = {firstName, familyName}})
		else
			return errorMessage('Le paramètre « cle » est obligatoire et doit contenir une clé de tris pour l’auteur')
		end
	end

	if args.initiale == nil then
		if args.cle ~= nil then
			args.initiale = string.sub(args.cle, 1, 1)
		else
			return errorMessage('Le paramètre « initiale » est obligatoire et doit contenir l’initiale du nom de l’auteur en majuscule non accentuée')
		end
	end
	

	local html = mw.html.create()
	local main = html:tag('div')
		:addClass('vcard')
		:css({['background-color'] = '#F1F1DE', ['overflow'] = 'auto', ['border-radius'] = '0.7em', ['box-shadow'] = '0.2em 0.3em 0.2em #B7B7B7'})

	--Image
	local image = args.image
	if image == nil then
		local defaultImages = {'Silver - replace this image male.svg', 'Silver - replace this image female.svg'}
		if sexe == 'Q6581097' then
			image = defaultImages[1]
		elseif sexe == 'Q6581072' then
			image = defaultImages[2]
		else
			image = defaultImages[math.random(#defaultImages)]
		end
	end
	main:tag('div')
		:css({['float'] = 'right', ['margin'] = '1em'})
		:wikitext('[[Fichier:' .. image .. '|140px|alt=' .. args.nom .. '|class=photo]]')

	--First row	
	local firstRow = main:tag('div')

		--Categorie Auteur-X
		firstRow:tag('div')
			:css({['float'] = 'left', ['font-size'] = '115%', ['text-indent'] = '1em'})
			:tag('span')
				:css('color', '#aaaa66')
				:wikitext('◄')
				:done()
			:wikitext('&nbsp;[[:Catégorie:Auteurs-' .. args.initiale .. '|Auteurs&nbsp;' .. args.initiale .. ']]')

		--Title
		firstRow:tag('h1')
			:addClass('fn')
			:css({['text-align'] = 'center', ['font-size'] = '160%', ['font-weight'] = 'bold', ['border-bottom'] = 'none'})
			:wikitext(args.nom)
	
	--Second row
	local secondRow = main:tag('div')

		--Interwikis
		local interwikis = secondRow:tag('div')
			:css({['float'] = 'left', ['height'] = '50%', ['font-size'] = '75%', ['text-indent'] = '2em'})
			:node(createLinkRow('<span class="plainlinks">[//fr.wikisource.org/wiki/Spécial:IndexPages?key=' .. mw.uri.encode(mw.title.getCurrentTitle().text) .. ' Fac-similés]</span>'))
			if item ~= nil and item:getSitelink('frwiki') ~= nil then
				interwikis:node(createLinkRow('[[w:' .. item:getSitelink('frwiki') .. '|Biographie]]'))
			else
				interwikis:node(createLinkRow('[[w:' .. args.nom .. '|<span style="color:#BA0000;">Biographie</span>]]'))
			end
			if item ~= nil and item:getSitelink('frwikiquote') ~= nil then
				interwikis:node(createLinkRow('[[q:' .. item:getSitelink('frwikiquote') .. '|Citations]]'))
			else
				interwikis:node(createLinkRow('[[q:' .. args.nom .. '|<span style="color:#BA0000;">Citations</span>]]'))
			end

			local commonsLink = nil
			if item ~= nil then
				commonsLink = item:getSitelink('commonswiki') or item:formatPropertyValues('P373').value
			end
			if commonsLink ~= nil then
				interwikis:node(createLinkRow('[[commons:' .. commonsLink .. '|Médias]]'))
			else
				interwikis:node(createLinkRow('[[commons:' .. args.nom .. '|<span style="color:#BA0000;">Médias</span>]]'))
			end
			if item ~= nil and item.id ~= nil then
				interwikis:node(createLinkRow('[[d:' .. item.id .. '|Données&nbsp;structurées]]'))
			else
				interwikis:node(createLinkRow('<span class="plainlinks">[//www.wikidata.org/w/index.php?title=Special:NewItem&site=frwikisource&page=' .. mw.uri.encode(mw.title.getCurrentTitle().fullText) .. '&label=' .. mw.uri.encode(args.nom) .. ' Données&nbsp;structurées</span>]</span>'))
			end

		--Description
		secondRow:tag('div')
			:addClass('label')
			:css({['text-align'] = 'center', ['font-size'] = '110%', ['line-height'] = '110%', ['padding'] = '1em'})
			:wikitext((args.description or '') .. ' ' .. formatDates(naissance, deces))

	--categories
	html:wikitext('[[Catégorie:Auteurs]]' .. '[[Catégorie:Auteurs-' .. args.initiale .. ']]')
	html:wikitext(categorization('', args.pseudo))
	html:wikitext(categorization('', args.genre))
	html:wikitext(categorization('Auteurs', args.langue))
	--html:wikitext(categorization('Auteurs par pays :', args.pays)) les catégories semblent ne pas exister
	html:wikitext(categorization('', args.metier))
	html:wikitext(categorization('Lauréats du', args.prix))

	--categorie dates
	if naissance.precision >= 9 and naissance.year > 1500 then
		html:wikitext('[[Catégorie:Naissance en ' .. naissance.year .. ']]')
	end
	if deces.precision >= 9 and deces.year > 1600 then
		html:wikitext('[[Catégorie:Décès en ' .. deces.year .. ']]')
	end
	local withoutEpoque = true
	if naissance.century ~= nil and (naissance.year == nil or naissance.year <= naissance.century * 100 - 20) then
		if 15 <= naissance.century then
			html:wikitext('[[Catégorie:Auteurs du ' .. getTextForCentury(naissance.century, false) .. ']]')
		elseif 6 <= naissance.century and naissance.century <= 14 then
			html:wikitext('[[Catégorie:Auteurs du Moyen Âge]]')
		else
			html:wikitext('[[Catégorie:Auteurs de l’Antiquité]]')
		end
		withoutEpoque = false
	end
	if deces.century ~= nil and (deces.year == nil or (deces.century - 1) * 100 + 5 <= deces.year) then
		if 15 <= deces.century then
			html:wikitext('[[Catégorie:Auteurs du ' .. getTextForCentury(deces.century, false) .. ']]')
		elseif 6 <= deces.century and deces.century <= 14 then
			html:wikitext('[[Catégorie:Auteurs du Moyen Âge]]')
		else
			html:wikitext('[[Catégorie:Auteurs de l’Antiquité]]')
		end
		withoutEpoque = false
	end
	if withoutEpoque then
		html:wikitext('[[Catégorie:Epoque inconnue]]')
	end

	--droits
	if args.droits == 'mpf' and deces.precision >= 9 and tonumber(os.date("%Y")) <= deces.year + 95 then
		html:wikitext(frame:expandTemplate({title = 'Auteur Mort pour la France'}))
	elseif args.droits == '50' then
		html:wikitext('[[Catégorie:Droits d’auteur 50 ans]]')
	elseif args.droits ~= 'non' and deces.year ~= nil and tonumber(os.date("%Y")) <= deces.year + 70 then --70 ans on vérifie le DP-EU
		if naissance.year ~= nil then
			if 1923 - naissance.year > 20 then
				html:wikitext(frame:expandTemplate({title = 'DP-EU-Auteur'}))
			end
		else -- en cas de doute
			html:wikitext(frame:expandTemplate({title = 'DP-EU-Auteur'}))
		end
	end

	--maintenance
	if args.image == nil then
		html:wikitext('[[Catégorie:Pages « Auteur » sans image]]')
	end

	html:wikitext(frame:preprocess('{{DISPLAYTITLE:' .. args.nom .. '}}'))
	if args.cle ~= nil then
		html:wikitext(frame:preprocess('{{DEFAULTSORT:' .. args.cle .. '}}'))
	end

	return tostring(html) .. '\n__NOTOC__'
end

local p = {}
function p.auteur( frame )
	return main( frame )
end
return p