Module:Authority control: Difference between revisions

From The Goon Show Depository

en>MSGJ
(add tooltip to show name of identifier is present, rename link2 to customlink)
No edit summary
 
(24 intermediate revisions by 3 users not shown)
Line 1: Line 1:
require('strict')
-- require('strict')
local config = require("Module:Authority control/config")
local p = {}
local p = {}
local frame = mw.getCurrentFrame()
local config_file = frame.args.config and frame.args.config~='' and ('/' .. frame.args.config) or ''
local config = mw.loadData('Module:Authority control/config' .. config_file)
local title = mw.title.getCurrentTitle()
local title = mw.title.getCurrentTitle()
local namespace = title.namespace
local namespace = title.namespace
local testcases = (string.sub(title.subpageText,1,9) == 'testcases')
local testcases = title.subpageText == config.i18n.testcases


local function needsAttention(sortkey)
local wikilink = function(target, label)
return '[[Category:Pages with authority control identifiers needing attention|' .. sortkey .. title.text .. ']]'
return label and '[[' .. target .. '|' .. label .. ']]' or '[[' .. target .. ']]'
end
end


local function addCat(cat,sortkey)
local needsAttention = function(sortkey)
if cat and cat ~= '' and (namespace == 0 or namespace == 14 or testcases) then
return wikilink(config.i18n.category .. ':' .. config.i18n.attentioncat, sortkey .. title.text)
end
 
local addCat = function(cat, sortkey)
if cat and cat~='' and (namespace==0 or namespace==14 or testcases) then
local redlinkcat = ''
local redlinkcat = ''
if testcases == false and mw.title.new(cat, 14).exists == false then
if testcases==false then
redlinkcat = needsAttention('N')
local success, exists = pcall(function() return mw.title.new(cat, 14).exists end)
end
if success and not exists then  
if sortkey then
redlinkcat = needsAttention('N')
cat = '[[Category:'..cat..'|' .. sortkey .. title.text .. ']]'
end
else
cat = '[[Category:'..cat..']]'
end
end
cat = cat .. redlinkcat
return wikilink(config.i18n.category..':'..cat, sortkey and sortkey..title.text) .. redlinkcat
return cat
else
else
return ''
return ''
Line 28: Line 31:
end
end


local function getCatForId(id,faulty)
local tooltip = function(text, label)
local cat = 'Articles with '
if label and label~='' then
if faulty then cat = cat .. 'faulty ' end
return frame:expandTemplate{
cat = cat .. id .. ' identifiers'
title = 'Tooltip',
return addCat(cat)
args = {text, label}
}
else
return text
end
end
end


local function getIdsFromWikidata(qid,property)
local getstatement = function(id, propid)
local function getquals(statement,qualid)
local statement = mw.wikibase.getBestStatements('P' .. id, 'P' .. propid)
if statement.qualifiers and statement.qualifiers['P'..qualid] then
local value
return mw.wikibase.renderSnak(statement.qualifiers['P'..qualid][1])
if statement and statement[1] and statement[1].mainsnak.datavalue.value.id then
else
value = statement[1].mainsnak.datavalue.value.id
return false
return value
end
end
end
p.getname = function(property) -- function to lookup the name of a property and provide a link if one exists
local item
for _, propnameqid in ipairs(config.property_items) do
item = getstatement(property, propnameqid)
if item then break end
end
end
local ids = {}
if item then
if qid then
local link = frame:expandTemplate{
for _, statement in ipairs(mw.wikibase.getBestStatements(qid,property)) do
title = 'Wikidata fallback link',
if statement.mainsnak.datavalue then
args = {item}
local val = statement.mainsnak.datavalue.value
}
if val then
local raw = mw.wikibase.getLabel(item)
local namedas = getquals(statement,1810) or getquals(statement,742) or ''
return link, raw
table.insert(ids,{id=val,name=namedas})
else
end
return ''
end
end
end
end
return ids
end
end


local function makelink(conf,val,nextid,qid) --validate values and create a link
local _makelink = function(id, val, n, qid) --validate values and create a link
local function tooltip(text,label)
local link = mw.html.create('span'):addClass('uid')
if label and label~='' then
if n==1 and id.prefix then --show prefix on primary value
return mw.getCurrentFrame():expandTemplate{title = "Tooltip", args = {text,label}}
link:wikitext(id.prefix .. ': ')
else
return text
end
end
local link
if nextid==1 then
if conf.prefix then
link = '*' .. conf.prefix .. '\n**'
else
link = '*'
end
else
link = '\n**'
end
end
local valid_value = false
local valid_value = false
if conf.customlink then -- use function to validate and generate link
if id.customlink then -- use function to validate and generate link
if conf.customlink(val.id) then
local label = n>1 and n
link = link .. conf.customlink(val.id)
local newlink = require(config.auxiliary)[id.customlink](val.id, label)
if newlink then
link:wikitext(newlink)
valid_value = true
valid_value = true
end
end
else
else
if conf.pattern then -- use pattern to determine validity if defined
if id.pattern then -- check pattern to determine validity
valid_value = string.match(val.id,conf.pattern)
valid_value = string.match(val.id, '^' .. id.pattern .. '$')
elseif conf.patterns then
elseif id.patterns then -- check multiple patterns to determine validity
for i = 1,#conf.patterns do
for _, pattern in ipairs(id.patterns) do
valid_value = val.id:match(conf.patterns[i])
valid_value = val.id:match('^' .. pattern .. '$')
if valid_value then break end
if valid_value then break end
end
end
elseif conf.valid then -- otherwise use function to determine validity
elseif id.valid then -- use function to determine validity
valid_value = conf.valid(val.id)
valid_value = require(config.auxiliary)[id.valid](val.id)
else -- no validation possible
else -- no validation possible
valid_value = val.id
valid_value = val.id
end
end
if valid_value then
if valid_value then
local label = id.label
if not label or n>1 then
label = tostring(n)
end
local newlink
local newlink
if not conf.label or nextid>1 then
if id.link then
conf.label = tostring(nextid)
end
if conf.link then
valid_value = valid_value:gsub('%%', '%%%%')
valid_value = valid_value:gsub('%%', '%%%%')
newlink = '[' .. mw.ustring.gsub(conf.link,'%$1',valid_value) .. ' ' .. conf.label .. ']'
newlink = '[' .. mw.ustring.gsub(id.link, '%$1', valid_value) .. ' ' .. label .. ']'
else
else
newlink = valid_value
newlink = valid_value
end
end
link = link .. '<span class="uid">'..tooltip(newlink,val.name)..'</span>'
link:wikitext(tooltip(newlink, val.name))
end
end
end
end
if valid_value then
if valid_value then
link = link .. getCatForId(conf.category or conf[1])
local cat = id.category and string.format(config.i18n.cat, id.category)
link:wikitext(addCat(cat))
else
else
--local preview = require("Module:If preview")
local wdlink = qid and wikilink(':wikidata:' .. qid .. '#P' .. id.property) or ''
local wdlink = qid and '[[:wikidata:' .. qid .. '#P' .. conf.property .. ']]' or ''
local _, name = p.getname(id.property)
link = link .. '[[File:345-409 Ambox warning centered.svg|20px|frameless|link=' .. wdlink .. '|The ' .. conf[1] .. ' id ' .. val.id .. ' is not valid.]]'
local tooltip = string.format(
if conf.errorcat then
config.i18n.idnotvalid,
link = link .. addCat(conf.errorcat)
name,
else
val.id
link = link .. getCatForId(conf.category or conf[1],true)
)
end
local cat = id.category and string.format(
link = link .. addCat('All articles with faulty authority control information',conf[1])-- .. preview._warning({'The '..conf[1]..' id '..val..' is not valid.'})
config.i18n.cat,
config.i18n.faulty .. ' ' .. id.category
)
link:wikitext(wikilink('File:' .. config.i18n.warningicon .. '|20px|frameless|link=' .. wdlink, tooltip .. '.'))
:wikitext(addCat(cat))
:wikitext(addCat(config.i18n.allfaultycat, name))
end
end
return link
return link
end
end


--[[==========================================================================]]
local _makelinks = function(id, qid)
--[[                                  Main                                  ]]
local getquals = function(statement, qualid)
--[[==========================================================================]]
if statement.qualifiers and statement.qualifiers['P'..qualid] then
function p.authorityControl(frame)
return mw.wikibase.renderSnak(statement.qualifiers['P'..qualid][1])
local function resolveQID(qid)
end
if qid then
end
qid = 'Q'..mw.ustring.gsub(qid, '^[Qq]', '')
local ids = {}
if mw.wikibase.isValidEntityId(qid) and mw.wikibase.entityExists(qid) then
if qid then
return qid
for _, statement in ipairs(mw.wikibase.getBestStatements(qid, 'P'..id.property)) do
if statement.mainsnak.datavalue then
local val = statement.mainsnak.datavalue.value
if val then
local namedas = getquals(statement, 1810) or getquals(statement, 742) or ''
table.insert(ids, {id=val, name=namedas})
end end end end
local links
if ids[1] then
links = mw.html.create('li'):node(_makelink(id, ids[1], 1, qid))
if ids[2] then
local sublinks = mw.html.create('ul')
for n = 2, #ids do
sublinks:tag('li'):node(_makelink(id, ids[n], n, qid)):done()
end
end
links:node(sublinks)
end
end
end
end
return links
end
--[[==================================]]
--[[              Main              ]]
--[[==================================]]
p.authorityControl = function(frame)
local resolveQID = function(qid)
if qid then
qid = 'Q' .. mw.ustring.gsub(qid, '^[Qq]', '')
if mw.wikibase.isValidEntityId(qid) and mw.wikibase.entityExists(qid) then
local sitelink = mw.wikibase.getSitelink(qid)
if sitelink then
return mw.wikibase.getEntityIdForTitle(sitelink) or mw.wikibase.getEntity(qid).id
end
return mw.wikibase.getEntity(qid).id
end end end
local conf = config.config
local conf = config.config
local parentArgs = frame:getParent().args
local parentArgs = frame:getParent().args
local auxCats = ''
local auxCats = ''
local rct = false -- boolean to track if there are any links to be returned
local rct = false -- boolean to track if there are any links to be returned
local qid,topic
local qid, topic
if namespace == 0 then
if namespace==0 then
qid = mw.wikibase.getEntityIdForCurrentPage()
qid = mw.wikibase.getEntityIdForCurrentPage()
end
end
if qid then -- article is connected to Wikidata item
if qid then -- article is connected to a Wikidata item
if parentArgs.qid and (parentArgs.qid ~= qid) then -- non-matching qid parameter
if parentArgs.qid and (resolveQID(parentArgs.qid) ~= qid) then -- non-matching qid parameter
auxCats = auxCats .. needsAttention('D')
auxCats = auxCats .. needsAttention('D')
end
end
Line 153: Line 190:
if qid then -- qid parameter is valid, set topic to display
if qid then -- qid parameter is valid, set topic to display
topic = mw.wikibase.getLabel(qid)
topic = mw.wikibase.getLabel(qid)
if topic and (mw.ustring.lower(title.subpageText) == mw.ustring.lower(topic)) then -- suppress topic display if subpagename equals topic up to case change
if topic then
topic = nil
if mw.ustring.lower(title.subpageText)==mw.ustring.lower(topic) then -- suppress topic display if subpagename equals topic up to case change
topic = nil
end
if topic and mw.wikibase.getSitelink(qid) then -- make wikilink to article
topic = wikilink(mw.wikibase.getSitelink(qid), topic)
end
else
auxCats = auxCats .. needsAttention('L')
end
end
elseif parentArgs.qid then -- invalid qid has been supplied, add to tracking cat
elseif parentArgs.qid and parentArgs.qid~='' then -- invalid qid has been supplied, add to tracking cat
auxCats = auxCats .. needsAttention('Q')
auxCats = auxCats .. needsAttention('Q')
end
end
end
end
local qids = {} -- setup any additional QIDs
local qids = {} -- setup any additional QIDs
if parentArgs.additional and parentArgs.additional ~= '' then
if parentArgs.additional=='auto' and qid then  -- check P527 for parts to add additional qids
for _,v in ipairs(mw.text.split(parentArgs.additional,"%s*,%s*")) do
local checkparts = function(property)
local parts = mw.wikibase.getBestStatements(qid, property)
if parts then
for _, part in ipairs(parts) do
if part.mainsnak.datavalue and part.mainsnak.datavalue.value.id then
local resolvedqid = resolveQID(part.mainsnak.datavalue.value.id)
if resolvedqid then
table.insert(qids,resolvedqid)
end end end end end
for _, part in ipairs(config.auto_additional) do
checkparts('P' .. part)
end
elseif parentArgs.additional and parentArgs.additional~='' then
for _, v in ipairs(mw.text.split(parentArgs.additional, '%s*,%s*')) do
v = resolveQID(v)
v = resolveQID(v)
if v == qid then -- duplicate of qid parameter
if v then
auxCats = auxCats .. needsAttention('R')
if v==qid then -- duplicate of qid parameter
auxCats = auxCats .. needsAttention('R')
end
table.insert(qids, v)
else -- invalid QID specified
auxCats = auxCats .. needsAttention('A')
end
end
table.insert(qids,v)
end
end
end
end


local numsections = 0
for _, _ in ipairs(config.sections) do -- count number of regular sections
numsections = numsections + 1
end
local sections = {}
local sections = {}
for _ = 1,#config.sectionNames + #qids do table.insert(sections,{}) end
for _ = 1, #qids+numsections do
local qslink = '' -- setup link to add using QuickStatements
table.insert(sections, {})
end


-- check which identifiers to show/suppress in template
-- check which identifiers to show/suppress in template
local show = {} -- setup list
local show, show_all_unsuppressed = {}, true
local showall = true
local stripP = function(pid) --strip P from property number
local function addshowlist(list)
if pid:match('^[Pp]%d+$') then
if list and list ~= '' then
pid = mw.ustring.gsub(pid, '[Pp]', '')
for _,v in ipairs(mw.text.split(string.lower(list),"%s*,%s*")) do
end
if config.whitelists[v] then
if pid:match('^%d+$') then
for _,w in ipairs(config.whitelists[v].properties) do
return tonumber(pid)
show[w] = true
end
end
end
showall = false
end
end
end
end
local addshowlist = function(list)
if list and list~='' then
for _, v in ipairs(mw.text.split(string.lower(list), '%s*,%s*')) do
local vprop = stripP(v)
if vprop then -- e.g. show=P214 to show one particular property
show[vprop] = true
else -- e.g. show=arts to use whitelist
if config.whitelists[v] then
for _, w in ipairs(config.whitelists[v].properties) do
show[w] = true
end end end end
show_all_unsuppressed = false
end end
addshowlist(frame.args.show) -- check show= parameter on wrapper template
addshowlist(frame.args.show) -- check show= parameter on wrapper template
addshowlist(parentArgs.show or parentArgs.country) -- check show parameter on article template
addshowlist(parentArgs.show) -- check show parameter on article
addshowlist(parentArgs.country) -- check country parameter on article
if parentArgs.suppress then
if parentArgs.suppress then
local suppresslist = mw.text.split(parentArgs.suppress,"%s*,%s*") -- split parameter by comma
local suppresslist = mw.text.split(parentArgs.suppress, '%s*,%s*') -- split parameter by comma
for _,v in ipairs(suppresslist) do
for _, v in ipairs(suppresslist) do
if v:match("^[Pp]%d+$") then
v = stripP(v)
v = mw.ustring.gsub(v,'[Pp]','') --strip P from property number
if v then
end
show[v] = false
if v:match("^%d+$") then
auxCats = auxCats .. wikilink(config.i18n.category .. ':' .. config.i18n.suppressedcat)
v = tonumber(v)
else
else
v = string.upper(v) -- convert to uppercase
auxCats = auxCats .. needsAttention('P')
end
end
show[v] = false
auxCats = auxCats .. '[[Category:Articles with suppressed authority control identifiers]]'
end
end
end
end
local function makeSections(qid,addit)
local makeSections = function(qid, addit)
local tval = {}
for _, id in ipairs(conf) do
local function parameter_is_used(property)
if id.suppressedbyproperty then
local used = false
for _, property in ipairs(id.suppressedbyproperty) do
if property then
if show[property]=='used' then -- property is in use
if tval[property] then
show[id.property] = false -- suppressed by another property
if tval[property][1] then
used = true
end
elseif tval[property] == false then -- property has been manually suppressed
used = true
end
end
return used
end
for _, params in ipairs(conf) do
tval[params.property] = getIdsFromWikidata(qid, 'P' .. params.property) -- setup table for values with property number as key
local showb = true
if (show[params.property] == nil) and (show[string.upper(params[1])] == nil ) then
showb = showall -- if not specified then depends on showall
elseif (show[params.property] == false) or (show[string.upper(params[1])] == false) then -- if either are false then id will be suppressed
showb = false
end
if not showb then
tval[params.property] = false -- indicates the identifier is suppressed
elseif not addit then
local val = parentArgs[mw.ustring.lower(params[1])] or parentArgs[params[1]]
if val and val ~= '' then -- add local parameter to list if not already in
local bnew = true
for _, w in pairs(tval[params.property]) do
if val == w.id then
bnew = false
end
end
if bnew then -- add new value to table
if qid then
qslink = qslink .. '%7C%7C' .. qid .. '%7CP' .. params.property .. '%7C%22' .. mw.uri.encode(val,"PATH") .. '%22%7CS143%7CQ328'
end
table.insert(tval[params.property],{id=val,name=''})
end
end
end
end
end
end
local suppress = false
if show[id.property]==nil then
if params.suppressedbyproperty then
show[id.property] = show_all_unsuppressed
for _,sc in ipairs(params.suppressedbyproperty) do
if parameter_is_used(sc) then
suppress = true
end
end
end
end
if tval[params.property] ~= false and not suppress then
if show[id.property] then
local tlinks = {} -- setup table for links
local links = _makelinks(id, qid)
local nextIdVal = 1
if links then
local row = ''
table.insert(
for _,val in ipairs(tval[params.property]) do
sections[addit or id.section],
local link = makelink(params,val,nextIdVal,qid)
links
row = row .. link
)
table.insert(tlinks,link)
show[id.property] = 'used'
nextIdVal = nextIdVal + 1
end
if nextIdVal>=2 then
row = row .. '\n'
table.insert(sections[addit or params.section],row)
rct = true
rct = true
end
end end end end
end
local pencil = function(qid)
end
if qid then
end
return require('Module:EditAtWikidata')._showMessage{
local function pencil(qid)
pid = 'identifiers',
if not qid then
qid = qid
}
else
return ''
return ''
end
end
local args = { pid = 'identifiers' } -- #target the list of identifiers
args.qid = qid
return require('Module:EditAtWikidata')._showMessage(args)
end
end


makeSections(qid,false)
makeSections(qid, false)
for c = 1,#qids do
for c = 1, #qids do
makeSections(qids[c],#config.sectionNames+c)
makeSections(qids[c], numsections+c)
end
end


Line 294: Line 322:
if rct then -- there is at least one link to display
if rct then -- there is at least one link to display
local Navbox = require('Module:Navbox')
local Navbox = require('Module:Navbox')
local sect,lastsect = 0,0
local sect, lastsect = 0, 0
local navboxArgs = {
local navboxArgs = {
name  = 'Authority control',
name  = 'Authority control',
navboxclass = 'authority-control',
navboxclass = 'authority-control',
bodyclass = 'hlist',
bodyclass = 'hlist',
state = parentArgs.state or 'autocollapse',
state = parentArgs.state or config.i18n.autocollapse,
navbar = 'off'
navbar = 'off'
}
}
for c=1,#config.sectionNames+#qids do
for c = 1, numsections+#qids do
if #sections[c] ~= 0 then -- section is non-empty
if #sections[c]>0 then -- section is non-empty
sect = sect + 1
sect = sect + 1
lastsect = c
lastsect = c
local sectname
local sectname
if c <= #config.sectionNames then -- regular section
if c<=numsections then -- regular section
sectname = config.sectionNames[c]
sectname = config.sections[c].name
else -- section from additional qid
else -- section from additional qid
sectname = mw.wikibase.getLabel(qids[c-#config.sectionNames]) .. pencil(qids[c-#config.sectionNames])
local qid = qids[c-numsections]
local label, sitelink = mw.wikibase.getLabel(qid), mw.wikibase.getSitelink(qid)
if label then
if sitelink then
local target = mw.title.new(sitelink)
if target==title or (target.isRedirect and target.redirectTarget==title) then -- do not link
sectname = label
else -- make wikilink to article
sectname = wikilink(sitelink, label)
end
else
sectname = label
end
else
auxCats = auxCats .. needsAttention('L')
sectname = qid
end
sectname = sectname .. pencil(qid)
end
end
navboxArgs['group' .. c] = sectname
navboxArgs['group' .. c] = sectname
navboxArgs['list' .. c] = table.concat(sections[c])
local list = mw.html.create('ul')
for _, link in ipairs(sections[c]) do
list:node(link)
end
navboxArgs['list' .. c] = tostring(list)
end
end
end
local aclink = '[[Help:Authority control|Authority control]]'
if qslink ~= '' then
qslink = '<span class="qs autoconfirmed-show">&#32;[[File:Commons to Wikidata QuickStatements.svg|20px|link=https://quickstatements.toolforge.org/#/v1=' .. qslink .. '|Add values to Wikidata.]]</span>'
end
end
if topic then -- display in expanded form with topic
if topic then -- display in expanded form with topic
navboxArgs.title = aclink .. ' &ndash; ' .. topic .. pencil(qid) .. qslink
navboxArgs.title = config.i18n.aclink .. ' &ndash; ' .. topic .. pencil(qid)
elseif sect == 1 then -- special display when only one section
elseif sect==1 then -- special display when only one section
if lastsect == 1 or lastsect == 8 then -- no special label when only general or other IDs are present
if lastsect<=numsections then
navboxArgs['group' .. lastsect] = aclink .. pencil(qid) .. qslink
if config.sections[lastsect].hidelabelwhenalone then -- no special label when only general or other IDs are present
elseif lastsect <= #config.sectionNames then -- other regular section
navboxArgs['group' .. lastsect] = config.i18n.aclink .. pencil(qid)
navboxArgs['group' .. lastsect] = aclink .. ': ' .. config.sectionNames[lastsect] .. pencil(qid) .. qslink
else -- other regular section
navboxArgs['group' .. lastsect] = config.i18n.aclink .. ': ' .. navboxArgs['group' .. lastsect] .. pencil(qid)
end
else -- section from additional qid
else -- section from additional qid
navboxArgs['group' .. lastsect] = aclink .. ': ' .. navboxArgs['group' .. lastsect] .. qslink
navboxArgs['group' .. lastsect] = config.i18n.aclink .. ': ' .. navboxArgs['group' .. lastsect]
end
end
else -- add title to navbox
else -- add title to navbox
navboxArgs.title = aclink .. pencil(qid) .. qslink
navboxArgs.title = config.i18n.aclink .. pencil(qid)
end
end
outString = Navbox._navbox(navboxArgs)
outString = Navbox._navbox(navboxArgs)
end
end


if parentArgs.state then
if parentArgs.state
if (parentArgs.state ~= 'collapsed') and (parentArgs.state ~= 'expanded') and (parentArgs.state ~= 'autocollapse') then --invalid state parameter
and parentArgs.state~=''
auxCats = auxCats .. needsAttention('S')
and parentArgs.state~=config.i18n.collapsed
end
and parentArgs.state~=config.i18n.expanded
and parentArgs.state~=config.i18n.autocollapse then --invalid state parameter
auxCats = auxCats .. needsAttention('S')
end
end
if testcases then
if testcases then
auxCats = mw.ustring.gsub(auxCats, '(%[%[)(Category)', '%1:%2') --for easier checking
auxCats = mw.ustring.gsub(auxCats, '(%[%[)(' .. config.i18n.category .. ')', '%1:%2') --for easier checking
end
end


--out
--out
outString = outString..auxCats
outString = outString .. auxCats
if namespace ~= 0 then
if namespace~=0 then
outString = mw.ustring.gsub(outString,'(%[%[)(Category:Articles)([^%|%]]+)%|?[^%|%]]*(%]%])','%1:%2%3%4')
outString = mw.ustring.gsub(outString, '(%[%[)(' .. config.i18n.category .. ':' .. config.i18n.Articles .. ')([^%|%]]+)%|?[^%|%]]*(%]%])','%1:%2%3%4')
outString = mw.ustring.gsub(outString,'(%[%[)(Category:All articles)([^%|%]]+)%|?[^%|%]]*(%]%])','%1:%2%3%4')
outString = mw.ustring.gsub(outString, '(%[%[)(' .. config.i18n.category .. ':' .. config.i18n.All_articles .. ')([^%|%]]+)%|?[^%|%]]*(%]%])','%1:%2%3%4')
end
end
local check = require('Module:Check for unknown parameters')._check
local check = require('Module:Check for unknown parameters')._check
local sortkey
local sortkey
if namespace == 0 then
if namespace==0 then
sortkey = '*' .. title.text
sortkey = '*' .. title.text
else
else
sortkey = title.fullText
sortkey = title.fullText
end
end
local tracking = check({
outString = outString .. check({
['unknown']='[[Category:Pages using authority control with parameters|' .. sortkey .. ']]',
['unknown'] = wikilink(config.i18n.category .. ':' .. config.i18n.pageswithparams, sortkey),
['preview']='Page using [[Template:Authority control]] with "_VALUE_", please move this to Wikidata.',
['preview'] = config.i18n.previewwarning, 'show', 'country', 'suppress', 'additional', 'qid', 'state'
'show', 'country', 'suppress', 'additional', 'qid', 'state'
}, parentArgs)
}, parentArgs)
if namespace == 0 -- mainspace
or namespace == 14 -- category
or namespace == 2 -- user
or namespace == 118 then -- draft
outString = outString .. tracking
end
return outString
return outString
end
end


-- Creates a human-readable standalone wikitable version of conf, and tracking categories with page counts, for use in the documentation
p.makelink = function(id, qid)
function p.docConfTable(frame)
return _makelinks(id, qid)
local count = frame.args.count or false
local wikiTable = '<table class="wikitable sortable">'..
  '<tr><th>Code</th>'..
  '<th>Identifier</th>'..
  '<th data-sort-type=number>Wikidata property</th>'..
  '<th>Section</th>'..
  '<th>Appears as</th>'
if count then
wikiTable = wikiTable .. '<th>[[:Category:Articles with authority control information|Articles]] ([[:Category:Articles with faulty authority control information|Faults]])</th>'
end
wikiTable = wikiTable .. '</tr>'
local columns = 4 + (count and 1 or 0)
local lang = mw.getContentLanguage()
local a, P, f = 0, 0, 0 --cumulative sums
local getlink = require("Module:Wikidata table")._getLink
local function checkcat(category,label)
local ret='[[:Category:'..category..'|'..label..']]'
if mw.title.new(category,14).exists == false then
ret = ret..' <span class="plainlinks" style="font-size:85%;">&#91;['..tostring(mw.uri.fullUrl('Category:'..category,'action=edit&preload=Template:Authority_control/preload'))..' create]&#93;</span>'
end
return ret
end
for _, conf in pairs(config.config) do
local category = conf.category or conf[1]
local articleCat = 'Articles with '..category..' identifiers'
local articleCount = mw.site.stats.pagesInCategory(articleCat,'pages')
local errorCat = conf.errorcat or 'Articles with faulty '..(conf.category or conf[1])..' identifiers'
local errorCount =  mw.site.stats.pagesInCategory(errorCat,'pages')
P = P + 1 --property count
a = a + articleCount
f = f + errorCount
local example = mw.wikibase.getBestStatements('P'..conf.property,'P1855') or ''
if example then
example = example[1].qualifiers['P'..conf.property][1].datavalue.value
example = mw.getCurrentFrame():expandTemplate{title = "Hlist", args = {'\n' .. makelink(conf,example,1)}} .. '\n'
end
local name = mw.wikibase.getBestStatements('P'..conf.property,"P1629")
if name and name[1] and name[1].mainsnak.datavalue.value.id then
name = getlink(name[1].mainsnak.datavalue.value.id)
else
name = ''
end
if conf.remark then
wikiTable = wikiTable..'<tr><td rowspan=2>'
else
wikiTable = wikiTable..'<tr><td>'
end
wikiTable = wikiTable .. '[[' .. conf[1] .. ' (identifier)' .. '|' .. conf[1] .. ']]</td>'
wikiTable = wikiTable..'<td>'.. name .. '</td>' ..
'<td data-sort-value=' .. conf.property .. '>' .. frame:expandTemplate{title='Wikidata property link',args={id='f',conf.property}} .. '</td>' ..
'<td>' .. config.sectionNames[conf.section]..'</td>' ..
'<td>' .. example .. '</td>'
if count then
wikiTable = wikiTable .. '<td style="text-align: right;">'..checkcat(articleCat,lang:formatNum(articleCount))..' ('..checkcat(errorCat,errorCount)..')</td>'
end
wikiTable = wikiTable .. '</tr>'
if conf.remark then
wikiTable = wikiTable .. "<tr><td colspan=" .. columns .. ">'''Remarks:''' "..conf.remark .. "</td></tr>"
end
end
if count then
wikiTable = wikiTable .. '<tr><th style="text-align: right;" colspan=' .. columns-1 .. '>Totals</th>' ..
'<th style="text-align: right;">' .. P .. '</th>' ..
'<th style="text-align: right;">' .. lang:formatNum(a) .. ' ([[:Category:All articles with faulty authority control information|' .. f .. ']])</th></tr>'
end
wikiTable = wikiTable .. '</table>'
return require('Module:Suppress categories').main(wikiTable)
end
 
function p.errorTable(frame)
local Table = '<table class="wikitable sortable">'..
  '<tr><th>Code</th>'..
  '<th>Wikidata property</th>'..
  '<th>Faulty IDs</th>'..
  '<th>[[:Category:Articles with faulty authority control information|Tracking category]]</th></tr>'
local f, P = 0, 0, 0 --cumulative sums
for _, conf in pairs(config.config) do
local category = conf.errorcat or 'Articles with faulty '..(conf.category or conf[1])..' identifiers'
local count =  mw.site.stats.pagesInCategory(category,'pages')
if count > 0 then
P = P + 1
f = f + count
Table = Table..'<tr><th>[['..(conf.idlink or conf[1]..' (identifier)')..'|'..conf[1]..']]</th>'..
'<td>'..frame:expandTemplate{ title = 'Wikidata property link', args = { id = 'f', conf.property } } .. '</td>'..
'<td style="text-align:center;">'..tostring(count)..'</td>'..
'<td>[[:Category:'..category..']]</td></tr>'
end
end
Table = Table..'<tr><th colspan=2 style="text-align: right;">Totals</th>'..
'<th style="text-align:center;">' .. '[[:Category:All articles with faulty authority control information|' .. tostring(f) .. ']]</th>'..
'<th style="text-align:center;">'..tostring(P)..'</th></tr></table>'
return Table
end
 
function p.whitelisttable(frame)
local Table = '<table class="wikitable sortable">'..
  '<tr><th>Code</th>'..
  '<th>Topic</th>'..
  '<th>Identifiers</th></tr>'
for code, wlist in pairs(config.whitelists) do
Table = Table .. '<tr><th>' .. code .. '</th>'..
'<td>[[' .. mw.wikibase.getSitelink('Q' .. wlist.topic) .. ']]</td>'
local plist = {}
for _, property in pairs(wlist.properties) do
table.insert(plist,frame:expandTemplate{title='Wikidata property link', args={'P' .. property}})
end
Table = Table .. '<td>' .. table.concat(plist,', ') .. '</td></tr>'
end
Table = Table .. '</table>'
return Table
end
 
function p.sectiontable(frame)
local Table = '<table class="wikitable sortable">'..
  '<tr><th>Section</th>'..
  '<th>Description</th>'..
  '<th>Identifiers</th></tr>'
for number,section in ipairs(config.sectionNames) do
Table = Table .. '<tr><th>' .. number .. '</th>' .. '<td>' .. section .. '</td>'
local plist = {}
for _,id in pairs(config.config) do
if id.section == number then
table.insert(plist,frame:expandTemplate{title='Wikidata property link', args={'P' .. id.property}})
end
end
Table = Table .. '<td>' .. table.concat(plist,', ') .. '</td></tr>'
end
Table = Table .. '</table>'
return Table
end
 
-- Main/External Call for Pages with authority control identifiers
function p.autoDetect( frame )
local function whichTOC( frame ) -- standardize TOC behavior via {{CatAutoTOC}}
return frame:expandTemplate{ title = 'CatAutoTOC', args = { align = 'center' } }
end
local ac_conf = require('Module:Authority control/config').config
local rmCats = require('Module:Suppress categories').main
--For use in [[Category:Articles with faulty authority control information]], i.e. on [[Category:Articles with faulty VIAF identifiers]]
local function wpfaulty( frame, id )
for _, conf in pairs(ac_conf) do
if conf.category == id or conf[1] == id then
local outString = frame:expandTemplate{ title = 'Cat more', args = {'Wikipedia:Authority control', conf.idlink or conf[1]..' (identifier)', ':d:Property:P'..conf.property} }
.. frame:expandTemplate{ title = 'Possibly empty category' }
.. frame:expandTemplate{ title = 'Wikipedia category', args = { hidden = 'yes', tracking = 'yes' } }
.. frame:expandTemplate{ title = 'Polluted category' }
.. whichTOC( frame )
.. '\nPages in this category should only be added by [[Module:Authority control]].'
.. addCat('Articles with '..id..' identifiers')
.. addCat('Articles with faulty authority control information',id)
return outString
end
end
return ''
end
--For use in [[Category:Articles with authority control information]], i.e. on [[Category:Articles with VIAF identifiers]]
local function wp(frame,id )
for _, conf in pairs( ac_conf ) do
if conf.category == id or conf[1] == id then
local link = '[[' .. (conf.idlink or conf[1] .. ' (identifier)') .. '|' .. conf[1] .. ']]'
local outString = frame:expandTemplate{ title = 'Category explanation', args = {'articles with '..link..' identifiers.'..' Please do not add [[Wikipedia:Categorization#Subcategorization|subcategories]].'} }
.. frame:expandTemplate{ title = 'Cat more', args = {'Wikipedia:Authority control', ':d:Property:P'..conf.property} }
.. frame:expandTemplate{ title = 'Possibly empty category' }
.. frame:expandTemplate{ title = 'Wikipedia category', args = { hidden = 'yes', tracking = 'yes' } }
.. whichTOC( frame )
.. '\nPages in this category should only be added by [[Module:Authority control]].'
.. addCat('Articles with authority control information',id)
return outString
end
end
return ''
end
if namespace == 14 then --cat space
local wpfaultyID = mw.ustring.match(title.text, 'Articles with faulty ([%w%.%- ]+) identifiers')
local wpID      = mw.ustring.match(title.text, 'Articles with ([%w%.%- ]+) identifiers')
if wpfaultyID then
return wpfaulty(frame,wpfaultyID)-- must be before wpID check, in case they both match
elseif wpID then
return wp(frame, wpID)-- to keep the regex simple
else
return needsAttention('U')
end
end
return ''
end
end


return p
return p

Latest revision as of 11:42, 2 September 2024

-- require('strict')
local p = {}
local frame = mw.getCurrentFrame()
local config_file = frame.args.config and frame.args.config~='' and ('/' .. frame.args.config) or ''
local config = mw.loadData('Module:Authority control/config' .. config_file)
local title = mw.title.getCurrentTitle()
local namespace = title.namespace
local testcases = title.subpageText == config.i18n.testcases

local wikilink = function(target, label)
	return label and '[[' .. target .. '|' .. label .. ']]' or '[[' .. target .. ']]'
end

local needsAttention = function(sortkey)
	return wikilink(config.i18n.category .. ':' .. config.i18n.attentioncat, sortkey .. title.text)
end

local addCat = function(cat, sortkey)
	if cat and cat~='' and (namespace==0 or namespace==14 or testcases) then
		local redlinkcat = ''
		if testcases==false then
			local success, exists = pcall(function() return mw.title.new(cat, 14).exists end)
			if success and not exists then 
				redlinkcat = needsAttention('N')
			end
		end
		return wikilink(config.i18n.category..':'..cat, sortkey and sortkey..title.text) .. redlinkcat
	else
		return ''
	end
end

local tooltip = function(text, label)
	if label and label~='' then
		return frame:expandTemplate{
			title = 'Tooltip',
			args = {text, label}
		}
	else
		return text
	end
end

local getstatement = function(id, propid)
	local statement = mw.wikibase.getBestStatements('P' .. id, 'P' .. propid)
	local value
	if statement and statement[1] and statement[1].mainsnak.datavalue.value.id then
		value = statement[1].mainsnak.datavalue.value.id
		return value
	end
end
p.getname = function(property) -- function to lookup the name of a property and provide a link if one exists
	local item
	for _, propnameqid in ipairs(config.property_items) do
		item = getstatement(property, propnameqid)
		if item then break end
	end
	if item then
		local link = frame:expandTemplate{
			title = 'Wikidata fallback link',
			args = {item}
		}
		local raw = mw.wikibase.getLabel(item)
		return link, raw
	else
		return ''
	end
end

local _makelink = function(id, val, n, qid) --validate values and create a link
	local link = mw.html.create('span'):addClass('uid')
	if n==1 and id.prefix then --show prefix on primary value
		link:wikitext(id.prefix .. ': ')
	end
	local valid_value = false
	if id.customlink then -- use function to validate and generate link
		local label = n>1 and n
		local newlink = require(config.auxiliary)[id.customlink](val.id, label)
		if newlink then
			link:wikitext(newlink)
			valid_value = true
		end
	else
		if id.pattern then -- check pattern to determine validity
			valid_value = string.match(val.id, '^' .. id.pattern .. '$')
		elseif id.patterns then -- check multiple patterns to determine validity
			for _, pattern in ipairs(id.patterns) do
				valid_value = val.id:match('^' .. pattern .. '$')
				if valid_value then break end
			end
		elseif id.valid then -- use function to determine validity
			valid_value = require(config.auxiliary)[id.valid](val.id)
		else -- no validation possible
			valid_value = val.id
		end
		if valid_value then
			local label = id.label
			if not label or n>1 then
				label = tostring(n)
			end
			local newlink
			if id.link then
				valid_value = valid_value:gsub('%%', '%%%%')
				newlink = '[' .. mw.ustring.gsub(id.link, '%$1', valid_value) .. ' ' .. label .. ']'
			else
				newlink = valid_value
			end
			link:wikitext(tooltip(newlink, val.name))
		end
	end
	if valid_value then
		local cat =  id.category and string.format(config.i18n.cat, id.category)
		link:wikitext(addCat(cat))
	else
		local wdlink = qid and wikilink(':wikidata:' .. qid .. '#P' .. id.property) or ''
		local _, name = p.getname(id.property)
		local tooltip = string.format(
			config.i18n.idnotvalid,
			name,
			val.id
		)
		local cat = id.category and string.format(
			config.i18n.cat,
			config.i18n.faulty .. ' ' .. id.category
		)
		link:wikitext(wikilink('File:' .. config.i18n.warningicon .. '|20px|frameless|link=' .. wdlink, tooltip .. '.'))
			:wikitext(addCat(cat))
			:wikitext(addCat(config.i18n.allfaultycat, name))
	end
	return link
end

local _makelinks = function(id, qid)
	local getquals = function(statement, qualid)
		if statement.qualifiers and statement.qualifiers['P'..qualid] then
			return mw.wikibase.renderSnak(statement.qualifiers['P'..qualid][1])
		end
	end
	local ids = {}
	if qid then
		for _, statement in ipairs(mw.wikibase.getBestStatements(qid, 'P'..id.property)) do
			if statement.mainsnak.datavalue then
				local val = statement.mainsnak.datavalue.value
				if val then
					local namedas = getquals(statement, 1810) or getquals(statement, 742) or ''
					table.insert(ids, {id=val, name=namedas})
	end end end end
	local links
	if ids[1] then
		links = mw.html.create('li'):node(_makelink(id, ids[1], 1, qid))
		if ids[2] then
			local sublinks = mw.html.create('ul')
			for n = 2, #ids do
				sublinks:tag('li'):node(_makelink(id, ids[n], n, qid)):done()
			end
			links:node(sublinks)
		end
	end
	return links
end

--[[==================================]]
--[[               Main               ]]
--[[==================================]]
p.authorityControl = function(frame)
	local resolveQID = function(qid)
		if qid then
			qid = 'Q' .. mw.ustring.gsub(qid, '^[Qq]', '')
			if mw.wikibase.isValidEntityId(qid) and mw.wikibase.entityExists(qid) then
				local sitelink = mw.wikibase.getSitelink(qid)
				if sitelink then
					return mw.wikibase.getEntityIdForTitle(sitelink) or mw.wikibase.getEntity(qid).id
				end
				return mw.wikibase.getEntity(qid).id
	end end end
	local conf = config.config
	local parentArgs = frame:getParent().args
	local auxCats = ''
	local rct = false -- boolean to track if there are any links to be returned
	local qid, topic
	if namespace==0 then
		qid = mw.wikibase.getEntityIdForCurrentPage()
	end
	if qid then -- article is connected to a Wikidata item
		if parentArgs.qid and (resolveQID(parentArgs.qid) ~= qid) then -- non-matching qid parameter
			auxCats = auxCats .. needsAttention('D')
		end
	else -- page is not connected to any Wikidata item
		qid = resolveQID(parentArgs.qid) -- check qid parameter if no wikidata item is connected
		if qid then -- qid parameter is valid, set topic to display
			topic = mw.wikibase.getLabel(qid)
			if topic then
				if mw.ustring.lower(title.subpageText)==mw.ustring.lower(topic) then -- suppress topic display if subpagename equals topic up to case change
					topic = nil
				end
				if topic and mw.wikibase.getSitelink(qid) then -- make wikilink to article
					topic = wikilink(mw.wikibase.getSitelink(qid), topic)
				end
			else
				auxCats = auxCats .. needsAttention('L')
			end
		elseif parentArgs.qid and parentArgs.qid~='' then -- invalid qid has been supplied, add to tracking cat
			auxCats = auxCats .. needsAttention('Q')
		end
	end
	local qids = {} -- setup any additional QIDs
	if parentArgs.additional=='auto' and qid then  -- check P527 for parts to add additional qids
		local checkparts = function(property)
			local parts = mw.wikibase.getBestStatements(qid, property)
			if parts then
				for _, part in ipairs(parts) do
					if part.mainsnak.datavalue and part.mainsnak.datavalue.value.id then
						local resolvedqid = resolveQID(part.mainsnak.datavalue.value.id)
						if resolvedqid then
							table.insert(qids,resolvedqid)
		end end end end end
		for _, part in ipairs(config.auto_additional) do
			checkparts('P' .. part)
		end
	elseif parentArgs.additional and parentArgs.additional~='' then
		for _, v in ipairs(mw.text.split(parentArgs.additional, '%s*,%s*')) do
			v = resolveQID(v)
			if v then
				if v==qid then -- duplicate of qid parameter
					auxCats = auxCats .. needsAttention('R')
				end
				table.insert(qids, v)
			else -- invalid QID specified
				auxCats = auxCats .. needsAttention('A')
			end
		end
	end

	local numsections = 0
	for _, _ in ipairs(config.sections) do -- count number of regular sections
		numsections = numsections + 1
	end
	local sections = {}
	for _ = 1, #qids+numsections do
		table.insert(sections, {})
	end

	-- check which identifiers to show/suppress in template
	local show, show_all_unsuppressed = {}, true
	local stripP = function(pid) --strip P from property number
		if pid:match('^[Pp]%d+$') then
			pid = mw.ustring.gsub(pid, '[Pp]', '')
		end
		if pid:match('^%d+$') then
			return tonumber(pid)
		end
	end
	local addshowlist = function(list)
		if list and list~='' then
			for _, v in ipairs(mw.text.split(string.lower(list), '%s*,%s*')) do
				local vprop = stripP(v)
				if vprop then -- e.g. show=P214 to show one particular property
					show[vprop] = true
				else -- e.g. show=arts to use whitelist
					if config.whitelists[v] then
						for _, w in ipairs(config.whitelists[v].properties) do
							show[w] = true
			end end end end
			show_all_unsuppressed = false
	end end
	addshowlist(frame.args.show) -- check show= parameter on wrapper template
	addshowlist(parentArgs.show) -- check show parameter on article
	addshowlist(parentArgs.country) -- check country parameter on article
	if parentArgs.suppress then
		local suppresslist = mw.text.split(parentArgs.suppress, '%s*,%s*') -- split parameter by comma
		for _, v in ipairs(suppresslist) do
			v = stripP(v)
			if v then
				show[v] = false
				auxCats = auxCats .. wikilink(config.i18n.category .. ':' .. config.i18n.suppressedcat)
			else
				auxCats = auxCats .. needsAttention('P')
			end
		end
	end
	
	local makeSections = function(qid, addit)
		for _, id in ipairs(conf) do
			if id.suppressedbyproperty then
				for _, property in ipairs(id.suppressedbyproperty) do
					if show[property]=='used' then -- property is in use
						show[id.property] = false -- suppressed by another property
					end
				end
			end
			if show[id.property]==nil then
				show[id.property] = show_all_unsuppressed
			end
			if show[id.property] then
				local links = _makelinks(id, qid)
				if links then
					table.insert(
						sections[addit or id.section],
						links
					)
					show[id.property] = 'used'
					rct = true
	end end end end
	local pencil = function(qid)
		if qid then
			return require('Module:EditAtWikidata')._showMessage{
				pid = 'identifiers',
				qid = qid
			}
		else
			return ''
		end
	end

	makeSections(qid, false)
	for c = 1, #qids do
		makeSections(qids[c], numsections+c)
	end

	--configure Navbox
	local outString = ''
	if rct then -- there is at least one link to display
		local Navbox = require('Module:Navbox')
		local sect, lastsect = 0, 0
		local navboxArgs = {
			name  = 'Authority control',
			navboxclass = 'authority-control',
			bodyclass = 'hlist',
			state = parentArgs.state or config.i18n.autocollapse,
			navbar = 'off'
		}
		for c = 1, numsections+#qids do
			if #sections[c]>0 then -- section is non-empty
				sect = sect + 1
				lastsect = c
				local sectname
				if c<=numsections then -- regular section
					sectname = config.sections[c].name
				else -- section from additional qid
					local qid = qids[c-numsections]
					local label, sitelink = mw.wikibase.getLabel(qid), mw.wikibase.getSitelink(qid)
					if label then
						if sitelink then
							local target = mw.title.new(sitelink)
							if target==title or (target.isRedirect and target.redirectTarget==title) then -- do not link
								sectname = label
							else -- make wikilink to article
								sectname = wikilink(sitelink, label)
							end
						else
							sectname = label
						end
					else
						auxCats = auxCats .. needsAttention('L')
						sectname = qid
					end
					sectname = sectname .. pencil(qid)
				end
				navboxArgs['group' .. c] = sectname
				local list = mw.html.create('ul')
				for _, link in ipairs(sections[c]) do
					list:node(link)
				end
				navboxArgs['list' .. c] = tostring(list)
			end
		end
		if topic then -- display in expanded form with topic
			navboxArgs.title = config.i18n.aclink .. ' &ndash; ' .. topic .. pencil(qid)
		elseif sect==1 then -- special display when only one section
			if lastsect<=numsections then
				if config.sections[lastsect].hidelabelwhenalone then -- no special label when only general or other IDs are present
					navboxArgs['group' .. lastsect] = config.i18n.aclink .. pencil(qid)
				else -- other regular section
					navboxArgs['group' .. lastsect] = config.i18n.aclink .. ': ' .. navboxArgs['group' .. lastsect] .. pencil(qid)
				end
			else -- section from additional qid
				navboxArgs['group' .. lastsect] = config.i18n.aclink .. ': ' .. navboxArgs['group' .. lastsect]
			end
		else -- add title to navbox
			navboxArgs.title = config.i18n.aclink .. pencil(qid)
		end
		outString = Navbox._navbox(navboxArgs)
	end

	if parentArgs.state
		and parentArgs.state~=''
		and parentArgs.state~=config.i18n.collapsed
		and parentArgs.state~=config.i18n.expanded
		and parentArgs.state~=config.i18n.autocollapse then --invalid state parameter
		auxCats = auxCats .. needsAttention('S')
	end
	if testcases then
		auxCats = mw.ustring.gsub(auxCats, '(%[%[)(' .. config.i18n.category .. ')', '%1:%2') --for easier checking
	end

	--out
	outString = outString .. auxCats
	if namespace~=0 then
		outString = mw.ustring.gsub(outString, '(%[%[)(' .. config.i18n.category .. ':' .. config.i18n.Articles .. ')([^%|%]]+)%|?[^%|%]]*(%]%])','%1:%2%3%4')
		outString = mw.ustring.gsub(outString, '(%[%[)(' .. config.i18n.category .. ':' .. config.i18n.All_articles .. ')([^%|%]]+)%|?[^%|%]]*(%]%])','%1:%2%3%4')
	end
	local check = require('Module:Check for unknown parameters')._check
	local sortkey
	if namespace==0 then
		sortkey = '*' .. title.text
	else
		sortkey = title.fullText
	end
	outString = outString .. check({
		['unknown'] = wikilink(config.i18n.category .. ':' .. config.i18n.pageswithparams, sortkey),
		['preview'] = config.i18n.previewwarning, 'show', 'country', 'suppress', 'additional', 'qid', 'state'
		}, parentArgs)
	return outString
end

p.makelink = function(id, qid)
	return _makelinks(id, qid)
end

return p