وحدة:Wikidata2/نسخة

من ويكيبيديا، الموسوعة الحرة
اذهب إلى: تصفح، ‏ ابحث
توثيق الوحدة[أنشئ] [استخدامات]
يمكن إنشاء توثيق الوحدة في صفحة الشرح
-- Den ordning fallback language hämtas, om svensk label saknas. Engelska först, därefter bokmål, danska, etc...
-- local fallback = {'en', 'nb', 'da', 'nn', 'de', 'fr', 'es', 'it', 'pt'}
local formatera = require('وحدة:Math')
local wikidata2 = require('وحدة:Wikidata2')

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-datatype"] = "Unknown datatype.",
		["unknown-entity-type"] = "Unknown entity type.",
		["unknown-value-module"] = "You must set both value-module and value-function parameters.",
		["unknown-claim-module"] = "You must set both claim-module and claim-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.",
		["claim-module-not-found"] = "The module pointed by claim-module not found.",
		["claim-function-not-found"] = "The function pointed by claim-function not found."
    },
    ["somevalue"] = "", --''غير محدد''
    ["novalue"] =''--قيمة مجهولة
}

local sortingproperties = {'P585','P571','P580','P569','P582','P570'}
local cateref = ''

function catewikidatainfo(options)
	local prop = options.property
	local catewikidatainfo = ''
return catewikidatainfo 
end

function formatcharacters(label, options)
	local formatcharacters = options.formatcharacters
	if options.firstversalisering and options.num == 1 then 
		formatcharacters = options.firstversalisering
	end
	if not formatcharacters or formatcharacters == '' then
		return label
	end
	if formatcharacters == 'lcfirst' then
		return mw.getCurrentFrame():preprocess("{{lcfirst: " .. label .. " }}")
	elseif formatcharacters == 'ucfirst' then
		return mw.language.getContentLanguage():ucfirst( label )
	elseif formatcharacters == 'lc' then
		return mw.getCurrentFrame():preprocess("{{lc: " .. label .. " }}")
	elseif formatcharacters == 'uc' then
		return mw.getCurrentFrame():preprocess("{{uc: " .. label .. " }}")
	end
	return label
end
function getqualifierbysortingproperty(claim, sortingproperty)
	for k, v in pairs(sortingproperty) do
		if claim.qualifiers and claim.qualifiers[v] and claim.qualifiers[v][1].snaktype == 'value' then
			return claim.qualifiers[v][1].datavalue.value.time 
		end
	end
	return nil
end

function getDate(claim, options)
	local sortingproperty = sortingproperties
	if type(options.sortingproperty) == 'table' then
		sortingproperty = options.sortingproperty
	elseif type(options.sortingproperty) == 'string' then
		sortingproperty = {options.sortingproperty}
	end
	return getqualifierbysortingproperty(claim, sortingproperty) 
end

function getDateArb(claim, options)
	local sortingproperty = options.sortingproperty or 'P569'
	if claim.mainsnak.snaktype == 'value' then
		local item = claim.mainsnak.datavalue.value['numeric-id']
		if claim.mainsnak.datavalue.value['entity-type'] == 'item' then
			item = 'Q' .. item
		elseif claim.mainsnak.datavalue.value['entity-type'] == 'property' then 
			item = 'P' .. item
		end
		return formatStatements({property = sortingproperty, entityId = item, enbarten = 'true', sortbytime = 'chronological', noref = 'true'})
	end
end
function descriptionIn(langcode , id) -- returns item description for a given language
	local lan = langcode or 'ar'
	if not mw.wikibase then return nil end
	local description, lange = mw.wikibase.getDescriptionWithLang( id )
	if lange == lan
	then
		return description
	else
		return nil
	--return str
	end
	--[[local entity = mw.wikibase.getEntityObject(id)
		if entity
		and entity.descriptions 
		and entity.descriptions[''..lan..'']
		and entity.descriptions[''..lan..''].value 
		then
			local lang = entity.descriptions[''..lan..'']
			if lang['language'] == lan then
			return entity.descriptions[''..lan..''].value
			else return nil end
		end
	]]
end

function labelIn(langcode,id) -- returns item label for a given language
	if not mw.wikibase then return nil end
	local lan = langcode or 'ar'
	local label, lange = mw.wikibase.getLabelWithLang( id )
	if lange == lan
	then
		return label
	else
		return nil
	--return str
	end
	--[[local entity = mw.wikibase.getEntityObject(id)
		if entity
		and entity.labels 
		and entity.labels[''..lan..'']
		and entity.labels[''..lan..''].value 
		then
			local lang = entity.labels[''..lan..'']
				if lang['language'] == lan then
				return entity.labels[''..lan..''].value
				else return nil end
		end
	]]
end

function comparedates(a, b) 
	if a and b then
		return a > b
	elseif a then
		return true
	end
end

function preferqualifier(claims, options)
	local claims2 = {}
	for i, statement in pairs( claims ) do -- 
		if statement.qualifiers and statement.qualifiers[options.preferqualifier:upper()] then
			if options.preferqualifiervalue and options.preferqualifiervalue ~= '' then
				local active = false
				for k, t in pairs(mw.text.split(options.preferqualifiervalue,',')) do
					for j, value in pairs(formatStatements({property=options.preferqualifier:upper(), raw = 'true',  formattsing = 'raw'}, statement.qualifiers)) do
						if value.item == t and not active then
						--if value == t and not active then
							table.insert( claims2, statement)
							active = true
						end
					end
				end
			else
				table.insert( claims2, statement)
			end
		end
	end
	return claims2
end

function getqualifierbysortingproperty2(claim, options)
	local sortingproperty = options.sortingproperty
	if type(options.sortingproperty) == 'string' then
		sortingproperty = {options.sortingproperty}
	end
	for k, v in pairs(sortingproperty) do
		if claim.qualifiers and claim.qualifiers[v] and claim.qualifiers[v][1].snaktype == 'value' then
			return claim.qualifiers[v][1].datavalue.value.time 
		end
	end
	return nil
end

function sortbyqualifiernumber(claims, options)
	table.sort(claims, function(a,b)
		local timeA = getqualifierbysortingproperty2(a, options)
		local timeB = getqualifierbysortingproperty2(b, options)
		if options.sortbynumber == 'inverted' then
			return comparedates(timeB, timeA)
		else
			return comparedates(timeA, timeB)
		end
	end
	)
	return claims
end

function sortbyqualifier(claims, options)
	table.sort(claims, function(a,b)
		local timeA = getDate(a, options)
		local timeB = getDate(b, options)
		if options.sortbytime == 'inverted' then
			return comparedates(timeB, timeA)
		else
			return comparedates(timeA, timeB)
		end
	end
	)
	return claims
end

function sortbyarb(claims, options)
mw.log("sortbyarb: " .. options.sortbyarbitrary)
	table.sort(claims, function(a,b)
		local timeA = getDateArb(a, options)
		local timeB = getDateArb(b, options)
		if options.sortbyarbitrary == 'inverted' then
			return comparedates(timeB, timeA)
		else
			return comparedates(timeA, timeB)
		end
	end
	)
	return claims
end

function getEntityFromId( id )
        if not mw.wikibase then return nil end
	if id then 
		return mw.wikibase.getEntityObject( id )
	else
		return mw.wikibase.getEntityObject() 
	end
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 formatError( key )
    return i18n.errors[key]
end

function formatOneStatement( statement , ref, options)
	local vava = nil
	local stat = formatStatement( statement, options )
	if stat then
		local s = stat.value
		local d = stat.datum
		local tf = stat.tifr
		local awardqual = stat.foto
		local pr = stat.pr
		local utgivort = stat.utgivort
		local ro = stat.ro
		local qp1a = stat.qp1a
		local onlyqualifier = stat.onlyqualifier
		local qp1 = stat.qp1
		local qp2 = stat.qp2
		local qp3 = stat.qp3
		local qp4 = stat.qp4
		local qp5 = stat.qp5
		--local PQual = stat.PQual

		local amatch =stat.amatch
		local goal =stat.goal

		local start2 = stat.start1
		local finish2 = stat.finish1
		local before2 = stat.before1
		local after2 = stat.after1
		local constituency2 = stat.constituency1
		local series2 = stat.series1
		local electedin2 = stat.electedin1
		local P1001 = stat.pp1001
		local P642 = stat.PP642

		if s == '' then s = nil end
		if s then
			if options.template and options.template ~= '' then
					s =	mw.getCurrentFrame():expandTemplate{ title = options.template 
						, args ={stat.QQ1
							,s
							,stat.QQ2
							,stat.QQ3
							,stat.QQ4
							,stat.QQ5
							,stat.QQ6
							,stat.QQ7
							,stat.QQ8
							,stat.QQ9
							,stat.QQ10
							,entityId = options.entityId
							,id = stat.ID} }
			end
			if options.football and options.football ~= '' then
				s =mw.getCurrentFrame():expandTemplate{ title = "صندوق معلومات سيرة كرة قدم/سطر فريق", args = {(start2 or ''),(finish2 or '') ,s,amatch,goal } }
			end
			
			if options.office and options.office ~= '' then
				s = mw.getCurrentFrame():expandTemplate{ title = "معلومات صاحب منصب/منصب ويكي بيانات/نواة", 
					args = {office = s
						, termstart = start2
						, termend = finish2
						, constituency = stat.constituency1
						, predecessor = stat.before1
						, successor = stat.after1
						, series= stat.series1
						,electedin=stat.electedin1
						,jurisdiction=stat.pp1001
						,entityId=options.entityId
						} } 

			end
			if options.office2 and options.office2 ~= '' then
				s = mw.getCurrentFrame():expandTemplate{ title = "معلومات صاحب منصب/منصب ويكي بيانات2", args = {office = s, termstart = start2, termend = finish2, constituency = constituency2, predecessor = before2, successor = after2, series= series2, P642= P642} }
			end
					if qp1 and options.qual1 and options.qual1 and qp1a and options.qual1a and options.qual1a ~= '' then
						s = s .. '، '.. (options.qual1pref or '') .. qp1 ..'، ' .. (options.qp1apref or '') .. qp1a
					else
					if qp1 and options.qual1 and options.qual1 ~= '' then
						s = s .. '، '.. (options.qual1pref or '') .. qp1
					else
					if qp1a and options.qual1a and options.qual1a ~= '' then
						s = s .. '، '.. (options.qp1apref or '') .. qp1a
					end end end
					if qp2 and options.qual2 and options.qual2 ~= '' then
						s = s .. ' ('.. (options.qual2pref or '') .. qp2 .. ')' 
					end
					if qp3 and options.qual3 and options.qual3 ~= '' then
						s = s ..  ' ('.. (options.qual3pref or '') .. qp3 .. ')' 
					end
					if qp4 and options.qual4 and options.qual4 ~= '' then
						s = s ..' ('.. (options.qual4pref or '') .. qp4 .. ')' 
					end
					if qp5 and options.qual5 and options.qual5 ~= '' then
						s = s .. ' ('.. (options.qual5pref or '') .. qp5 .. ')'
					end
					if options.justthisqual then
						if onlyqualifier then 
							s = onlyqualifier 
						else
							if not options.justthisqual ~= '' then s = nil  end-- We need only the qualifier
						end
					end
					if ro and options.withro and options.withro ~= '' then
						s = s ..  ' (' .. ro .. ')'
					end
					if d and options.withdate and options.withdate ~= '' then
						if options.withdate == 'y' then
							s = s ..  ' (سنة ' .. d .. ')'
						else
							s = s .. ' (' .. d .. ')'
						end
					end
					if awardqual and options.awardqua and options.awardqua ~= '' then
						s = s ..' (' .. awardqual .. ')'
					end
					if tf and options.withintervall and options.withintervall ~= '' then
						if options.withintervall == 'gift' then
							s = s .. mw.text.tag('br') .. '(g. ' .. tf .. ')'
						else
						if options.withintervall == 'before' then
							s =  '(' .. tf .. ') ' .. s
						else
							s = s .. ' (' .. tf .. ')'
						end end
					end
			
					if utgivort and options.withutgivort and options.withutgivort ~= '' then
						if options.withutgivort == 'قوسين' then
							s = s .. ' ' ..  ' (' .. utgivort .. ')'
						else
							s = s .. ' ' .. utgivort
						end
					end
					if options.getsimpleproperty == 'född' and pr and pr ~= '' then
						s = s .. ' ' ..  '(f. ' .. pr .. ')'
					end
					if options.getsimpleproperty == 'parentes' and pr and pr ~= '' then
						s = s .. ' ' .. mw.text.tag('span', {}, '(' .. pr .. ')')
					end
					if options.getsimpleproperty == 'avnågon' and pr and pr ~= '' then
						s = s .. ' ' .. mw.text.tag('span', {}, ' av ' .. pr .. '')
					end
					
					--if PQual and PQual ~= '' then
					--	if options.preferqualifiervalue == Q 
							--then s = s .. ' ' .. Q
							--else s = nil
						--end
					--end

			if type(ref) == 'table' or (options.noref and options.noref ~='') or (options.justthisqual and options.justthisqual ~='') -- or (options.preferqualifiervalue and options.preferqualifiervalue ~='') 
				then --Do not look for references if the call is made from a reference
					--table.insert( formattedStatements, s )
					vava =  s 
			else
				local t = formatReferences( statement, options )
				stat.ref = t
					if options.justref and options.justref ~= '' 
					then
						--table.insert( formattedStatements, t )
						vava =  t
					else 
						--table.insert( formattedStatements, s .. t )
						vava =  s .. t 
					end
			end
		end
	--table.insert(statementsraw, stat)
	end
	
	return { v = vava , raw = stat}
end

function formatStatements( options, ref )
   	local formattedStatements = {}
   	local claims = {}
   	if not options.property then
       	return formatError( 'property-param-not-provided' )
   	end

    if type(ref) == 'table' then -- för de fall där funktionen anropas och alla claims redan finns i en tabell
		claims = ref[options.property] or {}
	else
 
    	--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[options.property:upper()] then
        	return '' --TODO error?
    	end
 
    	--Format statement and concat them cleanly
		if options.rank == 'best' or not options.rank then 
			claims = entity:getBestStatements( options.property:upper() )
		elseif options.rank == 'valid' then
			for i, statement in pairs( entity.claims[options.property:upper()] ) do
	    		if statement.rank == 'preferred' or statement.rank == 'normal' then
    				table.insert( claims, statement )
    			end
			end
		elseif options.rank == 'all' then
			for i, statement in pairs( entity.claims[options.property:upper()] ) do
				table.insert( claims, statement )
			end
		else
			for i, statement in pairs( entity.claims[options.property:upper()] ) do
				if statement.rank == options.rank then
					table.insert( claims, statement )
				end
			end
		end
		if options.avoidqualifier then
			local claims2 = {}
			for i, statement in pairs( claims ) do	
				if not statement.qualifiers or not statement.qualifiers[options.avoidqualifier:upper()] then
					table.insert( claims2, statement)
				end
			end
			claims = claims2
		end
		if options.preferqualifier and options.preferqualifier ~= '' then
			claims = preferqualifier(claims, options)
		end		--om det finns vissa statements som har en qualifier som säger "språk = svenska", ta bara med dessa
		--alternativt om det finns statements som har en qualifier som säger "skriptsystem == latinska alfabetet"
		if not options.langpref or options.langpref == '' then
			local claims2 = {}
			for i, statement in pairs( claims ) do
				if statement.qualifiers and statement.qualifiers.P407 then
					for k, v in pairs( statement.qualifiers.P407 ) do
						if v.snaktype == 'value' and v.datavalue.value['numeric-id'] == 13955 then -- Q13955 = 'العربية'
							table.insert( claims2, statement )
						end
					end
				elseif statement.qualifiers and statement.qualifiers.P282 then
					for k, v in pairs( statement.qualifiers.P282 ) do
						if v.snaktype == 'value' and v.datavalue.value['numeric-id'] == 8196 then -- Q8196 = 'أبجدية عربية'
							table.insert( claims2, statement )
						end
					end
				end
			end
			if #claims2 > 0 then
				claims = claims2
			end
		end
		if options.sortbynumber == 'chronological' or options.sortbynumber == 'inverted' then
			claims = sortbyqualifiernumber(claims, options)
		elseif options.sortbytime == 'chronological' or options.sortbytime == 'inverted' then
			claims = sortbyqualifier(claims, options)
		elseif options.sortbyarbitrary == 'chronological' or options.sortbyarbitrary == 'inverted' then
			claims = sortbyarb(claims, options)
		end
	end
	if options.enbarten and options.enbarten ~='' and #claims > 1 then
		if options.enbarten == '2' then
			claims = {claims[2]}
			elseif options.enbarten == '3' and #claims > 2 then
			claims = {claims[3]}
			elseif options.enbarten == '4' and #claims > 3 then
			claims = {claims[4]}
			elseif options.enbarten == '5' and #claims > 4 then
			claims = {claims[5]}
			elseif options.enbarten == '6' and #claims > 5 then
			claims = {claims[6]}
			elseif options.enbarten == '7' and #claims > 6 then
			claims = {claims[7]}
			elseif options.enbarten == '8' and #claims > 7 then
			claims = {claims[8]}
			elseif options.enbarten == '9' and #claims > 8 then
			claims = {claims[9]}
			else
			claims = {claims[1]}
		end
	end
	local statementsraw = {}
	
	if claims then
			--==========================================
		if options['property-module'] or options['property-function'] then
			if not options['property-module'] or not options['property-function'] then
				return formatError( 'unknown-property-module' )
			end
			local formatter = require ('Module:' .. options['property-module'])
			if not formatter then
				return formatError( 'property-module-not-found' )
			end
			local fun = formatter[options['property-function']]
			if not fun then
				return formatError( 'property-function-not-found' )
			end

			mw.log("work with property-module: " .. options['property-module'] .. "|" .. options['property-function'])
			return fun( claims, options )
		else 
			--==========================================
			for i, statement in pairs( claims ) do
				options.num = i
				local va = formatOneStatement( statement,ref ,  options )
				if va.v then
					table.insert( formattedStatements, va.v )
				end
				table.insert( statementsraw, va.raw )
			end
		end
	end
	local Separator = options.separator 
	if not options.separator then Separator = "، و" end
	
	local Conjunction = options.conjunction
	if not options.conjunction then Conjunction = "، و" end

	if Conjunction and Conjunction == "br" then Conjunction =  "\n" end
	if Separator and Separator == "br" 
	then 
		Separator = "\n*" 
		Conjunction = "\n*" 
	end
	local tot = mw.text.listToText( formattedStatements, Separator, Conjunction )
	

	if tot == '' then tot = nil end
	if options.raw and options.raw ~= '' then
		return statementsraw
	end
	if options.numberofclaims and options.numberofclaims ~= '' then
		return #formattedStatements
	end
	return tot
end


function formatReferences( statement, options )
	local reference = {}
	if statement.references then
		local cite = require('وحدة:Cite/نسخة')
		for i, ref in pairs(statement.references) do
			local items, s = {}, nil
			if ref.snaks then

				if ref.snaks.P248 then
					for j, prop in pairs(ref.snaks.P248) do
						if prop.snaktype == 'value' then
							table.insert(items, 'Q' .. prop.datavalue.value['numeric-id'])
					end end
				elseif ref.snaks.P143 then
					for j, prop in pairs(ref.snaks.P143) do
						if prop.snaktype == 'value' then
						table.insert(items, 'Q' .. prop.datavalue.value['numeric-id'])
					end end
				end
				s = cite.citeitem( items , ref.snaks , ref.hash , options )

			end
			table.insert(reference, s)

		end
	end
	return table.concat(reference)
end

function formatStatement( statement, options )
       if options['claim-module'] or options['claim-function'] then
        if not options['claim-module'] or not options['claim-function'] then
            return {value = formatError( 'unknown-claim-module' )}
        end
        local formatter = require ('Module:' .. options['claim-module'])
        if not formatter then
            return {value = formatError( 'claim-module-not-found' )}
        end
        local fun = formatter[options['claim-function']]
        if not fun then
            return {value = formatError( 'claim-function-not-found' )}
        end
        return {value = fun( statement, options )}
    elseif  statement.type == 'statement' then
    	local s = formatSnak( statement.mainsnak, options )
    		if s and s ~= ''  then
    	if statement.qualifiers then
			function qua(p)
				if p and p ~='' then return (formatStatements({property =p,enlabelcate = 't', illwd2='t',enbarten = (enbarten or '')
				,modifytime = (modifytime or 'longdate'), noref = 'true'}, statement.qualifiers) or '') end
			end

			if options.template and options.template ~= '' then
					s.ID = getEntityIdFromValue(statement.mainsnak.datavalue.value)
					mw.log("id: " .. s.ID)
					s.QQ1 = qua(options.Q1)
					mw.log(s.QQ1 )
					s.QQ2 = qua(options.Q2)
					s.QQ3 = qua(options.Q3)
					s.QQ4 = qua(options.Q4)
					s.QQ5 = qua(options.Q5)
					s.QQ6 = qua(options.Q6)
					s.QQ7 = qua(options.Q7)
					s.QQ8 = qua(options.Q8)
					s.QQ9 = qua(options.Q10)
					s.QQ10 = qua(options.Q10)
			end
			if statement.qualifiers.P1350 or statement.qualifiers.P1351 then
				s.amatch = qua("P1350")
				s.goal = qua("P1351")
			end
			if statement.qualifiers.P580 or statement.qualifiers.P582 or statement.qualifiers.P1365 or statement.qualifiers.P1366 then
				s.start1 = qua("P580")
				s.finish1 = qua("P582")
				s.before1 = qua("P1365")
				s.after1 = qua("P1366")
				s.constituency1 = qua("P768")
				s.series1 = qua("P1545")
				s.electedin1 = qua("P2715")
				s.pp1001 = qua("P1001")
				s.pp108 = qua("P108")
				s.pp642 = qua("P642")
			end
    		if statement.qualifiers.P585 then
    			s.datum = qua("P585",options.modifyqualifiertime)
			end
                             local qwe = options.qwer
			if statement.qualifiers.qwe  then
    			s.ro =qua(qwe)
			end
			if statement.qualifiers.P574 then
				s.dateoftaxpub = qua("P574",options.modifyqualifiertime)
			end
			if statement.qualifiers.P405 then
				local auktorer = {}
				for i, j in pairs(statement.qualifiers.P405) do
					if j.snaktype == 'value' then
						local item = 'Q' .. j.datavalue.value['numeric-id']
						local auktorsnamn = formatStatements({property = "P428", entityId = item, noref = 'true', enbarten = 'true'})
						if auktorsnamn and auktorsnamn ~= '' then
							table.insert(auktorer, formatEntityId(item, {label = auktorsnamn}).value)
						else
							table.insert(auktorer, formatEntityId(item, {}).value)
						end
					end
				end
				s.auktor = mw.text.listToText(auktorer, ', ', ' & ')
			end	
			if statement.qualifiers.P580 then 
				local f = qua("P580",options.modifyqualifiertime)
				if statement.qualifiers.P582 
 				then
				local t =  qua("P582",options.modifyqualifiertime)
					s.tifr = f .. '–' .. t
				else 
				s.tifr = 'منذ '.. f 
				end
			end
			if statement.qualifiers.P585 or statement.qualifiers.P1346 then
				local fo = qua("P585",options.modifyqualifiertime)
				local to = qua('P1346')
				s.foto = fo .. ' ' .. mw.text.tag('span', {}, ' ' .. to  .. '')
			end
			if statement.qualifiers.P291 then       -- خاصية بلد النشر
				s.utgivort = formatStatements({property = "P291",illwd2 ='t', noref = 'true', separator = options.qualifierseparator, conjunction = options.qualifierconjunction}, statement.qualifiers)
			end
			if statement.qualifiers.P2096 then
				s.bildtext = formatStatements({property = "P2096",illwd2 ='t',  noref = 'true', langpref = (options.langpref or 'ar')}, statement.qualifiers)
			end
			if s then
				if options.qual1 and options.qual1 ~= '' and statement.qualifiers[options.qual1] then         -- عرض تصفيات لبنود الخاصية
					s.qp1 = formatStatements({property = options.qual1, illwd2 ='t', noref = 'true', separator = options.qualifierseparator, conjunction = options.qualifierconjunction,size =options.size,image =options.image}, statement.qualifiers)
				end
				if options.qual1a and options.qual1a ~= '' and statement.qualifiers[options.qual1a] then
					s.qp1a = formatStatements({property = options.qual1a,illwd2 ='t',  noref = 'true', separator = options.qualifierseparator, conjunction = options.qualifierconjunction}, statement.qualifiers)
				end
				if options.justthisqual and options.justthisqual ~= '' and statement.qualifiers[options.justthisqual] then
					s.onlyqualifier = formatStatements({property = options.justthisqual ,illwd2 ='t',  noref = 'true', separator = options.qualifierseparator, conjunction = options.qualifierconjunction}, statement.qualifiers)
				end
				if options.qual2 and options.qual2 ~= '' and statement.qualifiers[options.qual2] then
					s.qp2 = formatStatements({property = options.qual2,illwd2 ='t',  noref = 'true', separator = options.qualifierseparator, conjunction = options.qualifierconjunction,size =options.size,image =options.image}, statement.qualifiers)
				end
				if options.qual3 and options.qual3 ~= '' and statement.qualifiers[options.qual3] then
					s.qp3 = formatStatements({property = options.qual3,illwd2 ='t',  noref = 'true', separator = options.qualifierseparator, conjunction = options.qualifierconjunction}, statement.qualifiers)
				end
				if options.qual4 and options.qual4 ~= '' and statement.qualifiers[options.qual4] then
					s.qp4 = formatStatements({property = options.qual4,illwd2 ='t',  noref = 'true', separator = options.qualifierseparator, conjunction = options.qualifierconjunction}, statement.qualifiers)
				end
				if options.qual5 and options.qual5 ~= '' and statement.qualifiers[options.qual5] then
					s.qp5 = formatStatements({property = options.qual5,illwd2 ='t',  noref = 'true', separator = options.qualifierseparator, conjunction = options.qualifierconjunction}, statement.qualifiers)
				end
				--if options.preferqualifier and options.preferqualifier ~= '' and statement.qualifiers[options.preferqualifier] and options.preferqualifiervalue and options.preferqualifiervalue ~= '' then
				--	s.preferqualifier = formatStatements({property = options.preferqualifier, noref = 'true', formatting = 'raw' }, statement.qualifiers)
				--end
				
			end
	end
	
	end
		return s
	elseif not statement.type then
		return formatSnak( statement, options )
    end
	return {value = formatError( 'unknown-claim-type' )}
end
 
function formatSnak( snak, options )
    if snak.snaktype == 'somevalue' then
    	if options.somevalue then
    		if options.somevalue == '' then
    			return nil
    		else
    			return {value = options.somevalue}
    		end
    	end
        return {value =  i18n['somevalue']}
    elseif snak.snaktype == 'novalue' then
    	if options.novalue then
    		if options.novalue == '' then
    			return nil
    		else
    			return {value = options.novalue}
    		end
    	end
        return {value = i18n['novalue']}
    elseif snak.snaktype == 'value' then
    	local s = formatDatavalue( snak.datavalue, options, snak.datatype )
    	if s and s.value and options.prefix and options.prefix ~= '' then
    		s.value = options.prefix .. s.value
    	end
    	if s and s.value and options.suffix and options.suffix ~= '' then
    		s.value = s.value .. options.suffix
    	end
        if s and s.value and s.item and options.getsimpleproperty and options.getsimpleproperty ~= '' and options.getproperty and options.getproperty ~= '' then
        	local pr = formatStatements({property = options.getproperty, entityId = s.item, enbarten = options.getenbarten, noref = 'true', modifytime = options.getmodifytime, raw = options.getraw})
        	if pr then s.pr = pr end
        end
        return s
    else
        return {value = formatError( 'unknown-snak-type' )}
    end
end
 --[[ 
          datatype  wikibase-item  
 ]]



function formatwikibaseitem( datavalue, options, datatype )
		local item = getEntityIdFromValue( datavalue.value )
		local itemValue = formatEntityId( item , options ).value
		if options.formatting and options.formatting ~= '' 
		then
				if options.formatting == 'raw' then 
					return {value = item}
					
				elseif options.formatting == 'rawtotemplate' then 
					mw.log('options')
					mw.log(options)
					if options.rawtotemplate  and options.rawtotemplate ~= ''  then 
						return {value = mw.getCurrentFrame():expandTemplate{ title = options.rawtotemplate, args = {
							q = item , no1 = options.no1 or '' , no2 = options.no2 or ''
							
						}} .. '\n'
						}
					else
					end
				elseif options.formatting == 'fu' then 
					return {value = mw.getCurrentFrame():expandTemplate{ title = "Cycling race/stageclassification2", args = {item}}}
				elseif options.formatting == 'sitelink' then 
					return {value = formatsitelink(datavalue.value.id , options ) }
				elseif options.formatting == 'sitelink1' then 
					return {value = formatsitelink1(datavalue.value.id , options ) }
				else
					return {value = formatFromPattern( formatcharacters(datavalue.value, options), options )}
				end
		elseif options.property1 and options.property1 ~= '' then
				for i, statement in pairs( datavalue ) do
					local caca = formatStatements( {property =options.property1, itemyId = item, noref =options.noref ,rank=options.rank,pattern =options.pattern,size =options.size,image =options.image,noref='true',enbarten ='true' })
					local cooooca = (options.property1pref or '') ..''.. caca ..''.. (options.property1suff or '')
					if itemValue and itemValue  ~= '' then
						if caca and caca  ~= '' then return {value =  cooooca .. ' '.. itemValue	 } else return {value = itemValue  } end
					end
				end 
		elseif options.propertyimage and options.propertyimage ~= '' then
				for i, statement in pairs( datavalue ) do
					local caca = formatStatements( {property =options.propertyimage ,formatting=options.formattingpropertyimage, itemyId = item, noref =options.noref ,rank=options.rank,pattern =options.pattern,size =options.size,image =options.image,noref='true',enbarten ='true',nolink=options.nolink })
					if caca and caca  ~= '' then return {value =  caca } else end
				end 
		elseif options.property2 and options.property2 ~= '' then
				for i, statement in pairs( datavalue ) do
					local caca = formatStatements( 
						{property =options.property2
						, itemyId = item
						, noref =options.noref 
						,rank=options.rank
						,pattern =options.pattern
						,size =options.size
						,image =options.image
						,propertyimage =options.property3
						,enbarten ='true'
						})
					if itemValue and itemValue  ~= '' then
						if caca and caca  ~= '' then return {value =  caca .. ' '.. itemValue  } else return {value = itemValue  } end
					end
				end 
		elseif options.cateforjop and options.cateforjop ~= '' then
			for i, statement in pairs( datavalue ) do
				local caca = formatStatements(
					{property =options.cateforjop
					,itemyId = item
					,noref ='true'
					,rank=options.rank
					,pattern =options.pattern
					,size =options.size
					,image =options.image
					,propertyimage =options.cateforjop1
					,enbarten ='true' 
					,formattingpropertyimage=options.formattingcateforjop
					,nolink=options.nolink
					})
				if caca and caca  ~= '' then return {value =  caca	} else end

			end 
		else
			return {value = formatEntityId( item, options ).value, item = item}		
		end 
end
 --[[ 
          datatype  wikibase-property  
 ]]
function formatwikibaseproperty( datavalue, datatype, options )
	if options.formatting and options.formatting  ~= '' 
		then
			if options.formatting == 'raw' then 
				tid = getEntityIdFromValue( datavalue.value )
				else
			end
		else 
		tid =  formatEntityId( getEntityIdFromValue( datavalue.value ), options ).value
	end
	return {value = tid}
end
function formatcommonsMedia( datavalue, options, datatype )
        if options.image and options.image ~= '' then
        		return {value = '[[file:' .. datavalue.value  .. '|'.. (options.size or '120')..'px|'..'border'..']]' } 
        else
            return {value = formatcharacters(datavalue.value, options), label = datavalue.value}
        end
end
 --[[ 
          datatype math
 ]]
function formatmath( datavalue, options, datatype )
		 --return	{value = mw.text.tag('math', {}, ''.. datavalue.value..'') }
		 return	{value =mw.getCurrentFrame():callParserFunction( '#tag:math', ''.. datavalue.value..'' ) }
end
 --[[ 
        datatype  string  -  external-id
 ]]
 function formatstring( datavalue, options, datatype )
        if options.pattern and options.pattern ~= '' then
        		local patter = formatStatements( {property = "P1630", entityId = options.property, enbarten = 'true', noref = 'true',rank='all' }) -- get formatter URL
        		local ppp = formatFromPattern( datavalue.value, {pattern = patter} )
        		local plabel = mw.wikibase.label( options.property ) or ppp 
        	if options.pattern ==  "autourl" then -- like http://example.com/$1.html
        		 tid =  ppp
        	elseif options.pattern ==  "autourl2" then  -- like [http://example.com/$1.html $1]
        		 tid =  '[' .. ppp .. ' ' .. datavalue.value .. ']' 
        	elseif options.pattern ==  "autourl3"  then  -- like [http://example.com/$1.html http://example.com/$1.html]
        		 tid =  '[' .. ppp .. ' ' .. ppp .. ']' 
        	elseif options.pattern == "autourl4"  then
        		 tid =  '[' .. ppp .. ' ' .. plabel .. ']' 
        	else
            	 tid =  formatFromPattern( formatcharacters(datavalue.value, options), options )
            end
        else
             tid =  formatcharacters(datavalue.value, options)
        end
	return {value = tid}	
end
 --[[ 
        datatype  time
 ]]
function formattime( datavalue, options, datatype )
        local ModuleTime = require 'Module:wikidata2/time'
        local timen = datavalue.value 
        local modifytime = (options.modifytime or '')
        local tid = ModuleTime.getdate( timen , options)
       -- local tid =  mw.getCurrentFrame():preprocess(mall)
        if options.modifytime and options.modifytime ~= '' then
			if options.modifytime == 'q' then
				local mall = datavalue.value.time
				tid = mw.getCurrentFrame():preprocess(mall)
			elseif options.modifytime == 'precision' then
				local mall = datavalue.value.precision
				tid = mw.getCurrentFrame():preprocess(mall)

			end
		end
        return {value = tid}
        
        
end
--[[ 
        datatype  globe-coordinate
 ]] 
function formatcoordinate( datavalue, options, datatype )
        --local GlobeCoordinate = require 'Module:GlobeCoordinate'
        --return {value = GlobeCoordinate.newFromWikidataValue( datavalue.value ):toHtml()}

		local coord = datavalue.value
		local globetable = { Q2 = 'earth', Q111 = 'mars', Q405 = 'moon'}
	if options.formatting  and options.formatting  ~= '' then
		if options.formatting == 'latitude' then
			return {value =coord.latitude }
		elseif options.formatting == 'longitude' then
			return {value =coord.longitude }
		elseif options.formatting == 'dimension' then
			return {value =coord.dimension }
		elseif options.formatting == 'precision' then
			return {value =coord.precision}
		--elseif options.formatting == 'coord' then
			--return {value = }
		else

		end
		else
			return {value =mw.getCurrentFrame():expandTemplate{ title = "coord", args = {coord.latitude,coord.longitude,display=inline} }..catewikidatainfo(options) }
	end
end
 --[[ 
        datatype quantity
 ]] 
function formatquantity( datavalue, options, datatype )
		local amount, unit, cat = datavalue.value.amount, datavalue.value.unit, nil
		if unit then
			unit = unit:match('Q%d+')
		end
		local formatera = require('وحدة:Math')
		local number = formatera.newFromWikidataValue(datavalue.value)

		local unitraw = unit
		if unit then
			-- يتحقق اذا كان هناك اي اختصار لوحدة القياس
			local lab = options.label or formatStatements({property = 'P498', entityId = unit, enbarten = 'true', noref = 'true'}) or formatStatements({property = 'P558', entityId = unit, enbarten = 'true', langpref = options.langpref, noref = 'true'})
			if lab and ( not options.nounitshort or options.nounitshort == '' )  then
				local s = formatEntityId( unit, {label = lab, nolink = (options.nounitlink or options.nolink) })
				unit = s.value
				cat = s.cat
			else -- om det inte finns en förkortning
				local s = formatEntityId( unit, {nolink = options.nounitlink})
				unit = s.value
				cat = s.cat
			end
		end
	amount = mw.ustring.gsub( amount , '+', '' )
		return {value =amount  .. ' ' .. (unit or ''), amount = amount, unit = unit, unitraw = unitraw, cat = cat}
		
end

 --[[ 
       datatype  url
 ]]  

function formaturl( datavalue, datatype, options )
	local label = options.label or options.urllabel     
	va =  mw.ustring.gsub( datavalue.value, ' ', '_' )
	if not label and  options.property =='P856' then label = 'الموقع الرسمي' end
		if label and label ~= '' then
		pro = '[' .. va .. ' ' .. label .. ']' 
		else
		--	if property =='P856' then 	pro =  formatFromPattern( formatcharacters(va, options), {pattern = '[$1 الموقع الرسمي]'} )
			--	else
					pro = va
		--		end
		end
	return {value = pro }
end

 --[[ 
       datatype   monolingualtext
 ]] 
function formatmonolingualtext( datavalue, options, datatype )
	local langcode = datavalue.value.language
		local lang = mw.language.fetchLanguageName( langcode, 'ar'  )
		local text = datavalue.value.text --mw.text.tag('span', {title = lang }, datavalue.value.text)

		if options.showlang and options.showlang ~= '' then
			text = text ..  ' ('.. lang ..')'
		end
			if options.langpref and options.langpref ~= '' then
				if options.langpref == datavalue.value.language then return  {value =text} 
					elseif options.langpref =='justlang' then return  {value =lang}  
					elseif options.langpref =='langcode' then return  {value =langcode}
				end
			else 
				return  {value =text}
			end
			
end

function formatDatavalue( datavalue, options, datatype )
    --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 {value = formatError( 'unknown-value-module' )}
        end
        local formatter = require ('Module:' .. options['value-module'])
        if not formatter then
            return {value = formatError( 'value-module-not-found' )}
        end
        local fun = formatter[options['value-function']]
        if not fun then
            return {value = formatError( 'value-function-not-found' )}
        end
        return {value = fun( datavalue, datatype, options)}
    end
    --Default formatters
 		if datatype == 'wikibase-item' then return   formatwikibaseitem( datavalue, options, datatype ) 
 	elseif datatype == 'wikibase-property' then return   formatwikibaseproperty( datavalue, options, datatype ) 
 	elseif datatype == 'commonsMedia' then return   formatcommonsMedia( datavalue, options, datatype )
 	elseif datatype == 'math' then return       formatmath( datavalue, options, datatype )
 	elseif datatype == 'time' then return formattime( datavalue, options, datatype )
 	elseif datatype == 'string' or datatype == 'external-id' then return  formatstring( datavalue, options, datatype )
 	elseif datatype == 'globe-coordinate' then return  formatcoordinate( datavalue, options, datatype )
 	elseif datatype == 'quantity' then return   formatquantity( datavalue, options, datatype )
 	elseif datatype == 'url' then return   formaturl( datavalue, options, datatype )
 	elseif datatype == 'monolingualtext' then return  formatmonolingualtext( datavalue, options, datatype )
    else
        return {value = formatError( 'unknown-datatype' )}
    end
end

function formatlabel( entityId, options )
	local label = options.label
	if not label or label == '' 
		then 
			if options.arlabel and options.arlabel ~= ''
		then 
			label = labelIn('ar',entityId )
	else 
		label = mw.wikibase.label( entityId ) or nil
	end
	end
	--	label = mw.wikibase.label( entityId ) or nil
	--local label = options.label or labelIn('ar',entityId )
	--if label == '' then
	--	label = labelIn('ar',entityId ) or nil
	--end
	return label
end

function formatEntityId( entityId, options )
	local label = formatlabel( entityId, options )
    local link = mw.wikibase.sitelink( entityId )
    if link and (not options.nolink or options.nolink == '') then
        if label and label ~= '' then
            return {value = '[[' .. link .. '|' .. formatcharacters(label, options) .. ']]'.. catewikidatainfo(options), label = label }
        else
            return {value = '[[' .. formatcharacters(link, options) .. ']]'.. catewikidatainfo(options), label = link }
        end
    else
    	if label and label ~= '' 
    		then
    		local temp =formatcharacters(label, options)
    		local labelarabic = labelIn('ar',entityId )
    		if options.illwd2  and options.illwd2  ~= '' then
    			 if aar and aar ~= '' then
    				temp = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {labelarabic , id=entityId} }
					else 
					temp = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {id=entityId , target='en'} }
				end
    		end
    		return {value = temp , label = label}
    	else return ''
    	end
    	return '' --{value = entityId, cat = 'som har labels med Qid', label = entityId}
    end
end
 --[[ 
       function to get any link from any sister project
	local entity = mw.wikibase.getEntityObject(id)
	if entity
		and entity.sitelinks 
		and entity.sitelinks[''..site..'']
		and entity.sitelinks[''..site..''].site 
		and entity.sitelinks[''..site..''].title 
		then
			if entity.sitelinks[''..site..''].site == site 
			then
				link = entity.sitelinks[''..site..''].title
				mw.log("mw.wikibase.getEntityObject : " .. link)
			else 
				link = ''
			end
		end
 ]] 


function sitelink( id , wikisite )
	if not mw.wikibase then return '' end
	local site = wikisite
	if not site or site == "" then site = "arwiki" end
	local link = "" --mw.wikibase.sitelink( id , site )
	local entity = mw.wikibase.getEntityObject(id)
	if entity
		and entity.sitelinks 
		and entity.sitelinks[''..site..'']
		and entity.sitelinks[''..site..''].site 
		and entity.sitelinks[''..site..''].title 
		then
			if entity.sitelinks[''..site..''].site == site 
			then
				link = entity.sitelinks[''..site..''].title
				--mw.log("mw.wikibase.getEntityObject : " .. link)
			end
		end
	--mw.log("mw.wikibase.sitelink," .. "site: " .. site .. ": " .. link)
	return link
end

function formatsitelink( entityId, options )
    local label = labelIn('ar',entityId )
    local link = mw.wikibase.sitelink( entityId )
	if link and link ~= ''  
		then
			if label and label ~= ''  
				then
					return '[[' .. link .. '|'.. label .. ']]'
				else
					return '[[' .. link .. ']]'
			end
		else 
			--if link and link ~= ''  then
			--	return formatcharacters(link, options)
			--end
	end
end

function formatsitelink1( entityId, options )
    local link = mw.wikibase.sitelink( entityId )
	if link and link ~= ''  
		then
			if options.nolink and options.nolink ~= ''  
				then
					return  link 
				else
					return '[[' .. link .. ']]'
			end

end
end
function formatFromPattern( str, options )
	--if options.pattern and options.pattern ~='' then
			mw.log( str .. ':' .. options.pattern )
			return mw.ustring.gsub( options.pattern, '$1', str )  --الحصول على اول نتيجة للدالة
	--	else return str
	--end
end
function addTrackingCategory(prop,options)
	local cat =  require('Module:Wikidata/تتبع').makecategory1
	local category =  cat(options)
	if category and category ~= '' then
		return prop .. '  ' .. category
	else 
		return prop
	end
end

local p = {}
 
function p.formatEntityId( entityId, options )
	return formatEntityId( entityId, (options or {}) )
end

function formatEntityId2( entityId, options )
	local label = options.label or mw.wikibase.label( entityId )
	if label == '' then
		label = mw.wikibase.label( entityId ) or nil
	end
	
    local link = mw.wikibase.sitelink( entityId )

    if link and (not options.nolink or options.nolink == '') then
        if label and label ~= '' then
            return {value = '[[' .. link .. '|' .. formatcharacters(label, options) .. ']]'.. catewikidatainfo(options), label = label }
        else
            return {value = '[[' .. formatcharacters(link, options) .. ']]'.. catewikidatainfo(options), label = link }
        end
    else
    	if label then
    		return {value = formatcharacters(label, options), label = label}
    	else return ''

    	end
    	return '' --{value = entityId, cat = 'som har labels med Qid', label = entityId}
    end
end

function p.formatEntityId2( entityId, options )
	return formatEntityId2( entityId, (options or {}) )
end

function p.formatStatements( frame, key )
    local args = frame.args
    --If a value if already set, use it
    if args.value and args.value ~= '' then
        return args.value
    end
    local prop = formatStatements( frame.args, key )
	if prop and prop ~= '' then
    	if args.mainprefix and args.mainprefix ~= '' then -- mainprefix
    		prop = args.mainprefix .. prop
    	end
    	if args.mainsuffix and args.mainsuffix ~= '' then  -- mainsuffix
    		prop = prop .. args.mainsuffix
    	end
		if args.mainsuffixAfterIcon and args.mainsuffixAfterIcon ~= '' then   -- another suffix but after wikidata icon
		prop =  prop .. args.mainsuffixAfterIcon 
		end
	else 
    	if args.NoPropValue and args.NoPropValue ~= '' then -- value if no local value and no wikidata value  
    		prop = args.NoPropValue
    	end
	end
    return prop
end
 
function p.formatStatementsFromLua( options, key )
    --If a value if already set, use it
    if options.value and options.value ~= '' then
        return options.value
    end
    local s = formatStatements( options, key )
    if s == '' then
    	s = nil
    end
    return s
end
 
-- Return the site link (for the current site) for a given data item.
function p.getSiteLink( frame )
	local site = frame.args[2] or frame.args.site
	local id = frame.args[1]  or frame.args.id
	    local link = sitelink( id , site )
    if link and link ~= ''  then
            return link
	end
end

function p.descriptionIn(frame)
	local langcode = frame.args[1]
	local id = frame.args[2] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configuration

	return descriptionIn( langcode ,id  )
end
function p.labelIn(frame)
	local langcode = frame.args[1]
	local id = frame.args[2] -- "id" must be nil, as access to other Wikidata objects is disabled in Mediawiki configuration

	return labelIn( langcode ,id  )
end

return p