Module:Wikidata

From Wikimedia Commons, the free media repository
Revision as of 08:50, 2 October 2013 by Zolo (talk | contribs) (m)
Jump to navigation Jump to search
Lua

CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules

Module permitting basic data retrieval from Wikidata items, based on mw:Extension:Wikibase Client/Lua

Functions callable from Lua

p.getClaims returns claims in a particular item that match a particular query

  • item (required): its Qid
  • property (required) property that the claims should have
  • qualifier = qualifiers that the statement should have
  • withrank = rank of the statement ; 'preferred', 'normal', 'deprecated' or 'valid' (ie. normal and preferred). By default = preferred.
  • sourceproperty = this property should be used in the source
  • withsource = the source that should be provided in the statement (if sourceproperty is not provided, the property used is stated in (P248))
  • excludespecial = set to true if you do not want to get "novalue" and "somevalue".
  • numval = if you want to set a maximum number of values to be returned
  • sorttype = set to "chronological" to get the statements in chronological order using the start time (P580), end time (P582) and point in time (P585) qualifiers. Set to "inverted" for chronological order. From a Lua module, you can also define your own sorting criteria.
  • showsource = set to "true" if you want the source of the statement to be displayed.

p.formatStatements(args): returns a string containing the statements given in the table args. Same keys as getClaims, plus formatting arguments:

  • lang (required) for the desired language
  • displayformat = the format in which the args should be returned. For example, for a string-type property displayformat = "weblink" returns a formatted weblink.
  • conjtype = the conjunction separating the statements. For example, conj = '<br />' will make a new line between each statement.
  • showqualifiers = the qualifiers that should be shown along with the mainsnak value

p.getLabel get the label of an entity

  • entity = entity ID with its Q or P
  • lang

Functions callable from wikitext

  • p.formatStatementsE same as p.formatStatements, except that "lang" is not required. It is most conveniently used from {{Data}} that takes exactly the same arguments.

Examples

Code Render Comment
{{#invoke:Wikidata|pageId}} Script error: The function "pageId" does not exist. return wikidata q-code for pages connected to wikidata
{{#invoke:Wikidata|getLabel|entity=Q42|link=wikipedia}} Script error: The function "getLabel" does not exist. link to wikipedia
{{#invoke:Wikidata|getLabel|entity=Q42|link=wikipedia|format=lc}} Script error: The function "getLabel" does not exist. link to wikipedia but shown with lower case
{{#invoke:Wikidata|getLabel|entity=Q42|link=-}} Script error: The function "getLabel" does not exist. no links
{{#invoke:Wikidata|getLabel|entity=Q42|link=wikipedia|lang=ja}} Script error: The function "getLabel" does not exist.
{{#invoke:Wikidata|getLabel|entity=Q42|link=wikidata}} Script error: The function "getLabel" does not exist. link to wikidata
{{#invoke:Wikidata|getLabel|entity=Q42|link=wikidata|lang=ja}} Script error: The function "getLabel" does not exist.
{{#invoke:Wikidata|getDescription|entity=Q42|link=wikidata|lang=fr}} Script error: The function "getDescription" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q42|property=p31}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q42|property=p31|link=-}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q42|property=p31|lang=ja}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q42|property=p569}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q42|property=p569|lang=ja}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=p186}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=p186|link=-}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=p186|displayformat=raw}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=p186|lang=ja}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=p186|rank=valid}} Script error: The function "formatStatementsE" does not exist. rank = "valid" accepts both "preferred" and "normal" values
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=p186|showqualifiers=p518}} Script error: The function "formatStatementsE" does not exist. shows the value of the p518 qualifier (if any) in addition to the main value
{{#invoke:Wikidata|formatStatementsE|item=Q83259|property=p669|showqualifiers=p670|delimiter=&#32;}} Script error: The function "formatStatementsE" does not exist. shows the value of the P670 qualifier (if any) in addition to the main value separated by a space
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=p186|qualifier=p518}} Script error: The function "formatStatementsE" does not exist. should only display values that have a p518 qualifier
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=p186|numval=1}} Script error: The function "formatStatementsE" does not exist. returns the number of values numval (priority to those with "rank= preferred", if there are not enough of them, also accepts "rank = normal")
{{#invoke:Wikidata|formatStatementsE|item=Q12418|property=P276|sourceproperty=P854}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q11879536|property=P460|withsource=Q1645493}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q153|property=P231|showsource=true}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|item=Q205309|property=P793|sorttype=inverted}} Script error: The function "formatStatementsE" does not exist.
{{#invoke:Wikidata|formatStatementsE|property=P625|item=Q90|displayformat=latitude}} Script error: The function "formatStatementsE" does not exist. Latitude of Paris
{{#invoke:Wikidata|formatStatementsE|property=P19|item=Q1441042}} Script error: The function "formatStatementsE" does not exist. unknown value
{{#invoke:Wikidata|formatStatementsE|property=P19|item=Q43650835}} Script error: The function "formatStatementsE" does not exist. no value

Code

local i18n = {
    ["errors"] = {
        ["property-param-not-provided"] = "Property parameter not provided.",
        ["entity-not-found"] = "Entity not found.",
        ["unknown-claim-type"] = "Unknown claim type.",
        ["unknown-snak-type"] = "Unknown snak type.",
        ["unknown-datavalue-type"] = "Unknown datavalue type.",
        ["unknown-entity-type"] = "Unknown entity type.",
        ["unknown-value-module"] = "You must set both value-module and value-function parameters.",
        ["value-module-not-found"] = "The module pointed by value-module not found.",
        ["value-function-not-found"] = "The function pointed by value-function not found."
    },
    ["somevalue"] = "''unknown value''",
    ["novalue"] = "''no value''"
}

function getEntityFromId( id )
    return mw.wikibase.getEntity() --TODO support for getting other entities
end

function getEntityIdFromValue( value )
    if value['entity-type'] == 'item' then
        return 'q' .. value['numeric-id']
    elseif value['entity-type'] == 'property' then
        return 'p' .. value['numeric-id']
    else
        return formatError( 'unknown-entity-type' )
    end
end

function getSitelink( options)
	entity = getEntityFromId( )
	lang = options.lang
	if options.item then 
		item = options.item
	else 
		item = entity.id
	end
	if entity.sitelinks and entity.sitelinks[lang .. 'wiki'] then
		return entity.sitelinks[lang .. 'wiki']['title']
	else 
		return nil
	end
end
function formatError( key )
    return '<span class="error">' .. i18n.errors[key] .. '</span>'
end


function formatStatements( options )
    if not options.property then
        return formatError( 'property-param-not-provided' )
    end

    --Get entity
    local entity = nil
    if options.entity and type( options.entity ) == "table" then
        entity = options.entity
    else
        entity = getEntityFromId( options.entityId )
    end

    if not entity then
        return '' --TODO error?
    end

    if not entity.claims or not entity.claims[string.lower(options.property)] then
        return '' --TODO error?
    end

    --Format statement and concat them cleanly
    local formattedStatements = {}
    for i, statement in pairs( entity.claims[options.property:lower()] ) do
        if options.rank == 'one' then
            return formatStatement( statement, options ) --Output only one value
        else
            table.insert( formattedStatements, formatStatement( statement, options ) )
        end
    end
    return mw.text.listToText( formattedStatements, options.separator, options.conjunction )
end

function formatStatement( statement, options )
    if not statement.type or statement.type ~= 'statement' then
        return formatError( 'unknown-claim-type' )
    end

    return formatSnak( statement.mainsnak, options )
    --TODO reference and qualifiers
end

function formatSnak( snak, options )
    if snak.snaktype == 'somevalue' then
        return i18n['somevalue']
    elseif snak.snaktype == 'novalue' then
        return i18n['novalue']
    elseif snak.snaktype == 'value' then
        return formatDatavalue( snak.datavalue, options )
    else
        return formatError( 'unknown-snak-type' )
    end
end

function formatDatavalue( datavalue, options )
    --Use the customize handler if provided
    if options['value-module'] or options['value-function'] then
        if not options['value-module'] or not options['value-function'] then
            return formatError( 'unknown-value-module' )
        end
        local formatter = require ('Module:' .. options['value-module'])
        if not formatter then
            return formatError( 'value-module-not-found' )
        end
        local fun = formatter[options['value-function']]
        if not fun then
            return formatError( 'value-function-not-found' )
        end
        return fun( datavalue.value, options )
    end

    --Default formatters
    if datavalue.type == 'wikibase-entityid' then
        return formatEntityId( getEntityIdFromValue( datavalue.value ), options )
    elseif datavalue.type == 'string' then
        if options.pattern and options.pattern ~= '' then
            return formatFromPattern( datavalue.value, options )
        else
            return datavalue.value
        end
    else
        return formatError( 'unknown-datavalue-type' )
    end
end

function formatEntityId( entityId, options )
    local label = mw.wikibase.label( entityId )
    local link = mw.wikibase.sitelink( entityId )
    if link then
        if label then
            return '[[' .. link .. '|' .. label .. ']]'
        else
            return '[[' .. link .. ']]'
        end
    else
        return label --TODO what if no links and label + fallback language?
    end
end

function formatFromPattern( str, options )
    return mw.ustring.gsub( options.pattern, '$1', str ) .. '' --Hack to get only the first result of the function
end

local p = {}

function p.formatStatements( frame )
    local args = frame.args

    --If a value if already set, use it
    if args.value and args.value ~= '' then
        return args.value
    end
    return formatStatements( frame.args )
end

function p.translationTable(frame) -- translation tables that are so common on Commons
	entity = getEntityFromId( )
    if not entity then
        return '' --TODO error?
    end
    id = entity.id
	if not entity.labels then 
		return ''
	end
	labeltable = {}
	for lang, value in pairs(entity.labels) do
		label = value.value
		if entity.sitelinks then
			if entity.sitelinks[lang .. 'wiki'] then
				link = entity.sitelinks[lang .. 'wiki'].title
				link = lang .. ':' .. link
				return link
			end
		end
		if not link then 
			link = entity.id
			link = "wikidata:" .. ':' .. link
		end
		formattedlink = '[[:' .. link .. '|' .. label ']]'
		return formattedlink
		-- table.insert(labeltable, formattedlink)
	end
	return mw.text.listToText( labeltable )
end


function p.formatStatementsFromLua( options )
    --If a value if already set, use it
    if options.value and options.value ~= '' then
        return options.value
    end
    return formatStatements( options )
end

function p.getSitelink(frame)
	return getSitelink(frame.args)
end

return p