انتقل إلى المحتوى

وحدة:WdItem

من ويكاموس، القاموس الحر

-- Module: WdItem
-- Object-oriented Wikidata access module for Lua
-- Refactored from WikidataIB for direct Lua usage

require("strict")
local p = {}
local cdate -- initialise as nil and only load _complex_date function if needed
-- Module:Complex date is loaded lazily and has the following dependencies:
-- Module:Calendar
-- Module:ISOdate
-- Module:DateI18n
-- Module:I18n/complex date
-- Module:Ordinal
-- Module:I18n/ordinal
-- Module:Yesno
-- Module:Formatnum
-- Module:Linguistic

-- i18n configuration
local i18n = {
	["errors"] = {
		["property-not-found"] = "الخاصية غير موجودة.",
		["entity-not-found"] = "الكيان على ويكي بيانات غير موجود.",
		["unknown-claim-type"] = "نوع الادعاء غير معروف.",
		["local-article-not-found"] = "المعرف متاح على ويكي بيانات، ولكن المقال غير متاح على ويكيبيديا",
	},
	["months"] = {
		"January", "February", "March", "April", "May", "June",
		"July", "August", "September", "October", "November", "December"
	},
	["Unknown"] = "Unknown",
	["NaN"] = "Not a number",
	["missinginfocat"] = "[[تصنيف:Articles with missing Wikidata information]]",
	["list separator"] = ", ",
	["list separator-ar"] = "، ",
}

-- Date precision constants
local dp = {
	[6] = "millennium",
	[7] = "century",
	[8] = "decade",
	[9] = "year",
	[10] = "month",
	[11] = "day",
}

-- local options_aliases = {
-- 	["osd"] = "onlysourced",
-- 	["wdl"] = "wdlinks",
-- 	["uabbr"] = "unitabbr",
-- 	["qo"] = "qualsonly",
-- 	["lp"] = "linkprefix",
-- 	["lprefix"] = "linkprefix",
-- 	["qlp"] = "qlinkprefix",
-- 	["sn"] = "shortname",
-- 	["uselbl"]  = "uselabel",
-- 	["pd"] = "plaindate",
-- 	["qdf"] = "qualifierdateformat",
-- 	["df"] = "qualifierdateformat",
-- 	["qsn"] = "qshortname"
-- }

-- setmetatable(options_aliases, { __index = function(t, k) return k end })

-------------------------------------------------------------------------------
-- Internal helper functions
-------------------------------------------------------------------------------
local function in_array( needle, haystack )
	if needle == nil then
		return false
	end
	for n, v in ipairs( haystack ) do
		if v == needle then
			return n
		end
	end
	return false
end

local function findLang(langcode)
	local langobj
	langcode = mw.text.trim(langcode or "") 
	if langcode ~= "" then
		if mw.language.isKnownLanguageTag(langcode) then
			langobj = mw.language.new(langcode)
		end
	else
		langobj = mw.language.getContentLanguage()
	end

	return langobj and langobj.code
end

local function parseParam(param, default)
	if param == nil then
		return default
	end
	return param
end

local function setRanks(rank)
	rank = (rank or ""):lower()
	local ranks = {}
	for w in string.gmatch(rank, "%a+") do
		if w == "best" or w == "preferred" or w == "normal" or w == "deprecated" then
			ranks[w] = true
		end
	end
	if ranks.best or not next(ranks) then
		ranks.preferred = true
		ranks.normal = true
		ranks.deprecated = false
	end
	return ranks
end

local function labelOrId(id, lang_t)
	local langs = lang_t or {}
	local label

	for _,lang in ipairs(langs) do
		label = mw.wikibase.getLabelByLang(id, lang)
		if label ~= "" then
			break;
		end
	end

	label = label or mw.wikibase.getLabel(id)
	if label then
		return mw.text.nowiki(label), true
	else
		return id, false
	end
end

local function roundto(x, sf)
	if x == 0 then return 0 end
	local s = 1
	if x < 0 then
		x = -x
		s = -1
	end
	if sf < 1 then sf = 1 end
	local p = 10 ^ (math.floor(math.log10(x)) - sf + 1)
	x = math.floor(x / p + 0.5) * p * s
	if x == math.floor(x) then x = math.floor(x) end
	return x
end

local function decimalPrecision(x, p)
	local s = 1
	if x < 0 then
		x = -x
		s = -1
	end
	if not tonumber(p) then p = 1e-4
	elseif p > 1 then p = 1
	elseif p < 1e-6 then p = 1e-6
	else p = 10 ^ math.floor(math.log10(p))
	end
	x = math.floor(x / p + 0.5) * p * s
	if  x == math.floor(x) then x = math.floor(x) end
	if math.abs(x) < 1e-4 then x = string.format("%f", x) end
	return x
end

local function decimalToDMS(x, p)
	if not tonumber(p) then p = 1e-4 end
	local d = math.floor(x)
	local ms = (x - d) * 60
	if p > 0.5 then
		if ms > 30 then d = d + 1 end
		ms = 0
	end
	local m = math.floor(ms)
	local s = (ms - m) * 60
	if p > 0.008 then
		if s > 30 then m = m +1 end
		s = 0
	elseif p > 0.00014 then
		s = math.floor(s + 0.5)
	elseif p > 0.000014 then
		s = math.floor(10 * s + 0.5) / 10
	elseif p > 0.0000014 then
		s = math.floor(100 * s + 0.5) / 100
	else
		s = math.floor(1000 * s + 0.5) / 1000
	end
	return d, m, s
end

local function rawValue(dataValue)
	if dataValue.type == "string" then
		return dataValue.value
	elseif dataValue.type == "wikibase-entityid" then
		return dataValue.value and dataValue.value.id
	elseif dataValue.type == "monolingualtext" then
		return dataValue.value.text 
	elseif dataValue.type == "quantity"  then
		return tonumber(dataValue.value.amount)
	elseif dataValue.type == 'time' then
		return dataValue.value.time
	elseif dataValue.type == "globecoordinate" then
		return dataValue.value.latitude .. '/' .. dataValue.value.longitude
	end
end

local function compareValue(dataValue, strValue)
	return rawValue(dataValue) == strValue
end

local function dateFormat(timestamp, dprec, df, bcf, plaindate, qualifiers, lang, adj, model)
	df = (df or ""):lower()
	if df == "ymd" then
		if timestamp:sub(1,1) == "+" then
			return timestamp:sub(2,11)
		else
			local yr = tonumber(timestamp:sub(2,5)) - 1
			yr = ("000" .. yr):sub(-4)
			if yr ~= "0000" then yr = "-" .. yr end
			return yr .. timestamp:sub(6,11)
		end
	end
	timestamp = timestamp:gsub("%-00%-00T", "-01-01T")
	dprec = dprec or 11
	if df == "y" and dprec > 9 then dprec = 9 end
	dprec = dprec>11 and 11 or dprec
	dprec = dprec<6 and 6 or dprec
	bcf = (bcf or ""):upper()
	plaindate = (plaindate or ""):sub(1,1):lower()
	if plaindate == "" or plaindate == "n" or plaindate == "f" or plaindate == "0" then plaindate = false end
	do
		local llang = findLang()
		lang = in_array(lang, {llang, 'en'}) and lang or llang
	end
	adj = adj or ""
	
	local bc = timestamp:sub(1, 1)=="-" and "BC" or ""
	local year, month, day = timestamp:match("[+-](%d*)-(%d*)-(%d*)T")
	local iso = tonumber(year)
	
	if df == 'tt' then
		return {
			year = tonumber(timestamp:match("^([+-]%d*)-")) or 0,
			month = tonumber(month) or 0,
			day = tonumber(day) or 0
		}
	end
	
	if dprec == 6 then iso = math.floor( (iso - 1) / 1000 ) + 1 end
	if dprec == 7 then iso = math.floor( (iso - 1) / 100 ) + 1 end
	if dprec == 8 then iso = math.floor( iso / 10 ) .. "0" end
	if dprec == 10 then iso = year .. "-" .. month end
	if dprec == 11 then iso = year .. "-" .. month .. "-" .. day end
	
	local sc = not plaindate and qualifiers and qualifiers.P1480
	if sc then
		for k1, v1 in pairs(sc) do
			if v1.datavalue and v1.datavalue.value.id == "Q5727902" then
				adj = "circa"
				break
			end
		end
	end
	
	local calendarmodel = ""
	if tonumber(year) > 1582
		and dprec > 8 
		and not plaindate 
		and model == "http://www.wikidata.org/entity/Q1985786" then
		calendarmodel = "julian"
	end
	
	if not cdate then
		cdate = require("Module:Complex date")._complex_date
	end
	local fdate = cdate(calendarmodel, adj, tostring(iso), dp[dprec], bc, "", "", "", "", lang, 1)
	-- this may have QuickStatements info appended to it in a div, so remove that
	fdate = fdate:gsub(' <div style="display: none;">[^<]*</div>', '')
	-- it may also be returned wrapped in a microformat, so remove that
	fdate = fdate:gsub("<[^>]*>", "")
	-- there may be leading zeros that we should remove
	fdate = fdate:gsub("^0*", "")
	-- if a plain date is required, then remove any links (like BC linked)
	if plaindate then
		fdate = fdate:gsub("%[%[.*|", ""):gsub("]]", "")
	end
	-- if 'circa', use the abbreviated form *** internationalise later ***
	fdate = fdate:gsub('circa ', '<abbr title="circa">c.</abbr>&nbsp;')
	-- deal with BC/BCE
	if bcf == "BCE" then
		fdate = fdate:gsub('BC', 'BCE')
	end
	-- deal with mdy format
	if df == "mdy" then
		fdate = fdate:gsub("(%d+) (%w+) (%d+)", "%2 %1, %3")
	end
	-- deal with adjectival form *** internationalise later ***
	if plaindate == "a" then
		fdate = fdate:gsub(' century', '-century')
	end
	
	return fdate
end

local function hijriFormat(qualifiers, dateformat, lang)
	if not (qualifiers and qualifiers.P4241) then return; end
	local year, month, monthno, day
	local val
	local qhmonths = {["Q1952053"]=1,["Q489557"]=2, ["Q474167"] = 3, ["Q273815"] = 4, ["Q852002"] = 5, ["Q822218"] = 6,
		["Q194210"] = 7, ["Q220914"] = 8, ["Q8867089"]=9, ["Q685440"]=10,["Q150853"]=11,["Q186022"]=12 }
	local hmonths = {"محرم","صفر","ربيع الأول","ربيع الآخر","جمادى الأولى","جمادى الآخرة","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة"}
	local hmonths_inv = {["محرم"] = 1, ["صفر"]=2, ["ربيع الأول"]=3, ["ربيع الآخر"]=4, ["جمادى الأولى"]=5, ["جمادى الآخرة"]=6, ["رجب"]=7, ["شعبان"]=8, ["رمضان"]=9, ["شوال"]=10, ["ذو القعدة"]=11, ["ذو الحجة"]=12}
	
	for _, item in ipairs(qualifiers.P4241) do
		local timeQ = item.datavalue and item.datavalue.value and item.datavalue.value.id
		local hastime = false
		if timeQ then
			local timeQt = mw.wikibase.getBestStatements(timeQ, "P361")
			for _,timeQsnak in pairs(timeQt) do
				local timeType = timeQsnak.mainsnak and timeQsnak.mainsnak.datavalue and timeQsnak.mainsnak.datavalue.value and timeQsnak.mainsnak.datavalue.value.id
				if timeType == "Q28892" then
					local timeLableAr = mw.wikibase.getLabelByLang(timeQ, "ar")
					if timeLableAr then
						year = mw.ustring.match(timeLableAr, "^(%d+) *هـ$")
					end
					if not year then
						local timeLableEn = mw.wikibase.getLabelByLang(timeQ, "en")
						if timeLableEn then
							year = mw.ustring.match(timeLableAr, "^(%d+) *AH$")
						end
					end
					hastime=true
				elseif qhmonths[timeType] then
					monthno = qhmonths[timeType]
					if monthno>0 and monthno<13 then
						month = hmonths[monthno]
					end
					local timeLableAr = mw.wikibase.getLabelByLang(timeQ, "ar")
					if timeLableAr then
						day = mw.ustring.match(timeLableAr, "^(%d+) *%a+$")
					end
					if not day then
						local timeLableEn = mw.wikibase.getLabelByLang(timeQ, "en")
						if timeLableEn then
							day = mw.ustring.match(timeLableAr, "^(%d+) *%a+$")
						end
					end
					hastime=true
				end
			end
			if not hastime then
				timeQt = mw.wikibase.getBestStatements(timeQ, "P31")
				if "Q125390868" == (timeQt[1].mainsnak and timeQt[1].mainsnak.datavalue and timeQt[1].mainsnak.datavalue.value and timeQt[1].mainsnak.datavalue.value.id ) then
					val = mw.wikibase.getLabelByLang(timeQ, "ar")
					month, year = mw.ustring.match(val, "^(%a[%a ]+%a) *(%d+) *هـ?$")
					monthno = hmonths_inv[month]
				end
			end
		end
	end

	if year then
		if dateformat == "tt" then
			return {year = tonumber(year) or 0,
					month = monthno or 0,
					day = tonumber(day) or 0,
					monthname = month or ''}
		elseif dateformat == "y" or not month then
			return year;
		elseif day and month then
			if dateformat == 'ymd' then
				return string.format("%04d-%02d-%02d", tonumber(year), monthno, tonumber(day));
			else
				return day .. ' ' .. month .. ' ' .. year;
			end
		elseif month then
			return month .. ' ' .. year;
		end
	end
	return nil;
end

local function rawValueOrDF (statement, opt)
	local datasnak = statement.mainsnak or statement
	if (datasnak.datavalue and datasnak.datavalue.type == 'time') and (opt.hijri or opt.df) then
		if opt.hijri then
			return statement.qualifiers and hijriFormat(statement.qualifiers, opt.df) or nil
		elseif opt.df then
			local dv = datasnak.datavalue.value
			return dateFormat(dv.time, dv.precision, opt.df, opt.bc, opt.plaindate, statement.qualifiers, opt.lang, "", dv.calendarmodel)
		end
	else
		return rawValue(datasnak.datavalue)
	end
end

local function sourced(claim)
	if claim.references then
		for kr, vr in pairs(claim.references) do
			local ref = mw.wikibase.renderSnaks(vr.snaks)
			if not ref:find("Wiki") then
				return true
			end
		end
	end
end

local function linkedItem(id, args)
	local linkprefix = (args.linkprefix or ""):gsub('"', '')
	local lpostfix = (args.lpostfix or ""):gsub('"', '')
	local prefix = (args.prefix or ""):gsub('"', '')
	local postfix = (args.postfix or ""):gsub('"', '')
	local wikilinkprefix = (args.wikilinkprefix or ""):gsub('"', '')
	local dtxt = args.dtxt
	local uselabel = parseParam( args.uselabel, true)
	local langs = (args.langs and #args.langs>0) and args.langs or  { args.lang }
	local disp
	local sitelink = mw.wikibase.getSitelink(id, args.linksproject)
	local label, islabel
	if dtxt then
		label, islabel = dtxt, true
	else
		label, islabel = labelOrId(id, langs)
	end
	
	if sitelink then
		if not uselabel then
			local pos = sitelink:find(":") or 0
			local slink = sitelink
			if pos > 0 then
				local pfx = sitelink:sub(1,pos-1)
				if mw.site.namespaces[pfx] then
					slink = sitelink:sub(pos+1)
				end
			end
			slink = slink:gsub("%s%(.+%)$", ""):gsub(",.+$", "")
			if label:find("^%u") then
				label = slink:gsub("^(%l)", string.upper)
			else
				label = slink:gsub("^(%u)", string.lower)
			end
		end
		disp = "[[" .. wikilinkprefix .. sitelink .. lpostfix .. "|" .. prefix .. label .. postfix .. "]]"
	elseif islabel then
		disp = prefix .. label .. postfix
	else
		disp = prefix .. label .. postfix .. i18n.missinginfocat
	end
	
	return disp
end

local function rendersnak(propval, args, linked, lpre, lpost, pre, post, unitabbr, filter)
	lpre = lpre or ""
	lpost = lpost or ""
	pre = pre or ""
	post = post or ""
	args.lang = args.lang or (args.langs and args.langs[1]) or findLang();
	local langs = (args.langs and #args.langs>0) and args.langs or {args.lang }
	local snak = propval.mainsnak or propval
	local dtype = snak.datatype
	local dv = snak.datavalue
	dv = dv and dv.value
	local val, mlt
	local namedas;

	namedas = propval.qualifiers and propval.qualifiers.P1932 and propval.qualifiers.P1932[1].datavalue and propval.qualifiers.P1932[1].datavalue.value or nil
	args.dtxt = namedas

	if propval.rank and not args.reqranks[propval.rank] then
		return nil
	elseif snak.snaktype == "somevalue" then
		val = namedas or i18n["Unknown"]
	elseif snak.snaktype == "novalue" then
		-- return nothing
	elseif dtype == "wikibase-item" then
		local qnumber = dv.id
		if linked then
			val = linkedItem(qnumber, args)
		else
			if namedas then
				val = pre .. namedas .. post	
			else
				local label, islabel = labelOrId(qnumber, langs)
				val = pre .. label .. post
			end
		end
	elseif dtype == "time" then
		if args.hijri then
			val = hijriFormat(propval.qualifiers, args.df, args.lang)
		else
			val = dateFormat(dv.time, dv.precision, args.df, args.bc, args.plaindate, propval.qualifiers, args.lang, "", dv.calendarmodel)
		end
	elseif dtype == "commonsMedia" or dtype == "external-id" or dtype == "string" or dtype == "url" then
		if dtype == "external-id" and args.fullidurl then
			val = mw.ustring.match(mw.wikibase.formatValue(snak), "%[(https?://[^%s%]]+)")
		elseif (lpre == "" or lpre == ":") and lpost == "" then
			val = pre .. dv .. post
		elseif dtype == "external-id" then
			val = "[" .. lpre .. dv .. lpost .. " " .. pre .. dv .. post .. "]"
		else
			val = "[[" .. lpre .. dv .. lpost .. "|" .. pre .. dv .. post .. "]]"
		end
	elseif dtype == "quantity" then
		local amount = tonumber(dv.amount) or i18n["NaN"]
		local unit = ""
		local unitqid = string.match(dv.unit, "(Q%d+)")
		if filter and unitqid ~= filter then return nil end
		if unitqid then
			local uname = labelOrId(unitqid, langs) or ""
			if uname ~= "" then unit = " " .. uname end
		end
		val = tostring(amount) .. unit
	elseif dtype == "globe-coordinate" then
		local lat, long, prec = dv.latitude, dv.longitude, dv.precision
		local show = (args.show or ""):lower()
		if show == "lat" then
			val = decimalPrecision(lat, prec)
		elseif show == "lon" then
			val = decimalPrecision(long, prec)
		elseif show == "longlat" then
			val = decimalPrecision(long, prec) .. ", " .. decimalPrecision(lat, prec)
		else
			local ns = lat < 0 and "S" or "N"
			local ew = long < 0 and "W" or "E"
			if lat < 0 then lat = -lat end
			if long < 0 then long = -long end
			val = decimalPrecision(lat, prec) .. "°" .. ns .. " " .. decimalPrecision(long, prec) .. "°" .. ew
		end
	elseif dtype == "monolingualtext" then
		val = pre .. dv.text .. post
		mlt = dv.language
	else
		val = "unknown data type: " .. dtype
	end
	
	return val, mlt
end

local function assembleoutput(out, args, entityID, propertyID)
	local sorted = parseParam(args.sorted, false)
	local noicon = parseParam(args.noicon, false)
	local list = args.list or ""
	local separator = args.sep or ""
	separator = string.gsub(separator, '"', '')
	
	if separator == "" then
		local rtl_lang = {ar = true, fa = true, ur = true, ku = true, he = true}
		separator = rtl_lang[args.lang] and i18n["list separator-ar"] or i18n["list separator"]
	end
	
	local strout
	if #out > 0 then
		if sorted then table.sort(out) end
		
		if list == "" then
			strout = table.concat(out, separator)
		elseif list:lower() == "prose" then
			strout = mw.text.listToText(out)
		else
			strout = mw.getCurrentFrame():expandTemplate{title = list, args = out}
		end
	else
		strout = nil
	end
	
	return strout
end

-- WdItem
local function propertyvalueandquals(objproperty, args, qualID)
	-- needs this style of declaration because it's re-entrant

	-- onlysourced is a boolean passed to return only values sourced to other than Wikipedia
	-- if nothing or an empty string is passed set it true
	local onlysrc = parseParam(args.onlysourced, false)

	-- linked is a a boolean that enables the link to a local page via sitelink
	-- if nothing or an empty string is passed set it true
	local linked = parseParam(args.linked, true)

	-- prefix is a string that may be nil, empty (""), or a string of characters
	-- this is prefixed to each value
	-- useful when when multiple values are returned
	-- any double-quotes " are stripped out, so that spaces may be passed
	local prefix = (args.prefix or ""):gsub('"', '')

	-- postfix is a string that may be nil, empty (""), or a string of characters
	-- this is postfixed to each value
	-- useful when when multiple values are returned
	-- any double-quotes " are stripped out, so that spaces may be passed
	local postfix = (args.postfix or ""):gsub('"', '')

	-- linkprefix is a string that may be nil, empty (""), or a string of characters
	-- this creates a link and is then prefixed to each value
	-- useful when when multiple values are returned and indirect links are needed
	-- any double-quotes " are stripped out, so that spaces may be passed
	local linkprefix = (args.linkprefix or ""):gsub('"', '')

	-- linkpostfix is a string that may be nil, empty (""), or a string of characters
	-- this is postfixed to each value when linking is enabled with linkprefix
	-- useful when when multiple values are returned
	-- any double-quotes " are stripped out, so that spaces may be passed
	local lpostfix = (args.linkpostfix or ""):gsub('"', '')

	-- wdlinks is a boolean passed to enable links to Wikidata when no article exists
	-- if nothing or an empty string is passed set it false
	local wdlinks = parseParam(args.wdlinks, false)

	-- unitabbr is a boolean passed to enable unit abbreviations for common units
	-- if nothing or an empty string is passed set it false
	local unitabbr = parseParam(args.unitabbr, false)

	-- qualsonly is a boolean passed to return just the qualifiers
	-- if nothing or an empty string is passed set it false
	local qualsonly = parseParam(args.qualsonly, false)

	-- maxvals is a string that may be nil, empty (""), or a number
	-- this determines how many items may be returned when multiple values are available
	-- setting it = 1 is useful where the returned string is used within another call, e.g. image
	local maxvals = tonumber(args.maxvals) or 0

	-- plaindate boolean
	-- to disable/enable "sourcing cirumstances" or use adjectival form for the plain date
	local plaindate = args.plaindate or false
	args.plaindate = plaindate

	-- allow qualifiers to have a different date format; default to year unless qualsonly is set
	args.qualifierdateformat = args.qualifierdateformat or (not qualsonly and "y")

	local lang = args.lang or (args.langs and args.langs[1]) or findLang()

	-- qualID is a string list of wanted qualifiers or "ALL"
    qualID = qualID or ""
    -- capitalise list of wanted qualifiers and substitute "DATES"
    qualID = qualID:upper():gsub("DATES", "P580, P582")
    local allflag = (qualID == "ALL")
    -- create table of wanted qualifiers as key
    local qwanted = {}
    -- create sequence of wanted qualifiers
    local qorder = {}
    for q in mw.text.gsplit(qualID, "%p") do -- split at punctuation and iterate
        local qtrim = mw.text.trim(q)
        if qtrim ~= "" then
            qwanted[mw.text.trim(q)] = true
            qorder[#qorder+1] = qtrim
        end
    end
    -- qsep is the output separator for rendering qualifier list
    local qsep = (args.qsep or ""):gsub('"', '')
    -- qargs are the arguments to supply to assembleoutput()
    local qargs = {
        ["onlysourced"]         = false,
        ["linked"]      = tostring(linked),
        ["prefix"]      = args.qprefix,
        ["postfix"]     = args.qpostfix,
        ["linkprefix"]  = args.qlinkprefix,
        ["linkpostfix"] = args.qlinkpostfix,
        ["wdlinks"]     = false,
        ["unitabbr"]    = tostring(unitabbr),
        ["maxvals"]     = 0,
        ["sorted"]      = tostring(args.qsorted),
        ["noicon"]      = true,
        ["list"]        = args.qlist,
        ["sep"]         = qsep,
        -- ["langobj"]     = args.langobj,
        ["lang"]        = lang,
		langs 			= args.langs,
        ["df"]          = args.qualifierdateformat,
        ["shortname"]    = parseParam(args.qshortname, false),
    }

	-- all proper values of a Wikidata property will be the same type as the first
	-- qualifiers don't have a mainsnak, properties do
	--#Modified line
	
	local datatype = objproperty[1].datatype or (objproperty[1].mainsnak and objproperty[1].mainsnak.datatype)

	-- out[] holds the a list of returned values for this property
	-- mlt[] holds the language code if the datatype is monolingual text
	local out = {}
	local mlt = {}

	for k, v in ipairs(objproperty) do
		local hasvalue = true
		if (onlysrc and not sourced(v)) then
			-- no value: it isn't sourced when onlysourced=true
			hasvalue = false
		else
			local val, lcode = rendersnak(v, args, linked, linkprefix, lpostfix, prefix, postfix, unitabbr)
			if not val then
				hasvalue = false -- rank doesn't match
			elseif qualsonly and qualID then
				-- suppress value returned: only qualifiers are requested
			else
				out[#out+1], mlt[#out+1] = val, lcode
			end
		end

		-- See if qualifiers are to be returned:
		local snak = v.mainsnak or v
		if hasvalue and v.qualifiers and qualID ~= "" and snak.snaktype~="novalue" then
            -- collect all wanted qualifier values returned in qlist, indexed by propertyID
			local qlist = {}
			local timestart, timeend = "", ""
            -- loop through qualifiers
            for k1, v1 in pairs(v.qualifiers) do
                if allflag or qwanted[k1] then
                    if k1 == "P1326" then
                        local ts = v1[1].datavalue.value.time
                        local dp = v1[1].datavalue.value.precision
                        qlist[k1] = dateFormat(ts, dp, args.qualifierdateformat, args.bc, plaindate, "", lang, "before")
                    elseif k1 == "P1319" then
                        local ts = v1[1].datavalue.value.time
                        local dp = v1[1].datavalue.value.precision
                        qlist[k1] = dateFormat(ts, dp, args.qualifierdateformat, args.bc, plaindate, "", lang, "after")
                    elseif k1 == "P580" then
                        timestart = propertyvalueandquals(v1, qargs)[1] or "" -- treat only one start time as valid
                    elseif k1 == "P582" then
                        timeend = propertyvalueandquals(v1, qargs)[1] or "" -- treat only one end time as valid
                    else
						local q = assembleoutput(propertyvalueandquals(v1, qargs), qargs)
                        -- we already deal with circa via 'sourcing circumstances' if the datatype was time
                        -- circa may be either linked or unlinked *** internationalise later ***
                        if datatype ~= "time" or q ~= "circa" and not (type(q) == "string" and q:find("circa]]")) then
                            qlist[k1] = q
                        end
                    end
                end -- of test for wanted
            end -- of loop through qualifiers
            -- set date separator
			local t = timestart .. timeend
			-- *** internationalise date separators later ***
			local dsep = "&ndash;"
			if t:find("%s") or t:find("&nbsp;") then dsep = " &ndash; " end
            -- set the order for the list of qualifiers returned; start time and end time go last
			if next(qlist) then
                local qlistout = {}
                if allflag then
                    for k2, v2 in pairs(qlist) do
                        qlistout[#qlistout+1] = v2
                    end
                else
                    for i2, v2 in ipairs(qorder) do
                        qlistout[#qlistout+1] = qlist[v2]
                    end
                end
                if t ~= "" then
                    qlistout[#qlistout+1] = timestart .. dsep .. timeend
                end
				local qstr = assembleoutput(qlistout, qargs)
				if qualsonly then
					out[#out+1] = qstr
				else
					out[#out] = out[#out] .. " (" .. qstr .. ")"
				end
			elseif t ~= "" then
				if qualsonly then
					if timestart == "" then
						out[#out+1] = timeend
					elseif timeend == "" then
						out[#out+1] = timestart
					else
						out[#out+1] = timestart .. dsep .. timeend
					end
				else
					out[#out] = out[#out] .. " (" .. timestart .. dsep .. timeend .. ")"
				end
			end
		end -- of test for qualifiers wanted

		if maxvals > 0 and #out >= maxvals then break end
	end -- of for each value loop

	-- we need to pick one value to return if the datatype was "monolingualtext"
	-- if there's only one value, use that
	-- otherwise look through the fallback languages for a match
	if datatype == "monolingualtext" and #out >1 then
		lang = mw.text.split( lang, '-', true )[1]
		local fbtbl = mw.language.getFallbacksFor( lang )
		table.insert( fbtbl, 1, lang )
		local bestval = ""
		local found = false
		for idx1, lang1 in ipairs(fbtbl) do
			for idx2, lang2 in ipairs(mlt) do
				if (lang1 == lang2) and not found then
					bestval = out[idx2]
					found = true
					break
				end
			end -- loop through values of property
		end -- loop through fallback languages
		if found then
			-- replace output table with a table containing the best value
			out = { bestval }
		else
			-- more than one value and none of them on the list of fallback languages
			-- sod it, just give them the first one
			out = { out[1] }
		end
	end
	return out
end

local function mergeOptions(defaults, overrides)
	overrides = overrides or {}
	defaults = defaults or {}
	local result = {}
	for k, v in pairs(defaults) do
		result[k] = v
	end
	for k, v in pairs(overrides) do
		result[k] = v
		if k == 'rank' then
			result.reqranks = setRanks(v)
		end
	end
	return result
end

local function filterbyqualifier(statements,qual,value)
	local filtered_statements = {}
	for _, statement in ipairs(statements) do
		if statement.qualifiers and statement.qualifiers[qual] then
			if '*' == value then
				filtered_statements[#filtered_statements + 1] = statement
			else
				for _, q in ipairs(statement.qualifiers[qual]) do
					if q.datavalue and (rawValue(q.datavalue) == value) then
						filtered_statements[#filtered_statements + 1] = statement
						break
					end
				end
			end
		end
	end
	return filtered_statements
end

local function orderbyrank(statements)
	local pref_count = 0
	local sorted_statements = {}
	for k,v in ipairs(statements) do
		if v.rank == 'preferred' then
			pref_count = pref_count + 1
			table.insert(sorted_statements, pref_count, v)
		else
			sorted_statements[#sorted_statements + 1] = v
		end
	end
	return sorted_statements
end


-------------------------------------------------------------------------------
-- helper class functions
-------------------------------------------------------------------------------
local function class()
  local c = {}
  c.__index = c
  function c:new(...)
    local o = setmetatable({}, c)
    if o.init then o:init(...) end
    return o
  end
  return c
end

-------------------------------------------------------------------------------
-- Statement Class Definition
-------------------------------------------------------------------------------

local WdStatement = class()

function WdStatement:getValue(opts)
	local mergedOpts = mergeOptions(self.parent.options, opts)

	local statement = self._statement
	if not statement then
		return nil
	end

	local qualID = mw.text.trim(mergedOpts.qual or ""):upper()
	if qualID == "" then qualID = nil end

	local out = propertyvalueandquals({statement}, mergedOpts, qualID)
	return assembleoutput(out, mergedOpts, self.parent.qid, self.pid)
end

function WdStatement:getRawValue(opts)
	local mergedOpts = mergeOptions(self.parent.options, opts)
	if not self._statement then
		return nil
	end
	local datasnak = self._statement.mainsnak or self._statement
	if datasnak.snaktype == "value" then
		return rawValueOrDF(self._statement, mergedOpts)
	else
		return datasnak.snaktype
	end
end

function WdStatement:getRawQual(qualID)
	local ret = {}
	local s = self._statement
	if s.qualifiers and s.qualifiers[qualID]  then
		for _,q in pairs(s.qualifiers[qualID]) do
			if q.snaktype == "value" then
				ret[#ret + 1] = rawValueOrDF(q, self.parent.options)
			else
				ret[#ret + 1] = q.snaktype
			end
		end
	end
	return ret
end

-------------------------------------------------------------------------------
-- Statements Class Definition
-------------------------------------------------------------------------------
local WdStatements = class()

function WdStatements:getStatmentsTable()
	return self._statements
end

function WdStatements:count()
	return #self._statements
end

function WdStatements:getFilters()
	return self.filtered_by
end

function WdStatements:filter(filter_t)

	local statements = self._statements
	if #statements == 0 then return self; end

	local ret = WdStatements:new()
	ret.parent = self.parent
	ret.filtered_by = {}
	for _,v in ipairs(self.filtered_by) do
		ret.filtered_by[#ret.filtered_by + 1] = v
	end

	local filtered_statements = {}

	for k,v in pairs(filter_t) do
		filtered_statements = filterbyqualifier(statements, k, v)
		ret.filtered_by[#ret.filtered_by + 1] = {[k] = v}
		if #filtered_statements == 0 then
			break;
		else
			statements = filtered_statements
		end
	end

	ret._statements = filtered_statements
	return ret
end

function WdStatements:getValue(opts)
	local mergedOpts = mergeOptions(self.parent.options, opts)

	local statements = self._statements
	if not statements or #statements == 0 then
		return nil
	end

	local qualID = mw.text.trim(mergedOpts.qual or ""):upper()
	if qualID == "" then qualID = nil end

	local out = propertyvalueandquals(statements, mergedOpts, qualID)
	return assembleoutput(out, mergedOpts, self.parent.qid, self.pid)
end

function WdStatements:getQual(qualID, opts)
	local mergedOpts = mergeOptions(self.parent.options, opts)

	local statements = self._statements
	if not statements or #statements == 0 then
		return nil
	end

	local out = propertyvalueandquals(statements, mergedOpts, qualID)
	return assembleoutput(out, mergedOpts, self.parent.qid, self.pid)
end

function WdStatements:getRawQual(qualID)
	local ret = {}
	for _,s in pairs(self._statements) do
		local qual_t = {}
		if s.qualifiers and s.qualifiers[qualID]  then
			for _,q in pairs(s.qualifiers[qualID]) do
				if q.snaktype == "value" then
					qual_t[#qual_t + 1] = rawValueOrDF(q, self.parent.options)
				else
					qual_t[#qual_t + 1] = q.snaktype
				end
			end
		end
		ret[#ret + 1] = qual_t
	end
	return ret
end

function WdStatements:getRawValue(opts)
	local mergedOpts = mergeOptions(self.parent.options, opts)
	local ret = {}
	for _,v in pairs(self._statements) do
		local datasnak = v.mainsnak or v
		if datasnak.snaktype=="value" then
			ret[#ret + 1] = rawValueOrDF(v, mergedOpts)
		else
			ret[#ret + 1] = datasnak.snaktype
		end
	end
	return ret
end

function WdStatements:get(index)
	local ret = WdStatement:new()
	ret.parent = self.parent
	ret.filtered_by = ret.filtered_by
	ret._statement = self._statements[index]
	ret.pid = ret.pid
	return ret
end

function WdStatements:iter()
  local i = 0
  local n = self._statements and #self._statements or 0
  return function()
    i = i + 1
    if i <= n then
      return i, self:get(i)
    end
  end
end

function WdStatements:ipairs()
  return self:iter()
end

function WdStatements:getBestOne()
	local orderd_statements = orderbyrank(self._statements)
	local ret =  WdStatement:new() --setmetatable({}, WdStatement)
	ret.parent = self.parent
	ret.filtered_by = ret.filtered_by
	ret._statement = orderd_statements[1]
	ret.pid = ret.pid
	return ret
end
-------------------------------------------------------------------------------
-- WdItem Class Definition
-------------------------------------------------------------------------------

local WdItem = class()

function WdItem:__tostring()
	return "WdItem: " .. (self.qid or "no QID")
end

function WdItem:UpdateOptions(in_newOpts)
	local newOpts = in_newOpts or {}
	for k, v in pairs(newOpts or {}) do
		self.options[k] = v
	end
	-- Set default options
	if newOpts.lang then
		self.options.lang = findLang(newOpts.lang)
	end

	if (newOpts.lang and not self.options.lang) or
		(not newOpts.lang and newOpts.langs and #newOpts.langs > 0) then

		for _, l in ipairs(newOpts.langs) do
			self.options.lang = findLang(l)
			if self.options.lang then
				break;
			end
		end
	end

	if not self.options.lang then
		self.options.lang = findLang();
	end

	if newOpts.rank then
		self.options.reqranks = setRanks(self.options.rank)
	end

	if not self.options.reqranks then
		self.options.reqranks = setRanks('preferred normal')
	end
end

function WdItem:init(qid, options,snak)
	if qid == "" then qid = nil; end
	self.qid = qid
	self.snak = snak
	self.options = options or {}
	self:UpdateOptions(options)
	return self
end

function WdItem:newFromSnaks(snakTable, options)
	local self = WdItem:new(nil, options or {}, snakTable)
	self:UpdateOptions(options)
	return self
end

function WdItem:setOptions(newOpts)
	self:UpdateOptions(newOpts)
end

function WdItem:getStatements(pid, opts)
	local mergedOpts = mergeOptions(self.options, opts or {})
	local statements

	local ret = WdStatements:new()
	ret.parent = self
	ret.filtered_by = {}
	ret._statements = {}
	ret.pid = pid

	if self.snak and self.snak[pid] then
		statements = self.snak[pid]
	elseif not self.qid or not mw.wikibase then
		statements = {}
	elseif mergedOpts.reqranks and mergedOpts.reqranks.best then
		statements = mw.wikibase.getBestStatements(self.qid, pid) or {}
	else
		statements = mw.wikibase.getAllStatements(self.qid, pid) or {}
		local filtered_statements = {}
		if not (mergedOpts.reqranks.deprecated == true and mergedOpts.reqranks.preferred == true and mergedOpts.reqranks.normal == true) then
			for _,s in pairs(statements) do
				if mergedOpts.reqranks[s.rank] then
					filtered_statements[#filtered_statements + 1] = s
				end
			end
		end
		statements = filtered_statements
	end

	if #statements > 0 and mergedOpts.qualifiedaspossible and mergedOpts.qualifiedaspossible ~= {} then
		local filtered_statements = {}
		for q,qv in pairs(mergedOpts.qualifiedaspossible) do
			filtered_statements = filterbyqualifier(statements, q, qv)
			if #filtered_statements > 0 then
				ret.filtered_by[#ret.filtered_by + 1] = {[q] = qv}
				statements = filtered_statements
			end
		end
	end

	if #statements > 0 and mergedOpts.qualified and mergedOpts.qualified ~= {} then
		for q,qv in pairs(mergedOpts.qualified) do
			statements = filterbyqualifier(statements, q, qv)
			ret.filtered_by[#ret.filtered_by + 1] = {[q] = qv}
			if #statements == 0 then break; end
		end
	end

	ret._statements = statements
	return ret
end

function WdItem:getValue(pid, opts)
	local mergedOpts = mergeOptions(self.options, opts)

	local statements = self:getStatements(pid, mergedOpts):getStatmentsTable()
	
	if not statements or #statements == 0 then
		return nil
	end

	local qualID = mw.text.trim(mergedOpts.qual or ""):upper()
	if qualID == "" then qualID = nil end

	local out = propertyvalueandquals(statements, mergedOpts, qualID)
	return assembleoutput(out, mergedOpts, self.qid, pid)
end

function WdItem:getValueFromSnaks(pid, opts)
	if not self.snak or not self.snak[pid] then
		return nil
	end

	local mergedOpts = mergeOptions(self.options, opts)
	
	local props = self.snak[pid]
	local out = propertyvalueandquals(props, mergedOpts)
	return assembleoutput(out, mergedOpts, nil, pid)
end

function WdItem:getPropertyIDsTable(pid, opts)
	local mergedOpts = mergeOptions(self.options, opts)

	mergedOpts.noicon = tostring(parseParam(mergedOpts.noicon or "", true))
	
	local statements = self:getStatements(pid, opts)
	if not statements or #statements == 0 then return {} end
	
	local onlysrc = parseParam(mergedOpts.onlysourced or mergedOpts.onlysourced, true)
	local maxvals = tonumber(mergedOpts.maxvals) or 0
	
	local out = {}
	for i, v in ipairs(statements) do
		local snak = v.mainsnak  or v
		if (snak.datatype == "wikibase-item")
			and (v.rank and mergedOpts.reqranks[v.rank:sub(1, 1)])
			and (snak.snaktype == "value")
			and (sourced(v) or not onlysrc) then
			out[#out+1] = snak.datavalue.value.id
		end
		if maxvals > 0 and #out >= maxvals then break end
	end
	
	return out
end

function WdItem:getPropertyIDs(pid, opts)
	local out = WdItem:getPropertyIDsTable(pid, opts)
	if #out == 0 then
		return nil
	end
	return assembleoutput(out, mergeOptions(self.options, opts), self.qid, pid)
end

function WdItem:getPropOfProp(prop1, prop2, opts)

	local mergedOpts = mergeOptions(self.options, opts)
	if not self.qid then return nil end
	local maxvals = tonumber(mergedOpts.maxvals) or 0
	local prop1Values = self:getStatements(prop1, opts):getRawValue()
	if #prop1Values == 0 then return nil end

	local out = {}
	for k, qid2 in ipairs(prop1Values) do
		local item2 = WdItem:new(qid2, mergedOpts)
		local prop2Values = item2:getStatements(prop2):getStatmentsTable()
		if prop2Values and prop2Values[1] then
			local out2 = propertyvalueandquals(prop2Values, mergedOpts, mergedOpts.qual)
			out[#out+1] = assembleoutput(out2, mergedOpts, qid2, prop2)
		end
		if maxvals > 0 and #out >= maxvals then break end
	end
	
	return assembleoutput(out, mergedOpts, self.qid, prop1)
end

function WdItem:getRawPropOfProp(prop1, prop2, opts)

	local mergedOpts = mergeOptions(self.options, opts)
	if not self.qid then return nil end
	
	local prop1Values = self:getStatements(prop1, opts):getRawValue()
	if #prop1Values == 0 then return nil end

	local out = {}
	for k, qid2 in ipairs(prop1Values) do
		local item2 = WdItem:new(qid2, mergedOpts)
		local prop2Values = item2:getStatements(prop2):getRawValue()
		for _,val in ipairs(prop2Values) do
			if not in_array(val,out) then
				out[#out + 1] = val
			end
		end
	end
	
	return out
end

function WdItem:getLangOfProp(pid)
	if not pid then return {}; end
	local out = {}
	local props =  self.snak and self.snak[pid] or (self.qid and mw.wikibase.getAllStatements(self.qid, pid)) or {}
	for _, v in ipairs(props) do
		local datasnak = v.mainsnak or v
		if datasnak.datatype == "monolingualtext" and datasnak.datavalue then
			out[#out + 1] = datasnak.datavalue.value.language
		end
	end
	return out
end

function WdItem:followQid(props, all)
	all = parseParam(all, false)
	props = (props or ""):upper()
	
	if not self.qid then return nil end
	if props == "" then return self.qid end
	
	local out = {}
	for p in mw.text.gsplit(props, "%p") do
		p = mw.text.trim(p)
		for i, v in ipairs(mw.wikibase.getBestStatements(self.qid, p)) do
			local linkedid = v.mainsnak.datavalue and v.mainsnak.datavalue.value and v.mainsnak.datavalue.value.id
			if linkedid then
				if all then
					out[#out+1] = linkedid
				else
					return  WdItem:new(linkedid)
				end
			end
		end
	end
	
	if #out > 0 then
		return table.concat(out, " ")
	else
		return self
	end
end

-------------------------------------------------------------------------------
-- Public API - WdItem Constructors
-------------------------------------------------------------------------------

p.WdItem = WdItem

function p.newItem(qid, opts, snak )
	return WdItem:new(qid, opts, snak)
end

function p.newSnakItem(snakTable, opts)
	return WdItem:newFromSnaks(snakTable, opts)
end

return p