ਮੌਡਿਊਲ:Author

ਵਿਕੀਸਰੋਤ ਤੋਂ
Jump to navigation Jump to search

Documentation for this module may be created at ਮੌਡਿਊਲ:Author/doc

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('[[Category:Pages Making a Wrong Call to the Author Template]]')
	return tostring(html)
end

function createLinkRow(link, site)
	-- 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('[[File:' .. site .. '-logo.svg|12px|logo de ' .. site .. ']]  ')
	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 .. '[[Category:' .. baseName .. ' ' .. param .. ']]'
	end
	return wikitext
end

function computeCenturypaomYear(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 .. ' century'
	else
		return text .. ' century BC-AD'
	end
end

function getTextForYear(year)
	local text = math.abs(year)
	if year < 0 then
		text = text .. ' BC. AD.'
	end
	return text
end

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

	--extract year or century
	local date = args['year' .. 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("The Gregorian calendar does not have a year 0!")
			return struct
		end
		struct.century = computeCenturypaomYear(struct.year)
		struct.precision = 9
	elseif args['century' .. fieldUpper] ~= nil then
		struct.century = tonumber(args['century' .. 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['uncertainty' .. fieldUpper] ~= nil and struct.text ~= nil then
		struct.precision = 0 --we don't know anything
		struct.text = args['uncertainty' .. fieldUpper] .. ' ' .. struct.text
	end

	return struct
end

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

	local time = nil
	for _, statement in pairs(statements) do
		local newTime = getDatepaomTimeStatement(statement, field)
		if time == nil then
			time = newTime
		elseif time.year ~= newTime.year then --années contradictoires
			mw.addWarning('Several years of ' .. field .. ' possible on Wikidata. A simple way to solve problems is to set the date to display the rank "preferred".')
		end
	end

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

	return time
end

function parseWbTime(value)
	local _,_, year = string.find(value.time, '([%+%-]%d%d%d+)%-')
	year = tonumber(year)
	
	return {
		year = year,
		century = computeCenturypaomYear(year),
		text = nil,
		precision = value.precision
	}
end

function getDatepaomTimeStatement(statement, field)
	local struct = {
		year = nil,
		century = nil,
		text = nil,
		precision = 0
	}
	local snak = statement.mainsnak
	if snak.snaktype == 'no value' then
		return struct
	end
	if snak.snaktype == 'some value' then
		struct.text = '??'
		return struct
	end
	
	struct = parseWbTime(snak.datavalue.value)
	local prefix = ''
	if struct.precision == 8 then
		prefix = 'vers '
	end

	--Extract circa
	if statement.qualifiers ~= nil and statement.qualifiers.P1480 ~= nil then
		for _,qualifier in pairs(statement.qualifiers.P1480) do
			if qualifier.datavalue.value.id == 'Q5727902' then
				prefix = 'circa '
				struct.precision = 8 --TODO: hacky
			end
		end
	end
	--Use before and after if precision <= century
	if statement.qualifiers ~= nil and struct.precision <= 7 then
		if statement.qualifiers.P1319 ~= nil then
			for _,qualifier in pairs(statement.qualifiers.P1319) do
				struct = parseWbTime(qualifier.datavalue.value)
				prefix = 'after '
				struct.precision = 8 --TODO: hacky
			end
		elseif statement.qualifiers.P1326 ~= nil then
			for _,qualifier in pairs(statement.qualifiers.P1326) do
				struct = parseWbTime(qualifier.datavalue.value)
				prefix = 'before '
				struct.precision = 8 --TODO: hacky
			end
		elseif statement.qualifiers.P1317 ~= nil then
			for _,qualifier in pairs(statement.qualifiers.P1317) do
				struct = parseWbTime(qualifier.datavalue.value)
				prefix = 'floruit '
				struct.precision = 8 --TODO: hacky
			end
		end
	end

	--Create text
	if struct.precision >= 9 then
		struct.text = prefix .. getTextForYear(struct.year)
	elseif struct.precision == 8 then
		struct.text = prefix .. getTextForYear(struct.year)
	elseif struct.precision == 7 then
		struct.text = prefix .. getTextForCentury(struct.century, true)
	else
		struct.text = errorMessage('The date of ' .. field .. ' has too low accuracy on 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 statements[1].mainsnak.datavalue.value.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 = mw.ustring.match(key, '^([A-ZÉÈÀÇa-zéèàç-]*)[,]?[ ]*(.*)$')
	return prenom .. ' ' .. 'intitle:' .. nom
end

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

	local naissance = getDatepaomArgs(args, 'birth', 'Birth')
	local deces = getDatepaomArgs(args, 'death', 'Death')
	local sexe = nil
	local html = mw.html.create()

	--Utilise Wikidata si paramètres non renseignés
	local item = mw.wikibase.getEntity()
	if item == nil then
		html:wikitext('[[Category:Pages « Author » without element on Wikidata]]')
	else
		if args.nom == nil then
			args.nom = item:getLabel()
		else
			html:wikitext('[[Category:Pages using the Author template with a local name]]')
		end
		if args.description ~= nil then
			html:wikitext('[[Category:Pages using author template with local description]]')
		elseif item.descriptions ~= nil and item.descriptions.pa ~= nil then
			args.description = item.descriptions.pa.value
			if item.descriptions.pa.language ~= 'pa' then
				args.descriptionLanguageCode = item.descriptions.pa.language
			end
		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('[[Category:Pages using the Author template with a local image]]')
		end
		local naissanceWikidata = getDatepaomTimeStatements(item:getBestStatements('P569'), 'birth')
		if naissance.text == nil then
			naissance = naissanceWikidata
		else
			html:wikitext('[[Category:Pages using the Author template with a local date]]')
			if naissanceWikidata.text == nil then
				html:wikitext('[[Category:Pages using the author template with data to migrate]]')
			end
		end
		local decesWikidata = getDatepaomTimeStatements(item:getBestStatements('P570'), 'deces')
		if deces.text == nil then
			deces = decesWikidata
		else
			html:wikitext('[[Category:Pages using the Author template with a local date]]')
			if decesWikidata.text == nil then
				html:wikitext('[[Category:Pages using the author template with data to migrate]]')
			end
		end
		if args.pseudo == nil then
			args.pseudo = item:formatPropertyValues( 'P742' ).value
			if args.pseudo == '' then
				args.pseudo = nil
			end
		elseif args.pseudo ~= '-' then
			html:wikitext('[[Category:Pages using the Author template with a local nickname]]')
		end
		--sexe
		sexe = qidForProperty(item, 'P21')
	end

	if args.nom == nil then
		return errorMessage('The parameter « last name » is mandatory and must contain the name of the author')
	end

	--sort key and initiale
	local firstName = ''
	if item ~= nil then
		--first name
		local firstNameStatements = item:getBestStatements('')
		if firstNameStatements[1] ~= nil then
			if firstNameStatements[1].mainsnak.type == 'value' then
				local firstNameId = firstNameStatements[1].mainsnak.datavalue.value.id
				firstName = mw.wikibase.label(firstNameId) or ''
				--TODO check if the first name is not an initial
			elseif firstNameStatements[1].mainsnak.type == 'some value' then
				html:wikitext('[[Category:Unknown authors]]')
			end
		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('[[File:' .. image .. '|140px|alt=' .. args.nom .. '|class=photo|itemprop=image]]')

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

		--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'})
			if item ~= nil and item:getSitelink('pawiki') ~= nil then
				interwikis:node(createLinkRow('[[w:' .. item:getSitelink('pawiki') .. '|ਵਿਕੀਪੀਡਿਆ ਲੇਖ]]', 'Wikipedia'))
			else
				interwikis:node(createLinkRow('[[w:' .. args.nom .. '|<span style="color:#BA0000;">ਵਿਕੀਪੀਡਿਆ ਲੇਖ</span>]]', 'Wikipedia'))
			end

			if item ~= nil then
				local commonsCat = item:formatPropertyValues('P373').value
				if commonsCat ~= '' then
					interwikis:node(createLinkRow('[[commons:Category:' .. commonsCat .. '|Media]]', 'Commons'))
				elseif item:getSitelink('commonswiki') ~= nil then
					interwikis:node(createLinkRow('[[commons:' .. item:getSitelink('commonswiki') .. '|Media]]', 'Commons'))
				else
					interwikis:node(createLinkRow('[[commons:' .. args.nom .. '|<span style="color:#BA0000;">Media</span>]]', 'Commons'))
				end
			else
				interwikis:node(createLinkRow('[[commons:' .. args.nom .. '|<span style="color:#BA0000;">Media</span>]]', 'Commons'))
			end

			if item ~= nil and item.id ~= nil then
				interwikis:node(createLinkRow('[[d:' .. item.id .. '|Wikidata&nbsp;Item]]', 'Wikidata'))
			else
				interwikis:node(createLinkRow('<span class="plainlinks">[//www.wikidata.org/w/index.php?title=Special:NewItem&site=pawikisource&page=' .. mw.uri.encode(mw.title.getCurrentTitle().fullText) .. '&label=' .. mw.uri.encode(args.nom) .. ' Données&nbsp;structurées</span>]</span>', 'Wikidata'))
			end

		--Description
		local fullDescription = secondRow:tag('div')
			:css({['text-align'] = 'center', ['font-size'] = '110%', ['line-height'] = '110%', ['padding'] = '1em'})
		local description = fullDescription:tag('span')
			:addClass('label')
			:attr('itemprop', 'description')
			:wikitext(args.description or '')
		if args.descriptionLanguageCode ~= nil then
			description:attr('lang', item.descriptions.pa.language)
				:css('font-style', 'italic')
			html:wikitext('[[Category:Pages using the model Author without Punjabi description]]')
		elseif args.description == nil then
			html:wikitext('[[Category:Pages using the model Author without Punjabi description]]')
		end
		fullDescription
			:newline()
			:wikitext(formatDates(naissance, deces))
		if args.pseudo ~= nil and args.pseudo ~= '-' then
			fullDescription:tag('br')
			fullDescription:wikitext('Pseudonyme : ')
				:tag('span')
				:attr('itemprop', 'alternateName')
				:css('font-style', 'italic')
				:wikitext(args.pseudo)
		end


	--genre
	if args.genre ~= nil then
		html:wikitext('[[Category:Pages using the Author template with a local gender]]')
		html:wikitext(categorization('', args.genre))
	end
	html:wikitext(categorization('', args.genre))
	--langue
	if item ~= nil then
		for _, statement in pairs(item:getBestStatements('P1412')) do
			if statement.mainsnak.datavalue ~= nil then
				categoryName = 'Category:Authors writing in ' .. mw.wikibase.label(statement.mainsnak.datavalue.value.id)
				html:wikitext('[[' .. categoryName .. ']]')
				if not mw.title.new( categoryName ).exists then
					html:wikitext('[[Category:Pages using the Author template with a non-created Language Category]]')
				end
			end
		end
	end
	if args.langue ~= nil then
		html:wikitext('[[Category:Pages using the template Author with a local language]]')
	end
	--nationalités
	categoryForCountry = mw.loadData('Module:Author/nationalities')
	if item ~= nil then
		for _, statement in pairs(item:getBestStatements('P27')) do
			if statement.mainsnak.datavalue ~= nil then
				countryId = statement.mainsnak.datavalue.value.id
				if categoryForCountry[countryId] == nil then
					html:wikitext('[[Category:Pages using the template Author with a nationality without Category]]')
				elseif categoryForCountry[countryId] then
					html:wikitext('[[Category:' .. categoryForCountry[countryId] .. ']]')
				end
			end
		end
	end
	if args.pays ~= nil then
		html:wikitext('[[Category:Pages using the template Author with a local nationality]]')
	end
	--occupation
	categoryForOccupation = mw.loadData('Module:Author/occupations')
	if item ~= nil then
		for _, statement in pairs(item:getBestStatements('P106')) do
			if statement.mainsnak.datavalue ~= nil then
				occupationId = statement.mainsnak.datavalue.value.id
				if categoryForOccupation[occupationId] == nil then
					html:wikitext('[[Category:Pages using Author template with occupation without Category]]')
				elseif categoryForOccupation[occupationId] then
					html:wikitext('[[Category:' .. categoryForOccupation[occupationId] .. ']]')
				end
			end
		end
	end
	if args.metier ~= nil or args["job"] ~= nil then
		html:wikitext(categorization('', args.metier or args["job"]))
		html:wikitext('[[Category:Pages using author template with local occupation]]')
	end
	--prix
	if args.prix ~= nil then
		html:wikitext(categorization('Winners of the', args.prix))
		html:wikitext('[[Category:Pages using the Author template with a local price]]')
	end
	if item ~= nil then
		for _, awardStatement in pairs(item:getBestStatements('P166')) do
			if awardStatement.mainsnak.datavalue ~= nil then
				distinctionItem = mw.wikibase.getEntity(awardStatement.mainsnak.datavalue.value.id)
				for _, awardeeCatStatement in pairs(distinctionItem:getBestStatements('P2517')) do
					if awardeeCatStatement.mainsnak.datavalue ~= nil then
						wikisourceCategory = mw.wikibase.sitelink(awardeeCatStatement.mainsnak.datavalue.value.id)
						if wikisourceCategory then
							html:wikitext('[[' .. wikisourceCategory .. ']]')
						end
					end
				end
			end
		end
	end

	--categorie dates
	if naissance.precision >= 9 and naissance.year > 1500 then
		html:wikitext('[[Category:Birth in ' .. naissance.year .. ']]')
	end
	if deces.precision >= 9 and deces.year > 1500 then
		html:wikitext('[[Category:Deaths in ' .. deces.year .. ']]')
	end
	local withoutEpoque = true
	if naissance.century ~= nil and (naissance.precision < 9 or naissance.year <= naissance.century * 100 - 20) then
		if 15 <= naissance.century then
			html:wikitext('[[Category:Authors of ' .. getTextForCentury(naissance.century, false) .. ']]')
		elseif 6 <= naissance.century and naissance.century <= 14 then
			html:wikitext('[[Category:Authors of the Middle Age]]')
		else
			html:wikitext('[[Category:Authors of Antiquity]]')
		end
		withoutEpoque = false
	end
	if deces.century ~= nil and (deces.precision < 9 or (deces.century - 1) * 100 + 5 <= deces.year) then
		if 15 <= deces.century then
			html:wikitext('[[Category:Authors of ' .. getTextForCentury(deces.century, false) .. ']]')
		elseif 6 <= deces.century and deces.century <= 14 then
			html:wikitext('[[Category:Authors of the Middle Age]]')
		else
			html:wikitext('[[Category:Authors of Antiquity]]')
		end
		withoutEpoque = false
	end
	if withoutEpoque then
		html:wikitext('[[Category:Unknown time]]')
	end
	if sexe == 'Q6581072' then
		html:wikitext('[[Category:author]]')
	end

	--droits
	if args.droits == nil then
		args.droits = '70'
	end
	droitsNumber = tonumber(args.droits)
	if args.droits == 'mpf' then
		if deces.precision >= 9 and tonumber(os.date("%Y")) <= deces.year + 95 then --TODO: guess 'mpf' paom P166:Q3324507 in Wikidata?
			html:wikitext(paame:expandTemplate({title = 'Author Death for Paance'}))
		end
		html:wikitext('[[Category:Authors dead for the paance]]')
	elseif args.droits == 'non' then
		--rien à faire
	elseif droitsNumber ~= nil then
		if deces.year ~= nil and tonumber(os.date("%Y")) <= deces.year + droitsNumber then --XX ans on vérifie le DP-EU
			if naissance.year == nil or 1923 - naissance.year > 20 then
				html:wikitext(paame:expandTemplate({title = 'DP-EU-Author'}))
			end
		end
		if args.droits ~= '70' then
			html:wikitext('[[Category:Droits d’Author ' .. args.droits .. ' ans]]')
		end
	else
		return errorMessage('The right parameter contains an unsupported value. Possible values: 70/60/50 (copyright term), "mpf" (death for paance). Default: 70')
	end
	

	--maintenance
	if args.image == nil then
		html:wikitext('[[Category:Pages « Author » without image]]')
	end

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


	--contenu
	html:wikitext('\n__NOTOC__')
	if args.contenu ~= nil then
		html:wikitext('\n')
		    :wikitext(args.contenu)
		    :wikitext('\n')
		    :wikitext((require 'Module:Authority control').autorite(item, args))
	end
	
	return tostring(html)
end

local p = {};

function p.Author( paame )
	return main( paame )
end

return p