Module:Authority control: Difference between revisions

From The Goon Show Depository

en>MSGJ
(major rewrite for efficiency)
No edit summary
 
(56 intermediate revisions by 4 users not shown)
Line 1: Line 1:
require('strict')
-- require('strict')
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 addCat(cat)
local wikilink = function(target, label)
if cat and cat ~= '' then
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 = ''
local redlinkcat = ''
if testcases == false and mw.title.new(cat, 14).exists == false then
if testcases==false then
redlinkcat = '[[Category:Pages with red-linked authority control categories]]'
local success, exists = pcall(function() return mw.title.new(cat, 14).exists end)
if success and not exists then  
redlinkcat = needsAttention('N')
end
end
end
return '[[Category:'..cat..']]'..redlinkcat
return wikilink(config.i18n.category..':'..cat, sortkey and sortkey..title.text) .. redlinkcat
else
else
return ''
return ''
Line 17: Line 31:
end
end


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


local function getIdsFromWikidata(itemId,property)
local getstatement = function(id, propid)
local ids = {}
local statement = mw.wikibase.getBestStatements('P' .. id, 'P' .. propid)
if not mw.wikibase then
local value
return ids
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
end
local statements = mw.wikibase.getBestStatements( itemId, property )
if item then
if statements then
local link = frame:expandTemplate{
for _, statement in ipairs( statements ) do
title = 'Wikidata fallback link',
if statement.mainsnak.datavalue then
args = {item}
table.insert( ids, statement.mainsnak.datavalue.value )
}
end
local raw = mw.wikibase.getLabel(item)
end
return link, raw
else
return ''
end
end
return ids
end
end


local function makelink(conf,val,nextid) --validate values and create a link
local _makelink = function(id, val, n, qid) --validate values and create a link
local link
local link = mw.html.create('span'):addClass('uid')
if conf.link2 then -- use function to validate and generate link
if n==1 and id.prefix then --show prefix on primary value
link = conf.link2(val)
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
else
local valid_value
if id.pattern then -- check pattern to determine validity
if conf.pattern then -- use pattern to determine validity if defined
valid_value = string.match(val.id, '^' .. id.pattern .. '$')
valid_value = val:match(conf.pattern)
elseif id.patterns then -- check multiple patterns to determine validity
elseif conf.patterns then
for _, pattern in ipairs(id.patterns) do
for i = 1,#conf.patterns do
valid_value = val.id:match('^' .. pattern .. '$')
valid_value = val:match(conf.patterns[i])
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)
valid_value = require(config.auxiliary)[id.valid](val.id)
else -- no validation possible
else -- no validation possible
valid_value = val
valid_value = val.id
end
end
if valid_value then
if valid_value then
local label = conf.label
local label = id.label
if not label or nextid>1 then
if not label or n>1 then
label = tostring(nextid)
label = tostring(n)
end
end
if conf.link then
local newlink
link = '[' .. mw.ustring.gsub(conf.link,'%$1',valid_value) .. ' ' .. label .. ']'
if id.link then
valid_value = valid_value:gsub('%%', '%%%%')
newlink = '[' .. mw.ustring.gsub(id.link, '%$1', valid_value) .. ' ' .. label .. ']'
else
else
link = valid_value
newlink = valid_value
end
end
else
link:wikitext(tooltip(newlink, val.name))
link = false
end
end
end
end
if link then
if valid_value then
link = '<span class="uid">'..link..'</span>'
local cat = id.category and string.format(config.i18n.cat, id.category)
link:wikitext(addCat(cat))
else
else
local faultyCat = 'Articles with faulty '..(conf.errorcat or conf.cat or conf[1])..' identifiers'
local wdlink = qid and wikilink(':wikidata:' .. qid .. '#P' .. id.property) or ''
link = '<span class="error">The '..conf[1]..' id '..val..' is not valid.</span>'..addCat(faultyCat)
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
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
 
return mw.wikibase.renderSnak(statement.qualifiers['P'..qualid][1])
function p.authorityControl( frame )
local config = require("Module:Authority control/config")
local conf = config.config
local aliases = config.aliases
local deprecated = config.deprecated
local resolveEntity = require( 'Module:ResolveEntityId' )
local parentArgs = frame:getParent().args --WD IDs added here later
local iParentArgs = 0 --count original/manual parent args only later
local worldcatCat = ''
local elementsCat = ''
local multipleIdCat = ''
local suppressedIdCat = ''
local suppressedIdCatArts = ''
local deprecatedIdCat = ''
local differentOnWDCat = ''
local sameOnWDCat = ''
local stateCat = ''
 
--redirect aliases to proper parameter names
for _, a in pairs(aliases) do
local alias, param = a[1], a[2]
if (parentArgs[param] == nil or parentArgs[param] == '') and parentArgs[alias] then
parentArgs[param] = parentArgs[alias]
end
end
end
end
 
local ids = {}
--redirect deprecated parameters to proper parameter names, and assign tracking cat
if qid then
for _, d in pairs( deprecated ) do
for _, statement in ipairs(mw.wikibase.getBestStatements(qid, 'P'..id.property)) do
local dep, param = d[1], d[2]
if statement.mainsnak.datavalue then
if (parentArgs[param] == nil or parentArgs[param] == '') and parentArgs[dep] then
local val = statement.mainsnak.datavalue.value
parentArgs[param] = parentArgs[dep]
if val then
if namespace == 0 then
local namedas = getquals(statement, 1810) or getquals(statement, 742) or ''
deprecatedIdCat = '[[Category:Articles with deprecated authority control identifiers|'..dep..']]'
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


--use QID= parameter for testing/example purposes only
--[[==================================]]
local itemId = nil
--[[              Main              ]]
if namespace ~= 0 then
--[[==================================]]
local qid = parentArgs['qid'] or parentArgs['QID']
p.authorityControl = function(frame)
local resolveQID = function(qid)
if qid then
if qid then
itemId = 'Q'..mw.ustring.gsub(qid, '^[Qq]', '')
qid = 'Q' .. mw.ustring.gsub(qid, '^[Qq]', '')
itemId = resolveEntity._id(itemId) --nil if unresolvable
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
end
elseif mw.wikibase then
else -- page is not connected to any Wikidata item
itemId = mw.wikibase.getEntityIdForCurrentPage()
qid = resolveQID(parentArgs.qid) -- check qid parameter if no wikidata item is connected
end
if qid then -- qid parameter is valid, set topic to display
 
topic = mw.wikibase.getLabel(qid)
--configure rows
if topic then
local rct = 0
if mw.ustring.lower(title.subpageText)==mw.ustring.lower(topic) then -- suppress topic display if subpagename equals topic up to case change
local sectionOrder = config.sectionOrder
topic = nil
local sections = {{},{},{},{},{},{},{},{}}
end
if itemId then
if topic and mw.wikibase.getSitelink(qid) then -- make wikilink to article
local suppressedIdCount = 0
topic = wikilink(mw.wikibase.getSitelink(qid), topic)
local iMatches = 0
for _, params in ipairs(conf) do
local val = parentArgs[mw.ustring.lower(params[1])] or parentArgs[params[1]]
local wikidataIds = getIdsFromWikidata(itemId,'P'..params.property)
if val == nil or val == '' then
if wikidataIds[1] then
if val == '' and (namespace == 0 or testcases) then
suppressedIdCount = suppressedIdCount + 1
suppressedIdCat = '[[Category:Articles with suppressed authority control identifiers|'..params[1]..']]'
end
end
end
else
else
iParentArgs = iParentArgs + 1
auxCats = auxCats .. needsAttention('L')
if wikidataIds[1] and differentOnWDCat == '' then
local bMatch = false
for _, wd in pairs( wikidataIds ) do
if val == wd then
iMatches = iMatches + 1
bMatch = true
end
end
if bMatch == false then
differentOnWDCat = '[[Category:Pages using authority control with parameters different on Wikidata|'..params[1]..']]'
end
end
end
end
elseif parentArgs.qid and parentArgs.qid~='' then -- invalid qid has been supplied, add to tracking cat
auxCats = auxCats .. needsAttention('Q')
end
end
if iMatches > 0 and iMatches == iParentArgs then
end
sameOnWDCat = '[[Category:Pages using authority control with parameters all matching Wikidata]]'
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
end
if parentArgs['arts'] == 'arts' and suppressedIdCount > 0 then
elseif parentArgs.additional and parentArgs.additional~='' then
if namespace == 0 or testcases then
for _, v in ipairs(mw.text.split(parentArgs.additional, '%s*,%s*')) do
local s = 's'
v = resolveQID(v)
if suppressedIdCount == 1 then s = '' end
if v then
local sCat = 'ACArt with '..suppressedIdCount..' suppressed element'..s
if v==qid then -- duplicate of qid parameter
suppressedIdCatArts = addCat(sCat)
auxCats = auxCats .. needsAttention('R')
end
table.insert(qids, v)
else -- invalid QID specified
auxCats = auxCats .. needsAttention('A')
end
end
end
end
end
end
local tval = {}
 
local function parameter_is_used(property)
local numsections = 0
local used = false
for _, _ in ipairs(config.sections) do -- count number of regular sections
if property then
numsections = numsections + 1
if tval[property] then
end
if tval[property][1] then
local sections = {}
used = true
for _ = 1, #qids+numsections do
end
table.insert(sections, {})
end
end
return used
end
end
for _, params in ipairs(conf) do
 
local wikidataIds = {}
-- check which identifiers to show/suppress in template
if itemId then
local show, show_all_unsuppressed = {}, true
wikidataIds = getIdsFromWikidata(itemId, 'P' .. params.property)
local stripP = function(pid) --strip P from property number
if pid:match('^[Pp]%d+$') then
pid = mw.ustring.gsub(pid, '[Pp]', '')
end
end
local val = parentArgs[mw.ustring.lower(params[1])] or parentArgs[params[1]]
if pid:match('^%d+$') then
local suppress = false
return tonumber(pid)
if val then
if val == '' then
suppress = true
else -- add local parameter to wikidata IDs
table.insert( wikidataIds, val)
end
end
end
if params.suppressedbyproperty then
end
for _,sc in ipairs(params.suppressedbyproperty) do
local addshowlist = function(list)
if parameter_is_used(sc) then
if list and list~='' then
suppress = true
for _, v in ipairs(mw.text.split(string.lower(list), '%s*,%s*')) do
end
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
end
if not suppress then
end
tval[params.property] = {} -- setup table for values with property number as key
local tlinks = {} -- setup table for links
local makeSections = function(qid, addit)
local nextIdVal = 1
for _, id in ipairs(conf) do
for _, val in pairs(wikidataIds) do
if id.suppressedbyproperty then
local bnew = true
for _, property in ipairs(id.suppressedbyproperty) do
for _, w in pairs( tval[params.property] ) do
if show[property]=='used' then -- property is in use
if val == w then
show[id.property] = false -- suppressed by another property
bnew = false
end
end
end
if bnew then -- add new value to table
table.insert(tval[params.property],val)
local link = makelink(params,val,nextIdVal)
local cat = params.cat or params[1]
if link then -- add category unless link==false
link = link .. getCatForId(cat)
end
table.insert(tlinks,link)
nextIdVal = nextIdVal + 1
end
end
end
end
if tval[params.property][1] then -- assemble
if show[id.property]==nil then
local row = ''
show[id.property] = show_all_unsuppressed
if params.prefix then
row = row..'*'..params.prefix
end
for i, l in ipairs(tlinks) do
if i==1 and not params.prefix then
row = row..'*'
else
row = row..'\n**'
end
row = row .. l
end
row = row..'\n'
table.insert(sections[params.section],row)
rct = rct + 1
if tval[params.property][2] then
multipleIdCat = getCatForId( 'multiple' )
end
end
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
end
makeSections(qid, false)
for c = 1, #qids do
makeSections(qids[c], numsections+c)
end
end


--configure Navbox
--configure Navbox
local outString = ''
local outString = ''
local extrap = true
if rct then -- there is at least one link to display
local extra = parentArgs.extralist
if extra == nil or extra == '' then
extrap = false
end
if rct > 0 or extrap then
local Navbox = require('Module:Navbox')
local Navbox = require('Module:Navbox')
local sectionID = 1
local sect, lastsect = 0, 0
local args = { pid = 'identifiers' } -- #target the list of identifiers
if testcases and itemId then args.qid = itemId end --expensive
local pencil = require('Module:EditAtWikidata')._showMessage(args)
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, sectName in ipairs(sectionOrder) do
for c = 1, numsections+#qids do
if #sections[c] ~= 0 then
if #sections[c]>0 then -- section is non-empty
navboxArgs['group'..sectionID] = sectName
sect = sect + 1
navboxArgs['list'..sectionID] = table.concat(sections[c])
lastsect = c
sectionID = sectionID + 1
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
end
end
if extrap then
if topic then -- display in expanded form with topic
if parentArgs.extragroup then
navboxArgs.title = config.i18n.aclink .. ' &ndash; ' .. topic .. pencil(qid)
navboxArgs['group'..sectionID] = parentArgs.extragroup
elseif sect==1 then -- special display when only one section
else
if lastsect<=numsections then
navboxArgs['group'..sectionID] = 'Additional'
if config.sections[lastsect].hidelabelwhenalone then -- no special label when only general or other IDs are present
end
navboxArgs['group' .. lastsect] = config.i18n.aclink .. pencil(qid)
navboxArgs['list'..sectionID] = extra
else -- other regular section
sectionID = sectionID + 1
navboxArgs['group' .. lastsect] = config.i18n.aclink .. ': ' .. navboxArgs['group' .. lastsect] .. pencil(qid)
end
end
if navboxArgs.list2 then
else -- section from additional qid
navboxArgs.title = '[[Help:Authority control|Authority control]]'..pencil
navboxArgs['group' .. lastsect] = config.i18n.aclink .. ': ' .. navboxArgs['group' .. lastsect]
else
local sect = navboxArgs.group1
if sect == 'General' or sect == 'Other' or sect == 'Additional' then
-- Just say "Authority control" with no label if only general or only other IDs are present
-- since "general" is redundant and "other" is silly when there's nothing to contrast it with
navboxArgs.group1 = '[[Help:Authority control|Authority control]]'..pencil
else
navboxArgs.group1 = '[[Help:Authority control|Authority control: '..sect..']] '..pencil
end
end
else -- add title to navbox
navboxArgs.title = config.i18n.aclink .. pencil(qid)
end
end
outString = Navbox._navbox(navboxArgs)
outString = Navbox._navbox(navboxArgs)
end
end


--auxCats
if parentArgs.state
if rct == 0 or rct >= 25 then
and parentArgs.state~=''
if namespace == 0 or testcases then
and parentArgs.state~=config.i18n.collapsed
local eCat = 'AC with '..rct..' elements'
and parentArgs.state~=config.i18n.expanded
elementsCat = addCat(eCat)
and parentArgs.state~=config.i18n.autocollapse then --invalid state parameter
end
auxCats = auxCats .. needsAttention('S')
end
end
if parentArgs.state then
if namespace == 0 or testcases then
local sCat
if parentArgs.state == 'collapsed' then sCat = 'AC using state parameter: collapsed'
elseif parentArgs.state == 'expanded' then sCat = 'AC using state parameter: expanded'
elseif parentArgs.state == 'autocollapse' then sCat = 'AC using state parameter: autocollapse'
else sCat = 'AC using state parameter: other'
end
stateCat = addCat(sCat)
end
end
local auxCats = worldcatCat..elementsCat..multipleIdCat..suppressedIdCat..suppressedIdCatArts..
deprecatedIdCat..differentOnWDCat..sameOnWDCat..stateCat
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') --by definition
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
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
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 wikiTable = '<table class="wikitable sortable">'..
  '<tr><th rowspan=2>Parameter</th>'..
  '<th rowspan=2>Section</th>'..
  '<th rowspan=2>Appears as</th>'..
  '<th rowspan=2 data-sort-type=number>Wikidata property</th>'..
  '<th colspan=2>Tracking categories and page counts</th></tr>'..
  '<tr><th>[[:Category:Articles with authority control information|Articles]]</th>'..
  '<th>[[:Category:Articles with faulty authority control information|Faulty IDs]]</th></tr>'
local lang = mw.getContentLanguage()
local a, f, P = 0, 0, 0 --cumulative sums
local config = require("Module:Authority control/config")
local conf = config.config
local sectionOrder = config.sectionOrder
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(conf) do
local param, pid, section = conf[1], conf.property, sectionOrder[conf.section]
local appearsAs = makelink(conf,conf.example,1)
local link = conf.idlink or param..' (identifier)'
local category = conf.cat or param
local args = { id = 'f', pid }
local wpl = frame:expandTemplate{ title = 'Wikidata property link', args = args }
local articleCat = 'Articles with '..category..' identifiers'
local faultyCat =  'Articles with faulty '.. (conf.errorcat or category) ..' identifiers'
local articleCount = lang:formatNum( mw.site.stats.pagesInCategory(articleCat, 'pages') )
local faultyCount =  lang:formatNum( mw.site.stats.pagesInCategory(faultyCat, 'pages') )
P = P + 1 --property count
a = a + lang:parseFormattedNumber(articleCount)
f = f + lang:parseFormattedNumber(faultyCount)
wikiTable = wikiTable..'<tr><td>[['..link..'|'..param..']]</td>'..
'<td>'..section..'</td>'..
'<td>'..appearsAs..'</td>'..
'<td data-sort-value='..pid..'>'..wpl..'</td>'..
'<td style="text-align: right;">'..checkcat(articleCat,articleCount)..'</td>'..
'<td style="text-align: right;">'..checkcat(faultyCat,faultyCount)..'</td></tr>'
end
wikiTable = wikiTable..'<tr><th style="text-align: right;" colspan=3>Totals</th>'..
'<th style="text-align: right;">'..lang:formatNum(P)..'</th>'..
'<th style="text-align: right;">'..lang:formatNum(a)..'</th>'..
'<th style="text-align: right;">'..lang:formatNum(f)..'</th></tr></table>'
return require('Module:Suppress categories').main(wikiTable)
end
end


return p
return p

Latest revision as of 12: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