Jump to content

ماڈیول:Wikidata2

آزاد انسائیکلوپیڈیا، وکیپیڈیا توں

Documentation for this module may be created at ماڈیول:Wikidata2/doc

-- local fallback = {'en', 'nb', 'da', 'nn', 'de', 'fr', 'es', 'ur', 'pt'}
local formatera = require('module:Math')
local citetitle = 'Module:Cite'
	if nil ~= string.find (mw.getCurrentFrame():getTitle(), 'ملعب', 1, true) then			-- did the {{#invoke:}} use sandbox version?
		citetitle = 'Module:Cite/ملعب'		-- load sandbox versions of support modules
	end
	
local weblink = require('Module:Weblink')
local Infobox_Image = require('Module:InfoboxImage').Infobox_Image
local p = {}
local Frame;
local Frame_args = {}
local i18n = {
	["errors"] = {
		["property-param-not-provided"] = "وسيط property غير متوفر.",
		["entity-not-found"] = "الكيان غير موجود.",
		["unknown-claim-type"] = "نوع claim غير معروف.",
		["unknown-snak-type"] = "نوع snak غير معروف.",
		["unknown-datatype"] = "نوع data غير معروف.",
		["unknown-entity-type"] = "نوع entity غير معروف.",
		["unknown-value-module"] = "يجب عليك تعيين كل من  value-module و value-function.",
		["unknown-claim-module"] = "يجب عليك تعيين كل من claim-module و claim-function.",
		["unknown-property-module"] = "يجب عليك تعيين كل من property-module و property-function.",
		["property-module-not-found"] =  "الوحدة المستخدمة في وسيط property-module غير موجودة.",
		["property-function-not-found"] = "الوظيفة المستخدمة في وسيط property-function غير موجودة.",
		["value-module-not-found"] = "الوحدة المستخدمة في وسيط value-module غير موجودة.",
		["value-function-not-found"] = "الوظيفة المستخدمة في وسيط value-function غير موجودة.",
		["claim-module-not-found"] = "الوحدة المستخدمة في وسيط claim-module غير موجودة.",
		["claim-function-not-found"] = "الوظيفة المستخدمة في وسيط claim-function غير موجودة."
    },
	["nourdulabel"] = "گٹھ:ویکی ڈیٹا صفحات مع غیر موجود اردو نشانات",
	["warnDump"] = "[[Category:Called function 'Dump' from module Wikidata]]",
	["somevalue"] = "", --''غير محدد''
	["novalue"] ="",--قيمة مجهولة
	["cateref"] = "[[" .. "گٹھ:صفحات مع ویکی ڈیٹا حوالہ جات" .. "]]",
	['to translate'] = 'صفحات تستعمل معطيات من ويكي بيانات بحاجة لترجمة',
	["trackingcat"] = 'صفحات تستخدم خاصية $1',
	['see-wikidata-value'] = "الاطلاع ومراجعة البيانات على ويكي داتا", 
	['see-wikidata'] = "راجع العنصر من ويكي بيانات المقابل", 
	['see-another-project'] = "مقالة على $1",
	['see-another-language'] = "مقالة على ويكيبيديا $1",
}
local sortingproperties = {'P585','P571','P580','P569','P582','P570'}

function No_Tracking_cat(options)
	local notracking = options.notracking or Frame_args.notracking or ""
	local raw = options.raw or Frame_args.raw or ""
	local raw2 = options.raw2 or Frame_args.raw2 or ""
	--mw.log("raw2" .. raw2 )
	local nolink = options.nolink or Frame_args.nolink or ""
	if notracking ~= ""  or raw ~= '' or raw2 ~= '' or nolink ~= '' 
		then return true
	end
	return false
end

function addTrackingCategory(prop,options)
	if No_Tracking_cat(options) then return prop end
	local cat =  require('Module:Wikidata/تتبع').makecategory1
	local category = cat(options)
	if prop and prop ~= '' then
		if category and category ~= '' then
			return prop .. '  ' .. category
		else 
			return prop .. '  ' 
		end
	end
end

function catewikidatainfo(options)
--[[  function to add tracking category ]] 
 	--if (options.raw and options.raw ~= '') or (options.notracking and options.notracking== true) then return "" end
	if No_Tracking_cat(options) then return "" end
	local prop = options.property
	local cat = ' [[' .. 'گٹھ:ویکی ڈیٹا دے مواد دا ستعمال کرنے والے صفحے|'.. (prop or 'wikidata') .. ']]'
	if (not options.nolink or options.nolink == '')
		then return cat else return ''
	end
end

function countSiteLinks(id)
	numb = 0
	Table = {}
	local entity = mw.wikibase.getEntityObject(id)
	if entity and entity.sitelinks then
		for i, v in pairs(entity.sitelinks) do 
			Table[v.site] = v.title 
			numb = numb +1
		end
		--return Frame:extensionTag("source", mw.dumpObject( Table ),{ lang= 'lua'})
	end
	return numb
end
			
function make_format_num(String)
	local line = String
	line = mw.getCurrentFrame():preprocess("{{ {{{|safesubst:}}}formatnum: " .. String .. " }}")
	line = mw.ustring.gsub( line , '٫', '.' )
	line = mw.ustring.gsub( line , '٬', ',' )
	return line 
end

--auktoritetsdata
function formatcharacters(label, options)
	local formatcharacters = options.formatcharacters
	--if options.FormatfirstCharacter and options.num == 1 then 
		--formatcharacters = options.FormatfirstCharacter 
	--end
	if options.illwd2y and options.illwd2y ~= '' then
		String2 = mw.ustring.gsub( label , '–', '-' )
		ca = mw.ustring.match( String2 , "%d%d%d%d%-%d%d%d%d", 1 ) or mw.ustring.match( String2 , "%d%d%-%d%d%d%d", 1 )
		ca = ca or mw.ustring.match( String2 , "%d%d%d%d", 1 ) or mw.ustring.match( String2 , "%d%d%d%d%-%d%d", 1 )
		ca = ca or mw.ustring.match( String2 , "%d%d%d%d", 1 ) or String
		return ca
	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 .. " }}")
	elseif formatcharacters == 'formatnum' then
		return make_format_num( 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 get_entityId(options)
	local id = options.entityId or options["entityId"]
	id = id or options.id or options["id"]
	if not id or id == "" then
		if options.page and options.page ~= "" then
			id = mw.wikibase.getEntityIdForTitle( options.page )
		end
	end
	--mw.log("id :" .. id)
	return id or ""
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, firstvalue = 'true', sortbytime = 'chronological', noref = 'true'})
	end
end

function descriptionIn(langcode , id) -- returns item description for a given language
	local lan = langcode or 'ur'
	local entity = getEntityFromId(id)
	--[[
	local description, lange = mw.wikibase.getDescriptionWithLang( id )
	--mw.log( "descriptionIn:description : " .. description ",lange : " .. lange ".")
	if lange == lan
	then
		--return description
		return mw.getCurrentFrame():extensionTag("source", mw.dumpObject( description ),{ lang= 'lua'})
	else
		--mw.log( "descriptionIn:langcode : " .. langcode ",lange : " .. lange ".")
		--return nil
		return mw.getCurrentFrame():extensionTag("source", mw.dumpObject( description ),{ lang= 'lua'})
	--return str
	end
	]]
	if entity then 
		local description = entity.descriptions[lan]
		if description and description.value 
		then
			-- return mw.getCurrentFrame():extensionTag("source", mw.dumpObject( description ),{ lang= 'lua'})
			if description['language'] == lan then
				return description.value
			else return nil end
		end
	end
	
end

function labelIn(langcode,id) -- returns item label for a given language
	if not mw.wikibase then return nil end
	local lang = langcode
	if not langcode or langcode  == "" then lang  = "ur" end
	if type(id) ~= "string" then id = tostring(id) end
	local label = mw.wikibase.getLabelByLang( id , lang ) or nil
	return label
	--[[ 2nd old way
	local label, lange = mw.wikibase.getLabelWithLang( id )
	if lange == lang
	then
		return label
	else
		return nil
	--return str
	end ]]
	--[[ old way
	local entity = mw.wikibase.getEntityObject(id)
		if entity
		and entity.labels 
		and entity.labels[''..lang..'']
		and entity.labels[''..lang..''].value 
		then
			local lang = entity.labels[''..lang..'']
				if lang['language'] == lang then
				return entity.labels[''..lang..''].value
				else return nil end
		end
	]]
end

function get_snak_id(snak)
	if snak 
	and snak.type 
	and snak.type == "statement" 
	and snak.mainsnak 
	and snak.mainsnak.snaktype 
	and snak.mainsnak.snaktype == "value" 
	and snak.mainsnak.datavalue 
	and snak.mainsnak.datavalue.type
	and snak.mainsnak.datavalue.type == "wikibase-entityid" 
	and snak.mainsnak.datavalue.value 
	and snak.mainsnak.datavalue.value.id 
	then	
		--ID = 'Q' .. snak.datavalue.value['numeric-id']
		ID = snak.mainsnak.datavalue.value.id 
		return ID
	end
end

function comparedates(a, b)  -- returns true if a is earlier than B or if a has a date but not b
	if a and b then
		return a > b
	elseif a then
		return true
	end
end

function getonly(claims, options) 
	-- options.getonly 
	-- options.getonlyproperty 
	local claims2 = {}
	--mw.log("wikidata2 : getonly:" .. options.getonly )
	for i, j in pairs(claims) do
		local id = get_snak_id(j)
		--if j.mainsnak and j.mainsnak.snaktype == 'value' and j.mainsnak.datavalue and j.mainsnak.datavalue.value and j.mainsnak.datavalue.value.id then
			--local id = j.mainsnak.datavalue.value.id
		if id then
			local traff = false
			local t2 = formatStatements( {property = (options.getonlyproperty or "P31"), entityId = id, noref = 'true', raw = 'true' })
			if t2 and #t2 > 0 then
				for k, state in pairs( t2 ) do
					for j2, only in pairs(mw.text.split(options.getonly,',')) do
						if state.item == only then
							traff = true
						end
					end
				end
			end
			if traff then
				table.insert(claims2, j)
			end
		end
	end
	return claims2
end

function claimindex(claims, options)
	local claims2 = {}
	for j, index in pairs(mw.text.split(options.claimindex,',')) do
		if tonumber(index) and #claims >= tonumber(index) then
			table.insert(claims2, claims[tonumber(index)])
		end
	end
	return claims2
end

function avoidvalue(claims, options)
	-- options.avoidvalue 
	-- to avoid values
	local claims4 = {}
	local add2claims
	local avoidvalue
	if(type(options.avoidvalue) == 'string') then avoidvalue = mw.text.split(options.avoidvalue,',')
		elseif(type(options.avoidvalue) == 'table') then avoidvalue = options.avoidvalue
			else return claims
	end
	--mw.log("avoidvalue: " .. mw.dumpobject(options.avoidvalue))
	for i, j in pairs( claims ) do
		--mw.log('t:' .. t)
		ID = get_snak_id(j)
		add2claims = true
		if ID then
		    for k, t in pairs(avoidvalue) do
				--mw.log("ID: " .. ID)
				if ID == t then
					add2claims = false	
				end
			end
			if add2claims then
				table.insert( claims4, j)
			end
		end
	end
	return claims4
end

function prefervalue(claims, options)
	local claims3 = {}
	--mw.log("prefervalue: " .. mw.dumpobject(options.prefervalue))
	local prefervalue
	if(type(options.prefervalue) == 'string') then prefervalue = mw.text.split(options.prefervalue,',')
		elseif(type(options.prefervalue) == 'table') then prefervalue = options.prefervalue
			else return claims
	end	
	for k, t in pairs(prefervalue) do
		--mw.log('t:' .. t)
		for i, j in pairs( claims ) do
			local active = false
			ID = get_snak_id(j)
			if ID then
				--mw.log("ID: " .. ID)
				if ID == t and not active then
					table.insert( claims3, j)
					active = true
					--mw.log("ID == t" .. t)
				end
			end
		end
	end
	return claims3
end

function preferqualifier(claims, options)
	-- options.preferqualifier
	-- options.preferqualifiervalue
	mw.log("preferqualifier: " .. options.preferqualifier)
	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
					--mw.log( "t " .. t )
					--kaso = formatStatements({property=options.preferqualifier:upper(), raw = 'true',  formatting  = 'raw'}, statement.qualifiers)
					----kaso = formatStatements({property=options.preferqualifier:upper(), formatting  = 'raw'}, statement.qualifiers)
					----value = kaso
					for ii, quall in pairs( statement.qualifiers[options.preferqualifier:upper()] ) do
						--mw.log( "value " .. value )
						snaktype = quall.snaktype
						if snaktype == "value" then
							ty = quall.datavalue.value['id'] 
							if ty and ty == t  and not active then
								--if value == t and not active then
									table.insert( claims2, statement)
									active = true
								--end
							end
						end
					end
				end
			else
				table.insert( claims2, statement)
			end
		end
	end
	return claims2
end

function avoidqualifier(claims, options)
	-- options.avoidqualifier
	-- options.avoidqualifiervalue
	if not options.avoidqualifier or options.avoidqualifier == "" then return claims end
	local av = options.avoidqualifier:upper()
	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)
		elseif statement.qualifiers and statement.qualifiers[av] then
			if options.avoidqualifiervalue and options.avoidqualifiervalue ~= '' then
				list = {}
				if(type(options.avoidqualifiervalue) == 'string') then 
					list = mw.text.split(options.avoidqualifiervalue,',')
				elseif(type(options.avoidqualifiervalue) == 'table') then 
					list = options.avoidqualifiervalue
				end
				local active = true
				for k, t in pairs( list ) do
					for ii, quall in pairs( statement.qualifiers[av] ) do
						if quall.snaktype == "value" and quall.datavalue and quall.datavalue.value and quall.datavalue.value['id'] then
							if quall.datavalue.value['id'] == t then
								active = false
							end
						end
					end
				end
				if active then 
					table.insert( claims2, statement)
				end
			end
		end
	end
	return claims2
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 sortbyqualifiernumber(claims, options)
	local sortingproperty = options.sortingproperty
	if type(options.sortingproperty) == 'string' then
		sortingproperty = {options.sortingproperty}
	end
	table.sort(claims, function(a,b)
		local timeA = getqualifierbysortingproperty(a, sortingproperty)
		local timeB = getqualifierbysortingproperty(b, sortingproperty)
		if options.sortbynumber == '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 id and id ~= "" then
	--	if not(mw.wikibase.isValidEntityId(id)) or not(mw.wikibase.entityExists(id)) then
		--	return false
		--end
		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 Labelfunction( entityId, label ,labeloption , options) -- label with no urwiki sitelink
	if options.illwd2nowd  and options.illwd2nowd  ~= '' then noWD='' else noWD='y' end
	local jlabel = label --formatcharacters(label, options) -- The label
	local ur = labelIn('ur',entityId ) -- The urdu label
	local urlabel = ur --formatcharacters(ur, options) 
	if labeloption and labeloption ~= '' then
			jlabel = labeloption 
	elseif options.illwd2  and options.illwd2  ~= '' then
		if urlabel and urlabel ~= '' then
			jlabel = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {urlabel, fromlua="t", id=entityId, y = (options.illwd2y or '') } }
			else 
			jlabel  = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {id=entityId, fromlua="t", target='en', y = (options.illwd2y or '') } }
		end
		
	elseif options.enlabelcate and options.enlabelcate  ~= '' then
			if not urlabel or urlabel == '' then
				jlabel = label --formatcharacters(label, options)
				 if jlabel and jlabel ~= '' then
				 jlabel = jlabel ..' [['.. i18n.nourdulabel ..'|'.. entityId ..']]'
			end end
			
	else--if options.justurdu and options.justurdu  ~= '' then
			if urlabel and urlabel ~= ''
				then jlabel = urlabel
				else jlabel = nil
			end
	end
	if jlabel and jlabel ~= ''
	then
	return jlabel.. catewikidatainfo(options)
	end
end

function formatOneStatement( statement ,ref ,  options)
	local vava = nil
	local stat = formatStatement( statement, options )
	if stat then
		if not stat.qualifiers then 
			stat.qualifiers = {}
		end
		local s = stat.value
		local P585 = stat.qualifiers.P585 or ""
		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 reff  =stat.reff
		local QPrefix 
		local QSuffix
		if s == '' then s = nil end
		if s then
			if reff and options.reff and options.reff ~= ''  then
				s= s .. reff
			end
				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 = {
					stat.qualifiers.P580 or "",
					stat.qualifiers.P582 or "",
					s,
					stat.amatch,
					stat.goal
					} }
				end
				
				if options.office and options.office ~= '' then
					s = mw.getCurrentFrame():expandTemplate{ title = "معلومات صاحب منصب/منصب ويكي بيانات/نواة", args = 
					{office = s, 
					termstart = stat.qualifiers.P580 or "", 
					termend = stat.qualifiers.P582 or "", 
					constituency = stat.qualifiers.P768 or "", 
					predecessor = stat.qualifiers.P1365 or "", 
					successor = stat.qualifiers.P1366 or "", 
					series= stat.qualifiers.P1545 or "",
					of=stat.qualifiers.P642 or "",
					electedin=stat.qualifiers.P2715 or "",
					jurisdiction=stat.qualifiers.P1001 or "",
					employer=stat.qualifiers.P108 or "",
					entityId=options.entityId
					} } 
				end
			
			function qoo(Prefix,qualpref,p,Suffix)
				if p and p ~='' then 
				return mw.text.tag('small', {}, (Prefix or ' (').. (qualpref or '') .. p .. (Suffix or ')'))  end
			end
			QPrefix = options.qualifierprefix
			QSuffix = options.qualifiersuffix
			if qp1 and qp1 ~='' and options.qual1 and options.qual1 and qp1a and qp1a ~='' and options.qual1a and options.qual1a ~= ''
			then
				s = s .. qoo(QPrefix, options.qual1pref, qp1, QSuffix) .. qoo(QPrefix, options.qp1apref, qp1a, QSuffix)
			elseif qp1 and qp1 ~='' and options.qual1 and options.qual1 ~= '' then
				s = s .. qoo(QPrefix, options.qual1pref, qp1, QSuffix)
			elseif qp1a and qp1a ~='' and options.qual1a and options.qual1a ~= '' then
				s = s .. qoo(QPrefix, options.qp1apref, qp1a, QSuffix)
			end
			
			if qp2 and qp2 ~='' and options.qual2 and options.qual2 ~= '' then 
				s = s .. qoo(QPrefix, options.qual2pref, qp2, QSuffix) 
			end
			if qp3 and qp3 ~='' and options.qual3 and options.qual3 ~= '' then 
				s = s .. qoo(QPrefix, options.qual3pref, qp3, QSuffix) 
			end
			if qp4 and qp4 ~='' and options.qual4 and options.qual4 ~= '' then 
				s = s .. qoo(QPrefix, options.qual4pref, qp4, QSuffix) 
			end
			if qp5 and qp5 ~='' and options.qual5 and options.qual5 ~= '' then 
				s = s .. qoo(QPrefix, options.qual5pref, qp5, QSuffix) 
			end
			if options.justthisqual and options.justthisqual ~= '' then 
				if onlyqualifier then 
					s = onlyqualifier 
				else 
					s = nil   -- We need only the qualifier 	
				end 
			end
			if ro and ro ~='' and options.withro and options.withro ~= '' then s = s .. qoo(QPrefix, '' , ro, QSuffix) end
			
			if options.withdate and options.withdate ~= '' then
				if P585 and P585 ~=''  then
					if options.withdate == 'y' then 
						s = s .. qoo(QPrefix, 'سنة ' , P585, QSuffix)
					elseif options.withdate == 'before' then 
						s = '*' .. P585 ..':' .. s..'\n'
					else 
						s = s .. qoo(QPrefix, '' , P585, QSuffix)
					end
				end
			end
			
			if awardqual and options.awardqua and options.awardqua ~= '' then 
				s = s .. qoo(QPrefix, '' , awardqual, QSuffix) 
			end
			local bothdates = options.withintervall or options.bothdates
			if tf and bothdates and bothdates  ~= '' then
				if bothdates == 'line' then
					 s = s .. mw.text.tag('br') .. qoo(QPrefix, '' , tf, QSuffix)
				elseif bothdates == 'before' then
					 s = qoo(QPrefix, '' , tf, QSuffix) .. s
				else 
					s = s .. qoo(QPrefix, '' , tf, QSuffix)
				end
			end
			--if utgivort and options.withutgivort and options.withutgivort ~= '' then
				--if options.withutgivort == 'قوسين' then s = s .. ' ' .. qoo(QPrefix, '' , utgivort, QSuffix)
					--else s = s .. ' ' .. utgivort
				--end
			--end
			if pr and pr ~= '' and options.getsimpleproperty and options.getsimpleproperty ~= '' then
				if options.getsimpleproperty == 'f?dd' then s = s .. ' ' .. qoo(QPrefix, 'f. ' , pr, QSuffix)
					elseif options.getsimpleproperty == 'parentes' then s = s .. ' ' .. qoo(QPrefix, '' , pr, QSuffix)
					elseif options.getsimpleproperty == 'avn?gon'  then s = s .. ' ' .. mw.text.tag('span', {}, ' av ' .. pr .. '')
				end
			end
			
			if type(ref) == 'table' or (options.noref and options.noref ~='') or (options.justthisqual and options.justthisqual ~='') 
			then
				--table.insert( formattedStatements, s )
				vava =  s 
			else
				local t = formatReferences( statement, options )
				stat.ref = t
					if options.justref and options.justref ~= '' 
					then
						vava =  t
					elseif options.onlyvaluewithref and options.onlyvaluewithref ~= '' then
						if t and t ~= "" then
							vava =  s .. t 
						end
					else 
						vava =  s .. t 
					end
			end
		end
	--table.insert(statementsraw, stat)
	end
	return { v = vava , raw = stat}
end

function filter_claims( claims , options)
	local claims = claims
		--======================================================
		if options.avoidqualifier and options.avoidqualifier ~= '' then 		-- to avoid value with a given qualifier
			claims = avoidqualifier(claims, options)
		end
		--======================================================
		if options.preferqualifier and options.preferqualifier ~= '' then
			claims = preferqualifier(claims, options)
		end
		--======================================================
		-- options.avoidvalue
		if options.avoidvalue and options.avoidvalue ~= '' then
			claims = avoidvalue(claims, options)
		end
		--======================================================
		-- options.prefervalue
		if options.prefervalue and options.prefervalue ~= '' then
			claims = prefervalue(claims, options)
		end
		--======================================================
		-- options.getonly
		if options.getonly and options.getonly ~= '' then
			claims = getonly(claims, options)
		end
		--======================================================
		if not options.langpref or options.langpref == '' then
			local claims7 = {}
			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'] == 1617 then -- Q1617 = 'اردو'
							table.insert( claims7, 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'] == 209468 then -- Q209468 = 'اردو حروف تہجی'
							table.insert( claims7, statement )
						end
					end
				end
			end
			if #claims7 > 0 then
				claims = claims7
			end
		end
		--======================================================
		if options.sortbytime == 'chronological' or options.sortbytime == 'inverted' then
			claims = sortbyqualifier(claims, options)
		elseif options.sortbynumber == 'chronological' or options.sortbynumber == 'inverted' then
			claims = sortbyqualifiernumber(claims, options)
		elseif options.sortbyarbitrary == 'chronological' or options.sortbyarbitrary == 'inverted' then
			claims = sortbyarb(claims, options)
		end
		--======================================================
	local firstvalue =  options.enbarten or  options.firstvalue
	if firstvalue and firstvalue ~='' and #claims > 1 then
		if firstvalue == '2' then
			claims = {claims[2]}
			elseif firstvalue == '3' and #claims > 2 then
			claims = {claims[3]}
			elseif firstvalue == '4' and #claims > 3 then
			claims = {claims[4]}
			elseif firstvalue == '5' and #claims > 4 then
			claims = {claims[5]}
			elseif firstvalue == '6' and #claims > 5 then
			claims = {claims[6]}
			elseif firstvalue == '7' and #claims > 6 then
			claims = {claims[7]}
			elseif firstvalue == '8' and #claims > 7 then
			claims = {claims[8]}
			elseif firstvalue == '9' and #claims > 8 then
			claims = {claims[9]}
			else
			claims = {claims[1]}
		end
	end
	local numval =  options.numval
	if numval and type(numval) ~= "number" then 
		numval = tonumber(numval)
	end
	if numval and type(numval) == "number" and #claims > 1 and #claims > numval then
		local claimsnumval= {}
		local ic = 1
		while (numval >= ic) and (#claims >= ic) do
			table.insert( claimsnumval, claims[ic] ) 
			ic =ic +1
		end
		claims = claimsnumval;
	end	
	return claims
end

function formatStatements( options, ref )
   	local valuetable = {} -- formattedStatements
   	local claims = {}
   	if not options.property then return formatError( 'property-param-not-provided' ) end
   	functions = {
   		["P172"] = {["value-module"] ="Wikidata2/P172" ,["value-function"] ="get_P172_lab"} , 
   		["P106"] = {["value-module"] ="Wikidata2/P106" ,["value-function"] ="formatEntityWithGenderClaim"} , 
   	}
   	functions["P413"] = functions["P106"]
   	--[[if ( not options["value-module"] or options["value-module"] == "" ) 
   			or ( not options["value-function"] or options["value-function"] == "" )
   		or  ( not options["property-module"] or options["property-module"] == "" ) 
   			or ( not options["property-function"] or options["property-function"] == "" )
   		or  ( not options["claim-module"] or options["claim-module"] == "" ) 
   			or ( not options["claim-function"] or options["claim-function"] == "" )
   	then 
	   	if functions[options.property:upper()] then 
	   		options["value-module"] = functions[options.property:upper()]["value-module"]
	   		options["value-function"] = functions[options.property:upper()]["value-function"]
	   	end
   	end]]
   	local option1 = options["option1"] or options.option1
   	if option1 and options["option1value"] then 
   		options[ option1 ] = options["option1value"] 
   		options['"' .. option1 .. '"'] = options["option1value"]
   		--mw.log( "option1: " .. option1 .. "value: " .. options["option1value"]  )
   		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 )
        	id = get_entityId( options )
        	entity = getEntityFromId( id )
    	end
    	local property = options.property:upper()
    	--property = options.property:upper() 
 
    	if not entity then return '' end --TODO error? 
    	if not entity.claims or not entity.claims[property] then
    		if options.otherproperty and options.otherproperty ~= "" then 
	    		options.property = options.otherproperty
	    		property = options.otherproperty
	    	end
    	end
    	if not entity.claims or not entity.claims[property] then
        	return '' --TODO error?
    	end
 
    	--Format statement and concat them cleanly
		if options.rank == 'best' or not options.rank then 
			--claims = entity:getAllStatements( property )
			claims = entity:getBestStatements( property )
			elseif options.rank == 'valid' then
				for i, statement in pairs( entity.claims[ property ] ) 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[property] ) do
					table.insert( claims, statement )
				end
		else
			for i, statement in pairs( entity.claims[property] ) do
				if statement.rank == options.rank then
					table.insert( claims, statement )
				end
			end
		end
	end
	claims = filter_claims( claims , options)
	local statementsraw = {}
	local All_claims = claims
	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( valuetable, va.v )
				end
				table.insert( statementsraw, va.raw )
			end
		end
	end
	local priff = ""
	local Separator = options.separator-- or ""
	local Conjunction = options.conjunction-- or ""
	
	--if Conjunction and Conjunction == "br" then Conjunction =  "\n" end
	if (Separator and Separator == "br") or (Conjunction and Conjunction == "br")  then 
		Separator = mw.text.tag('br')
		Conjunction = mw.text.tag('br')
	end
	if Separator and Separator == "*"  then 
		priff = "\n*" 
		Separator = "\n*" 
		Conjunction = "\n*" 
	end
	if Separator and Separator == "#"  then 
		priff = "\n#" 
		Separator = "\n#" 
		Conjunction = "\n#" 
	end
	local tot = mw.text.listToText( valuetable, Separator, Conjunction )
	if #valuetable > 1 then
		tot = priff .. tot
	end
	
	if tot == '' then tot = nil end
	if options.raw and options.raw ~= '' then
		if options.rawtolua and options.rawtolua ~= '' then
			return  mw.getCurrentFrame():extensionTag("source", mw.dumpObject(statementsraw),{ lang= 'lua'})
		end
		return statementsraw
	end
	if options.returnnumberofvalues and (options.returnnumberofvalues ~= "" or options.returnnumberofvalues == true ) then
		return tot, #valuetable
	end
	if options.numberofclaims and options.numberofclaims ~= '' then
		return #All_claims
	end
	return tot
end

function p.formatAndCat(args)
	if args then Frame_args = args end
	if not args then return nil end
	args.linkback = args.linkback or true
	args.addcat = true
	if args.value then
		if args.value == '-' then return nil end
		local val = args.value .. p.addTrackingCat(args.property)
		val = p.addLinkBack(val, args.entity, args.property)
		return val
	end 
	return p.formatStatementsFromLua( args )
end

function formatReferences( statement, options )
	local ic
	local s
	local statementreferences = statement.references
	local reference = {}
	local numberofref = tonumber(options.numberofreferences) or 7
	if statementreferences then
		local cite = require(  citetitle  )
		ic = 1
		for i, ref in pairs( statementreferences ) do
			if ref.snaks then
				if numberofref >= ic then
					s =  cite.citeitem2(ref , options )
					if s and s ~= "" then 
						ic = ic + 1
						table.insert(reference, s)
					end
				end
			end
		end
	end
	local final = table.concat(reference)
		if final and final ~= '' then
			final = final .. i18n.cateref
		end
	return final
end

function formatqualifiers( statement,s, options )
	s.qualifiers = {}
	function qua(p,firstvalue,modifytime)
		if p and p ~='' then
			vvv = formatStatements({property =p,enlabelcate = 't', firstvalue = (firstvalue or '')
				,modifytime = (modifytime or 'longdate'), noref = 'true'}, statement.qualifiers) or ''
			s.qualifiers[p] = vvv
			return vvv
		end
	end
	
	if options.template and options.template ~= '' then
		s.ID = getEntityIdFromValue(statement.mainsnak.datavalue.value)
		s.QQ1 = qua(options.Q1)
		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 options.football and options.football ~= '' then
		if statement.qualifiers.P1350 or statement.qualifiers.P1351 then
			s.amatch = qua("P1350",'true')
			s.goal = qua("P1351",'true')
		end
	end
	if (options.football and options.football ~= '' ) or (options.office and options.office ~= '') then
		s.start1 = qua("P580",'true')
		
		s.finish1 = qua("P582",'true')
	end
	if options.office and options.office ~= '' then
		if statement.qualifiers.P580 or statement.qualifiers.P582 or statement.qualifiers.P1365 or statement.qualifiers.P1366 then
			s.before1 = qua("P1365",'true')
			s.after1 = qua("P1366",'true')
			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
	end
	
	if options.withdate and options.withdate ~= '' then
	--if statement.qualifiers.P585 then
		s.P585 = qua("P585",'true',options.modifyqualifiertime)
	end
    local qwe = options.qwer
	if statement.qualifiers.qwe  then
		s.ro = qua(qwe,'true')
	end
	--if statement.qualifiers.P574 then
		--s.dateoftaxpub = qua("P574",'true',options.modifyqualifiertime)
	--end
	--[[
	if statement.qualifiers.P405 then
		local author = {}
		for i, j in pairs(statement.qualifiers.P405) do
			if j.snaktype == 'value' then
				local item = 'Q' .. j.datavalue.value['numeric-id']
				local authorname = formatStatements({property = "P428", entityId = item, noref = 'true', firstvalue = 'true'})
				if author and authorname ~= '' then
					table.insert(author, formatEntityId(item, {label = authorname }).value)
				else
					table.insert(author, formatEntityId(item, {}).value)
				end
			end
		end
		s.auktor = mw.text.listToText(author, ', ', ' & ')
	end	
	--]]
	local bothdates_option = options.withintervall or options.bothdates
	if  bothdates_option and bothdates_option  ~= '' then
		if statement.qualifiers.P580 or statement.qualifiers.P582 then
			local f = qua("P580",'true',options.modifyqualifiertime)
			local t =  qua("P582",'true',options.modifyqualifiertime)
				s.tifr = f .. '–' .. t
				
		end
	end
	if options.awardqua and options.awardqua ~= '' then 
		if statement.qualifiers.P585 or statement.qualifiers.P1346 then
			local fo = qua("P585",'true',options.modifyqualifiertime)
			local to = qua('P1346','true')
			s.foto = fo .. ' ' .. mw.text.tag('span', {}, ' ' .. to  .. '')
		end
	end
	function quaaal(opti,options)
		if opti and opti ~=''  and statement.qualifiers[opti] then
			kkk = formatStatements({property = opti, noref = 'true', separator = options.qualifierseparator
				, conjunction = options.qualifierconjunction,size =options.size,image =options.image
				, modifytime = options.modifyqualifiertime,enlabelcate = 't',langpref = options.langpref,showlang = options.showlang}
				, statement.qualifiers) or ''
			
			s.qualifiers[ opti ] = kkk
			return kkk
		end
	end
	--if statement.qualifiers.P291 then       -- خاصية بلد النشر
		--s.utgivort = quaaal('P291',options)
	--end
	--if statement.qualifiers.P2096 then
		--s.bildtext = formatStatements({property = "P2096", noref = 'true', langpref = (options.langpref or 'ur')}, statement.qualifiers)
	--end
	if options.justthisqual and options.justthisqual ~= '' and statement.qualifiers[options.justthisqual] then
		s.onlyqualifier = quaaal(options.justthisqual,options)
	end
	if options.qual1 and options.qual1 ~= '' and statement.qualifiers[options.qual1] then
		s.qp1 = quaaal(options.qual1,options) 
	end
	if options.qual1a and options.qual1a ~= '' and statement.qualifiers[options.qual1a] then
		s.qp1a = quaaal(options.qual1a,options) 
	end
	if options.qual2 and options.qual2 ~= '' and statement.qualifiers[options.qual2] then 
		s.qp2 = quaaal(options.qual2,options) 
	end
	if options.qual3 and options.qual3 ~= '' and statement.qualifiers[options.qual3] then
		s.qp3 = quaaal(options.qual3,options) 
	end
	if options.qual4 and options.qual4 ~= '' and statement.qualifiers[options.qual4] then
		s.qp4 =  quaaal(options.qual4,options) 
	end
	if options.qual5 and options.qual5 ~= '' and statement.qualifiers[options.qual5] then
		s.qp5 = quaaal(options.qual5,options) 
	end	
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
			s.qualifiers = {}
			if statement.qualifiers then
				qualu = formatqualifiers( statement,s, options )
				--if qualu and qualu ~= '' then table.insert(qualu) end
			end
			if statement.references then
				if options.reff and options.reff ~= ''  then
					s.reff  = formatReferences( statement, options )
				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, snak.datatype, options )
    	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.item and options.getsimpleproperty then
        	if options.getsimpleproperty ~= '' and options.getproperty and options.getproperty ~= '' then
        		local pr = formatStatements({property = options.getproperty, entityId = s.item, firstvalue = options.getenbarten
        			, noref = 'true', modifytime = options.getmodifytime, raw = options.getraw})
        	if pr then s.pr = pr end
        end
        end
        return s
    else
        return {value = formatError( 'unknown-snak-type' )}
    end
end

local skiip = {
	["P106"] = {
		"Q42857"  ,  -- prophet
		"Q14886050"  , -- terrorist
		"Q2159907"  , -- criminal
	}}

function formatwikibaseitem( datavalue, datatype, options )
 --[[  datatype  wikibase-item   ]]

	local item = getEntityIdFromValue( datavalue.value )
	local itemValue = formatEntityId( item , options ).value
	local Format = options.formatting or options["formatting"]
	local Skipped = skiip[options.property] or {}
	for k, v in pairs(Skipped) do
		if datavalue.value.id == v then 
			return {value = ""}    	
		end
	end
	if Format and Format  ~= '' 
	then
		if Format == 'raw' then 
			--mw.log("raw: " .. item )
			return {value = item }
		elseif Format == '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'
				}
			end
		elseif Format == 'fu' then 
			fu_temp = "Cycling race/stageclassification1"
			return {value = mw.getCurrentFrame():expandTemplate{ title = fu_temp , args = {item}} }
		elseif Format == 'sitelink' then -- for Wikidata property giving Wikimedia list
			return {value = formatsitelink(datavalue.value.id , options ) }
		else
			return {value = formatFromPattern( formatcharacters(datavalue.value, options), options )}
		end
	elseif options.property1 and options.property1 ~= '' and options.property1:upper():sub(1,1) =="P" 
		then
		for i, statement in pairs( datavalue ) do
			caca = formatStatements( {property = options.property1 or options["property1"]
				, entityId = item
				, noref =options.noref or options["noref"]
				,rank=options.property1rank or options["property1rank"]
				,pattern = options.property1pattern or options["property1pattern"]
				,formatting=options.property1formatting or options["property1formatting"]
				,size =options.size or options["size"]
				,image =options.image or options["image"]
				,noref='true'
				,firstvalue ='true' })
			if itemValue and itemValue  ~= '' then
				if caca and caca  ~= '' then 
					cooooca = (options.property1pref or '') ..''.. caca ..''.. (options.property1suff or '')
					if options.property1after and options.property1after ~= "" then
						return {value = itemValue .. cooooca } 
					else
						return {value = cooooca .. ' '.. itemValue } 
					end
				else
					return {value = itemValue  }
				end
			end
		end 
	elseif options.propertyimage and options.propertyimage ~= '' then
		local p_f = options.propertyimageformatting or options.formattingpropertyimage
		for i, statement in pairs( datavalue ) do
			local vas = formatStatements( {
				property =options.propertyimage 
				,formatting = p_f
				,entityId = item
				,noref =options.noref 
				,rank=options.rank
				,pattern =options.pattern
				,size =options.size
				,image =options.image
				,noref='true'
				,avoidvalue = options.avoidvaluepropertyimage
				,firstvalue ='true'
				,nolink=options.nolink 
			})
			if vas and vas  ~= '' then 
				return {value =  vas } 
			else
			end
		end 
	elseif options.property2 and options.property2 ~= '' then
		for i, statement in pairs( datavalue ) do
			local caca = formatStatements( 
				{property =options.property2
				, entityId = item
				, noref =options.noref 
				,rank=options.rank
				,pattern =options.property2pattern
				,size =options.size
				,image =options.image
				,propertyimage =options.property3
				,firstvalue ='true'
				})
			if itemValue and itemValue  ~= '' then
				if caca and caca  ~= '' then
						return {value =  caca .. ' '.. itemValue  } 
					else 
						return {value = itemValue  } 
				end
			end	
		end 
   else
		return {value = formatEntityId( item, options ).value, item = item }    	
	end
end

function formatwikibaseproperty( datavalue, datatype, options )
 --[[  datatype  wikibase-property   ]]
 
	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 formattabulardata( datavalue, datatype, options )
 --[[  tabular-data ]]
	data=  '[[commons:' .. datavalue.value .. '|' .. datavalue.value .. ']]'
	return {value = data}
end

function formatgeoshape( datavalue, datatype, options )
 --[[  geo-shape  ]]
	shape =  '[[commons:' .. datavalue.value .. '|' .. datavalue.value .. ']]'
	return {value = shape}
end
function formatcommonsMedia( datavalue, datatype, options )

 --[[ commonsMedia ]]
  if options.image and options.image ~= '' then -- return real image
		--tid = '[[file:' .. datavalue.value  .. '|'.. (options.size or '60')..'px|'..'border'..']]' 
		params = {
			image = datavalue.value
			, maxsize = "280x330px"
			, center = options.center
		}
		if options.size and options.size ~= "" then params.size = options.size  end
		tid = Infobox_Image( params )
	else
		tid =  formatcharacters(datavalue.value, options)
	end
	return {value = tid}
end

function formatmath( datavalue, datatype, options )
 --[[datatype math ]]
		 --return	{value = mw.text.tag('math', {}, ''.. datavalue.value..'') } -- that doesn't work well
		 return	{value =mw.getCurrentFrame():callParserFunction( '#tag:math', ''.. datavalue.value..'' ) }
end

function formatstring( datavalue, datatype, options )
 --[[  datatype  string  -  external-id  ]]
	--old value: auktoritetsdata , auktoritetsdata2 , auktoritetsdata3
	local par = options.pattern
	if options.stringpattern and options.stringpattern ~= "" then
		--mw.log(options.stringpattern)
		tid = mw.ustring.gsub( options.stringpattern, '$1', datavalue.value ) 
	elseif par and par ~= '' then
		if par == "autourl" or par == "autourl2" or par == "autourl3" or par == "autourl4"
		then 
			tid =  formatcharacters(datavalue.value, options)
		else 
			tid = formatFromPattern( formatcharacters(datavalue.value, options), options )
		end
	else
		 tid =  formatcharacters(datavalue.value, options)
	end
	return {value = tid}	
end

function formatexternalid( datavalue, datatype, options )
	if options.pattern and options.pattern ~= '' 
	then
		par = options.pattern
			local patter = formatStatements( {property = "P1630", entityId = options.property, firstvalue = 'true', noref = 'true',rank='all' }) -- get formatter URL
			--mw.log( options.property .. ':' .. patter )
			local pp = formatFromPattern( datavalue.value, {pattern = patter} )
			local plabel = pp
        if mw.wikibase
			then  plabel =  mw.wikibase.label( options.property ) or pp 
        end
        ppp = mw.ustring.gsub( pp, ' ', '_' )
		if patter and patter ~= '' then   -- if P1630 are there
				
				if par == "autourl" then -- like http://example.com/$1.html
					 tid =  ppp
				elseif par ==  "autourl2" then  -- like [http://example.com/$1.html $1]
					 tid =  '[' .. ppp .. ' ' .. datavalue.value .. ']' 
				elseif par ==  "autourl3"  then  -- like [http://example.com/$1.html http://example.com/$1.html]
					 tid =  '[' .. ppp .. ' ' .. ppp .. ']' 
				elseif par == "autourl4"  then
					 tid =  '[' .. ppp .. ' ' .. plabel .. ']' 
				else
					tid =  formatFromPattern( formatcharacters(datavalue.value, options), options )
				end
			else   --  P1630 are not there
				if par ==  "autourl" or par ==  "autourl2" or par == "autourl3" or par == "autourl4"
				then
					tid =  formatcharacters(datavalue.value, options)  --just return value
				else
					tid =  formatFromPattern( formatcharacters(datavalue.value, options), options )
				end
			end
	else
		 tid =  formatcharacters(datavalue.value, options) --just return value
	end
	return {value = tid}	
end

function formattime( datavalue, datatype, options )
 --[[  datatype  time  ]]
        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

function formatcoordinate( datavalue, datatype, options )
--[[  datatype  globe-coordinate  ]] 
	--local GlobeCoordinate = require 'Module:GlobeCoordinate'
	--return {value = GlobeCoordinate.newFromWikidataValue( datavalue.value ):toHtml()}
	local coord = datavalue.value 
	local globe = datavalue.value.globe
	--local globe = globe:match('Q%d+')
	local globe2 =  require('Module:Wikidata2/Globes')[globe] or ""
	if options.formatting  and options.formatting  ~= '' then
		if options.formatting == 'latitude' then 
			pro =coord.latitude 
		elseif options.formatting == 'longitude' then 
			pro =coord.longitude 
		elseif options.formatting == 'dimension' then 
			pro =coord.dimension  
		elseif options.formatting == 'precision' then 
			pro =coord.precision 
		elseif options.formatting == 'globe' then 
			pro = globe:match('Q%d+') 
		elseif options.formatting == 'globe2' then 
			pro = globe2 
		--elseif options.formatting == 'coord' then
			--return {value = }
		else
		end
	else
		pro =
			mw.getCurrentFrame():preprocess('{{ {{{|safesubst:}}}#invoke:Coordinates|coord'
			.. '|'.. coord.latitude
			.. '|'.. coord.longitude
			.. '|display=inline'
			.. '|globe:'.. globe2 ..'_type:landmark'
			.. '|format='..(options.formatcoord or '')..'}}'
			)..catewikidatainfo(options) 
	end
	return {value = pro }
end

function formatquantity( datavalue, datatype, options )
--[[  datatype quantity  ]] 
		local amount, unit, cat = datavalue.value.amount, datavalue.value.unit, nil
		amount = mw.ustring.gsub( amount , '+', '' )
		if unit then
			unit = unit:match('Q%d+')
		end
		local formatera = require('module:Math')
		local number = formatera.newFromWikidataValue(datavalue.value)
		local unitraw = unit
		if unit then
			-- يتحقق اذا كان هناك اي اختصار لوحدة القياس
			--if lab and ( not options.nounitshort or options.nounitshort == '' )  then
			if options.unitshort and options.unitshort ~= '' then
				local lab = options.label 
				or formatStatements({property = 'P498', entityId = unit, firstvalue = 'true', noref = 'true'}) 
				or formatStatements({property = 'P5061', entityId = unit, firstvalue = 'true', langpref = options.langpref, noref = 'true'})
				or ""
				local s = formatEntityId( unit, {label = lab ,enlabelcate ='t' , 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 ,enlabelcate ='t'})
				unit = s.value
				cat = s.cat
			end
			
		end
	if options.formatcharacters and options.formatcharacters =="formatnum" then
		amount = make_format_num( amount )
	end
		local Value = amount .. ' ' .. (unit or '')
		if options.nounit and options.nounit ~= "" then
			Value = amount
		end
		return {value = Value, amount = amount, unit = unit, unitraw = unitraw, cat = cat}
end

function formaturl( datavalue, datatype, options )
--[[  datatype  url  ]] 
	local label = options.label
	if options.urllabel and options.urllabel  ~= '' then
		label = options.urllabel     
	end
	va =  mw.ustring.gsub( datavalue.value, ' ', '_' )
	if not label and  options.property =='P856' then label = 'باضابطہ ویب سائٹ' end
	if options.displayformat and options.displayformat == "weblink" then
		return {value = weblink.makelink(va ) }
	end
	if options.formatting and options.formatting == "raw" then
		return {value = va }
	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

function formatmonolingualtext( datavalue, datatype, options ) -- showlang
	local text = datavalue.value.text
	if options.textformat and options.textformat == "text" then
		return {value = text}
	end
	local Moduletext = require 'Module:wikidata2/monolingualtext'
	local tid = Moduletext._main( datavalue, datatype, options )
	return {value = tid}	
end

function formatDatavalue( datavalue, datatype, 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 {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, datatype, options ) 
 	elseif datatype == 'wikibase-property' then return   formatwikibaseproperty( datavalue, datatype, options)
 	elseif datatype == 'commonsMedia' then return   formatcommonsMedia( datavalue, datatype, options)
 	elseif datatype == 'math' then return       formatmath( datavalue, datatype, options )
 	elseif datatype == 'time' then return formattime( datavalue, datatype, options )
 	elseif datatype == 'external-id' then return  formatexternalid( datavalue, datatype, options )
 	elseif datatype == 'string' then return  formatstring( datavalue, datatype, options )
 	elseif datatype == 'globe-coordinate' then return  formatcoordinate( datavalue, datatype, options )
 	elseif datatype == 'quantity' then return   formatquantity( datavalue, datatype, options )
 	elseif datatype == 'url' then return   formaturl( datavalue, datatype, options )
 	elseif datatype == 'monolingualtext' then return  formatmonolingualtext( datavalue, datatype, options )
 	elseif datatype == 'geo-shape' then return formatgeoshape( datavalue, datatype, options )
 	elseif datatype == 'tabular-data' then return formattabulardata( datavalue, datatype, options )
    else
        return {value = formatError( 'unknown-datatype' )}
    end
end

function formatEntityId( 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 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 = '[[:' .. link .. '|' .. formatcharacters(link, options) .. ']]'.. catewikidatainfo(options), label = link }
        end
    else
    	if label and label ~= '' 
    		then
    		local label3 = Labelfunction( entityId, label,options.label, options)
    		return {value = label3 , label = label}
    	else return ''

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

function sitelink_g( id , wikisite )
 --[[ 
       function to get any link from any sister project
 ]]
	if not mw.wikibase then return '' end
	local site = wikisite or 'urwiki'
	local link = mw.wikibase.sitelink( id , site ) or ""
	--mw.log("mw.wikibase.sitelink,site: " .. site.. ",link:" .. link )
	return link
end

function sitelink( id , wikisite )
	if not mw.wikibase then return '' end
	local site = wikisite or 'urwiki'
	--local link = mw.wikibase.getSitelink( id , site ) or ""
	--return link
	
	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
			return entity.sitelinks[''..site..''].title
			else return ''
			end
	end
end

function formatsitelink( entityId, options )
 --[[ function to get only the value with link ]] 
    local link = sitelink( entityId )
    if link and link ~= ''  then
		if not options.nolink or options.nolink == '' then
            --return '[[' .. formatcharacters(link, options) .. ']]'.. catewikidatainfo(options)
            return '[[' .. link .. ']]'.. catewikidatainfo(options)
    else
    		return link -- formatcharacters(link, options)
		end
    else 
		return ''
    	end

end

function formatFromPattern( str, options )
 --[[  function to replace $1 with string  ]] 
	--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 p.getEntity( id ) 
	if type(id) == 'table' then return id end
	return getEntityFromId(id)
end

function p.translate(str, rep1, rep2)
	str = i18n[str] or str
	if rep1 and (type (rep1) == 'string') then
		str = str:gsub('$1', rep1)
	end
	if rep2 and (type (rep2) == 'string')then
		str = str:gsub('$2', rep2)
	end
	return str
end

function p.getId(snak)
	if (snak.snaktype == 'value') then
		if snak.datavalue.type == "wikibase-entityid" then 
			return 'Q' .. snak.datavalue.value['numeric-id']
		end
	end
end

function p.addLinkBack(str, id, property)
	if not id then id = p.getEntity() end
	if not id then return str end
	if type(property) == 'table' then property = property[1] end
	if type(id) == 'table' then id = id.id end
	local class = ''
	if property then
		class = 'wd_' .. string.lower(property)
	end
	local icon = '[[File:Blue pencil.svg|%s|10px|baseline|class=noviewer|link=%s]]'
	local title = i18n['see-wikidata-value']
	local url = mw.uri.fullUrl('d:' .. id, 'uselang=ur')
	url.fragment = property
	url = tostring(url)
	local v = mw.html.create('span')
		:addClass(class)
		:wikitext(str)
		:tag('span')
			:addClass('noprint wikidata-linkback')
			:css('padding-left', '0.5em')
			:wikitext(icon:format(title, url))
		:allDone()
	return tostring(v)
end

-- Function to check whether a certain item is a parent of a given item.
-- If pExitItem is reached without finding the searched parent item, the search stops.
-- A parent is connected via P31 or P279.
-- Attention: very intensive function, use carefully!
function isParent(property, pItem, pParent, pExitItem, pMaxDepth, pDepth)
	if not pDepth then pDepth = 0 end
	 	if not mw.wikibase then return false end
	local entity = mw.wikibase.getEntity(pItem)
	if not entity then return false end
	local claims31
	local claims279
	if entity.claims then 
		if property and property ~= '' then
			claims31 = entity.claims[property] 
		else
			claims31 = entity.claims['P31'] 
			claims279 = entity.claims['P279'] 
		end
	else
		return false
	end
	if not claims31 and not claims279 then return false end
	local parentIds = {}
		if claims31 and #claims31 > 0 then
			for i, v in ipairs(claims31) do parentIds[#parentIds+1] = p.getId(v.mainsnak) end
		end
		if claims279 and #claims279 > 0 then
			for i, v in ipairs(claims279) do parentIds[#parentIds+1] = p.getId(v.mainsnak) end
		end
	-- check if searched parent or exit item is reached or do recursive call
	if not parentIds[1] or #parentIds == 0 then return false end
	local itemString = ""
	local result = nil
	for i, qid in ipairs(parentIds) do
		if not qid then return false end
		--itemString = "Q" .. v
		itemString = qid
		if itemString == pParent then 
			-- successful!
			return true
		elseif itemString == pExitItem then --or itemString == "Q35120"  
			-- exit if either "exit item" or node item (Q35120) is reached
			return false
		else
			if pDepth+1 < pMaxDepth then
				result = isParent(property, itemString, pParent, pExitItem, pMaxDepth, pDepth+1)
			else return false end
			
			if result == true then return result end
		end
	end
	do return false end
end

function p.Subclass(options)
	if options then Frame_args = options end
	local parent = options.parent or ""
	local id = options.id or ""
	local Entity = getEntityFromId(id) 
	if Entity then id = Entity.id end
	local property = options.property or "P31"
	if parent == "" or id == "" or property == "" then return false end
	local tab = mw.text.split(options.parent,',')
	local result = mw.wikibase.getReferencedEntityId( id , property,  tab  ) -- { 'Q5', 'Q2095' } )
	if not result and property == "P31" then
		result = mw.wikibase.getReferencedEntityId( id , "P279" ,  tab  )
	end
	if result then return true end
end

function old_isSubclass(options)
	if not options.parent then return false end
	local maxDepth
	maxDepth = tonumber(options.maxDepth) or 10
	if not type(maxDepth) == "number" then maxDepth = 5 end
	property = options.property
	local result
	result = isParent(property, options.id, options.parent , options.exitItem, maxDepth)
	if options.returnInt then
		if result == true then return 1 else return nil end
	else
		return result
	end
end

function p.formatSnak( snak, options )
    return formatSnak( snak, options )
end

function p.getLabel( entity, lang )
     return labelIn( lang , entity )
end

function p.formatEntityId( entityId, options )
	return formatEntityId( entityId, (options or {}) )
end
 
function p.formatStatements( frame, key )
	if frame.args then
		if type(key)  == 'table' and key ~= {}  then else Frame_args = frame.args end
	end
 --[[ 
       The main function 
 ]] 
    local args = frame.args
    --If a value if already set, use it
    if args.value and args.value ~= '' then
        return args.value
    end
    local valuesnumb = 0
    local prop = formatStatements( args, key )
    if args.returnnumberofvalues then
        s , valuesnumb = formatStatements(  frame.args, key )
    end
	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.addTrackingCat and args.addTrackingCat ~= '' then   -- add tracking cat
		prop =  addTrackingCategory(prop,frame.args)
		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
    if args.returnnumberofvalues and args.returnnumberofvalues ~= "" then
		mw.log( "valuesnumb: " .. valuesnumb ) 
        return s , valuesnumb
    end
    return prop
end
function p.formatStatementsFromLua( options, key ) --  main function but to use from lua module
	if options then if type(key) == 'table' and key ~= {}  then else Frame_args = options end end
	
    --If a value if already set, use it
    if options.value and options.value ~= '' then
        return options.value
    end
    local valuesnumb = 0
    local s = formatStatements( options, key )
    if options.returnnumberofvalues and (options.returnnumberofvalues ~= "" or options.returnnumberofvalues == true ) then
        s , valuesnumb = formatStatements( options, key )
    end
    if s == '' then
    	s = nil
    end
	if s and s ~= '' then
    	if options.mainprefix and options.mainprefix ~= '' then -- mainprefix
    		s = options.mainprefix .. s
    	end
    	if options.mainsuffix and options.mainsuffix ~= '' then  -- mainsuffix
    		s = s .. options.mainsuffix
    	end
		if options.addTrackingCat and options.addTrackingCat ~= '' then   -- add tracking cat
			s = addTrackingCategory(s,options)
		end
		if options.mainsuffixAfterIcon and options.mainsuffixAfterIcon ~= '' then   -- another suffix but after wikidata icon
		s =  s .. options.mainsuffixAfterIcon 
		end
	else 
    	if options.NosValue and options.NosValue ~= '' then -- value if no local value and no wikidata value  
    		s = options.NosValue
    	end
	end
    if options.returnnumberofvalues and (options.returnnumberofvalues ~= "" or options.returnnumberofvalues == true ) then
	--	mw.log( "valuesnumb: " .. valuesnumb ) 
        return s , valuesnumb
    end
    return s
end

function p.isSubclass(frame)
	if frame.args then Frame_args = frame.args end
	return p.Subclass(frame.args)
end

-- Return the site link for a given data item and a given site (the current site by default) 

function p.getSiteLink( frame )
	if not mw.wikibase then return '' end
	if frame.args then Frame_args = frame.args end

	local site = frame.args[2] or frame.args.site
	local id = frame.args[1] or frame.args.id
	local count = frame.args.countsitelinks
	if not id or id == "" then
		if frame.args.page and frame.args.page ~= "" then
			id = mw.wikibase.getEntityIdForTitle( frame.args.page )
		end
	end
	if count and count ~= "" then 
		return countSiteLinks(id)
	end
    local link = sitelink( id , site )
    if link and link ~= ''  then
        return link
	end
end

function p.getSiteLink1(frame)
	if frame.args then Frame_args = frame.args end

	local project = frame.args[1] 
	local id = frame.args[2]
	local link = sitelink( id , project )
	var = link
	return var
end

-- returns the page id (Q...) of the current page or nothing of the page is not connected to Wikidata
function p.pageId(frame)
	return  mw.wikibase.getEntityIdForCurrentPage()
end

function p.descriptionIn(frame)
	if frame.args then Frame_args = frame.args end

	local langcode = frame.args[1] or frame.args["lang"]
	local id = frame.args[2]  or frame.args["id"]
	return descriptionIn( langcode ,id  )
end

function p.labelIn(frame)
	if frame.args then Frame_args = frame.args end

	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

function p.ViewSomething(frame)   -- from en:Module:Wikidata
	if frame.args then Frame_args = frame.args end

	local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
          if f.args.id and f.args.id ~='' then aa = f.args.id end
	local data = mw.wikibase.getEntityObject(aa)
	if not data then
		return nil
	end
	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			if type(data) == "table" then
				return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
			else
				return tostring(data)
			end
		end
		data = data[index] or data[tonumber(index)]
		if not data then
			return
		end
		i = i + 1
	end
end

function p.Dump(frame)
	if frame.args then Frame_args = frame.args end

	local f = (frame.args[1] or frame.args.id) and frame or frame:getParent()
          if f.args.id and f.args.id ~='' then aa = f.args.id end
	local data = mw.wikibase.getEntityObject(aa)
	if not data then
		return i18n.warnDump
	end
	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			return frame:extensionTag("source", mw.dumpObject(data),{ lang= 'lua'}).. i18n.warnDump
		end
		data = data[index] or data[tonumber(index)]
		if not data then
			return i18n.warnDump
		end
		i = i + 1
	end
end

function p.countSiteLinks(id)
	return countSiteLinks(id)
end

function p.EntityIdForTitle(frame)
	if frame.args then Frame_args = frame.args end

	local title = frame.args[1]
	local str = mw.wikibase.getEntityIdForTitle( title )
	--mw.log(str)
	return str
end

return p