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

La bibliothèque libre.
Contenu supprimé Contenu ajouté
+ itemprop=name pour le nom
correction de bug si les labels n'existent pas
Ligne 305 : Ligne 305 :
if firstNameStatements[1].mainsnak.type == 'value' then
if firstNameStatements[1].mainsnak.type == 'value' then
local firstNameId = 'Q' .. firstNameStatements[1].mainsnak.datavalue.value['numeric-id']
local firstNameId = 'Q' .. firstNameStatements[1].mainsnak.datavalue.value['numeric-id']
firstName = mw.wikibase.label(firstNameId)
firstName = mw.wikibase.label(firstNameId) or ''
--TODO check if the first name is not an initial
--TODO check if the first name is not an initial
elseif firstNameStatements[1].mainsnak.type == 'somevalue' then
elseif firstNameStatements[1].mainsnak.type == 'somevalue' then
Ligne 314 : Ligne 314 :
local familyNameId = qidForProperty(item, 'P734')
local familyNameId = qidForProperty(item, 'P734')
if familyNameId ~= nil then
if familyNameId ~= nil then
familyName = mw.wikibase.label(familyNameId)
familyName = mw.wikibase.label(familyNameId) or ''
end
end
end
end

Version du 8 avril 2016 à 18:03

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 == 'novalue' then
		return struct
	end
	if snak.snaktype == 'somevalue' then
		struct.text = '??'
		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
	
	--Extract circa
	if statement.qualifiers ~= nil and statement.qualifiers.P1480 ~= nil then
		for _,qualifier in pairs(statement.qualifiers.P1480) do
			if qualifier.datavalue.value['numeric-id'] == 5727902 then
				struct.precision = 8
			end
		end
	end
	--TODO: before and after
	
	--Create text
	if struct.precision >= 9 then
		struct.text = getTextForYear(struct.year)
	elseif struct.precision == 8 then
		struct.text = 'vers ' .. getTextForYear(struct.year)
	elseif struct.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" itemprop="birthDate">' .. 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" itemprop="deathDate">' .. 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 searchKey(key)
	-- normally the key does not contain any diacritic but it's a common misuse
	-- of the clef = so handle at least the most usual diacritics, note than
	-- prenom can be empty
	local nom, prenom = string.match(key, '^([A-ZÉÈÀÇa-zéèàç-]*)[,]?[ ]*(.*)$')
	return prenom .. ' ' .. 'intitle:' .. nom
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
	local html = mw.html.create()

	--Utilise Wikidata si paramètres non renseignés
	local item = mw.wikibase.getEntityObject()
	if item == nil then
		html:wikitext('[[Catégorie:Pages « Auteur » sans élément sur Wikidata]]')
	else
		if args.nom == nil then
			args.nom = item:getLabel()
		else
			html:wikitext('[[Catégorie:Pages utilisant le modèle Auteur avec un nom local]]')
		end
		if args.description ~= nil then
			html:wikitext('[[Catégorie:Pages utilisant le modèle Auteur avec une description locale]]')
		elseif 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
		else 
			html:wikitext('[[Catégorie:Pages utilisant le modèle Auteur avec une image locale]]')
		end
		local naissanceWikidata = getDateFromTimeStatements(item:getBestStatements('P569'), 'naissance')
		if naissance.text == nil then
			naissance = naissanceWikidata
		else
			html:wikitext('[[Catégorie:Pages utilisant le modèle Auteur avec une date locale]]')
			if naissanceWikidata.text == nil then
				html:wikitext('[[Catégorie:Pages utilisant le modèle Auteur avec des données à migrer]]')
			end
		end
		local decesWikidata = getDateFromTimeStatements(item:getBestStatements('P570'), 'deces')
		if deces.text == nil then
			deces = decesWikidata
		else
			html:wikitext('[[Catégorie:Pages utilisant le modèle Auteur avec une date locale]]')
			if decesWikidata.text == nil then
				html:wikitext('[[Catégorie:Pages utilisant le modèle Auteur avec des données à migrer]]')
			end
		end
		if args.pseudo == nil then
			args.pseudo = item:formatPropertyValues( 'P742' ).value
			if args.pseudo == '' then
				args.pseudo = nil
			end
		else
			html:wikitext('[[Catégorie:Pages utilisant le modèle Auteur avec un pseudo local]]')
		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
		--first name
		local firstNameStatements = item:getBestStatements('P735')
		if firstNameStatements[1] ~= nil then
			if firstNameStatements[1].mainsnak.type == 'value' then
				local firstNameId = 'Q' .. firstNameStatements[1].mainsnak.datavalue.value['numeric-id']
				firstName = mw.wikibase.label(firstNameId) or ''
				--TODO check if the first name is not an initial
			elseif firstNameStatements[1].mainsnak.type == 'somevalue' then
				html:wikitext('[[Catégorie:Auteurs de prénom inconnu]]')
			end
		end
		--family name
		local familyNameId = qidForProperty(item, 'P734')
		if familyNameId ~= nil then
			familyName = mw.wikibase.label(familyNameId) or ''
		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 main = html:tag('div')
		:addClass('vcard')
		:attr('itemscope', '')
		:attr('itemtype', 'http://schema.org/Person')
		:css({['background-color'] = '#F1F1DE', ['overflow'] = 'auto', ['border-radius'] = '0.7em', ['box-shadow'] = '0.2em 0.3em 0.2em #B7B7B7'})

	if item ~= nil and item.id ~= nil then
		main:attr('itemid', 'http://www.wikidata.org/entity/' .. item.id)
	end
	
	--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|itemprop=image]]')

	--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')
			:attr('itemprop', 'name')
			: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(searchKey(args.cle)) .. ' 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

			if item ~= nil then
				local commonsCat = item:formatPropertyValues('P373').value
				if commonsCat ~= '' then
					interwikis:node(createLinkRow('[[commons:Category:' .. commonsCat .. '|Médias]]'))
				elseif item:getSitelink('commonswiki') ~= nil then
					interwikis:node(createLinkRow('[[commons:' .. item:getSitelink('commonswiki') .. '|Médias]]'))
				else
					interwikis:node(createLinkRow('[[commons:' .. args.nom .. '|<span style="color:#BA0000;">Médias</span>]]'))
				end
			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
		local description = '<span class="label" itemprop="description">' .. (args.description or '') .. '</span> ' .. formatDates(naissance, deces)
		if args.pseudo ~= nil then
			description = description .. '<br />Pseudonyme : \'\'<span itemprop="alternateName">' .. args.pseudo .. '</span>\'\''
		end
		secondRow:tag('div')
			:css({['text-align'] = 'center', ['font-size'] = '110%', ['line-height'] = '110%', ['padding'] = '1em'})
			:wikitext(description)

	--categories
	html:wikitext('[[Catégorie:Auteurs]]' .. '[[Catégorie:Auteurs-' .. args.initiale .. ']]')
	html:wikitext(categorization('', args.genre))
	--html:wikitext(categorization('Auteurs', args.langue)) Les catégories semblent être des nationalités et non des langues
	--html:wikitext(categorization('Auteurs par pays :', args.pays)) les catégories semblent ne pas exister
	html:wikitext(categorization('', args.metier or args["métier"]))
	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 > 1500 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
	if sexe == 'Q6581072' then
		html:wikitext('[[Catégorie:Femmes auteurs]]')
	end

	--droits
	if args.droits == 'mpf' then
		if deces.precision >= 9 and tonumber(os.date("%Y")) <= deces.year + 95 then --TODO: guess 'mpf' from P166:Q3324507 in Wikidata?
			html:wikitext(frame:expandTemplate({title = 'Auteur Mort pour la France'}))
		end
		html:wikitext('[[Catégorie:Auteurs morts 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